refactor: restructure src into player/views/ui subfolders; fix notification skip buttons

- Move player.js + nowplaying.js → src/player/
- Move views.js + spotify/soundcloud/youtube/abs → src/views/
- Move ui.js + components.js → src/ui/
- Update all import paths (static + lazy) across every file
- MusicService: wrap ExoPlayer in ForwardingPlayer that always advertises
  next/prev commands so the notification skip buttons stay visible in radio
  mode even when the JS queue has only one native track

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
HoneyandClaude Sonnet 4.6 committed 2026-06-06 13:12:27 +02:00
1 parent d8908c69e9
commit 308a27d293
11 files changed
+78 -54

No files matched your search

+754
View File
@@ -0,0 +1,754 @@
import { S } from '../state.js';
import { esc, toast } from '../utils.js';
import { cancelMusicAutoplay } from '../player/player.js';
// ─── HTTP HELPERS ───
// API calls are routed through the NovaSonic backend proxy to avoid CORS restrictions.
// Audio streaming uses <audio src> directly (HTML media elements bypass CORS).
async function absRequest(method, path, body) {
const backend = S.cfg.backendUrl;
let url, headers;
if (backend) {
// Proxy through NovaSonic backend — no CORS issue
url = `${backend}/api/abs-proxy${path}`;
headers = {
'Content-Type': 'application/json',
'X-ABS-URL': S.abs.url,
'X-ABS-Token': S.abs.token || '',
};
} else {
// Direct — requires CORS to be configured on the ABS server
url = `${S.abs.url}${path}`;
headers = { 'Content-Type': 'application/json' };
if (S.abs.token) headers['Authorization'] = `Bearer ${S.abs.token}`;
}
const opts = { method, headers };
if (body !== undefined) opts.body = JSON.stringify(body);
const res = await fetch(url, opts);
if (!res.ok) {
const txt = await res.text().catch(() => '');
throw new Error(`ABS ${method} ${path}: HTTP ${res.status} ${txt.slice(0, 120)}`);
}
const txt = await res.text();
return txt ? JSON.parse(txt) : {};
}
const absGet = p => absRequest('GET', p);
const absPost = (p, b) => absRequest('POST', p, b);
const absPatch = (p, b) => absRequest('PATCH', p, b);
// ─── AUTH ───
export async function absVerifyApiKey(url, apiKey) {
S.abs.url = url.replace(/\/$/, '');
S.abs.token = apiKey;
// Verify by fetching current user — throws if token is invalid
const me = await absGet('/api/me');
S.abs.userId = me.id || null;
return me;
}
// ─── LIBRARIES ───
export async function absGetLibraries() {
const d = await absGet('/api/libraries');
return d.libraries || [];
}
export async function absGetItems(libId, { page = 0, limit = 100, search = '' } = {}) {
if (search) {
const d = await absGet(`/api/libraries/${libId}/search?q=${encodeURIComponent(search)}&limit=40`);
const items = (d.book || d.podcast || []).map(r => r.libraryItem || r);
return { items, total: items.length };
}
const d = await absGet(
`/api/libraries/${libId}/items?expanded=1&limit=${limit}&page=${page}` +
`&sort=media.metadata.title&asc=1&include=progress`
);
return { items: d.results || [], total: d.total || 0 };
}
export async function absGetItem(itemId) {
return absGet(`/api/items/${itemId}?expanded=1`);
}
export function absCoverUrl(itemId) {
if (!S.abs.token || !S.abs.url || !itemId) return null;
return `${S.abs.url}/api/items/${itemId}/cover?token=${encodeURIComponent(S.abs.token)}`;
}
// ─── PROGRESS ───
export async function absGetProgress(itemId) {
try { return await absGet(`/api/me/progress/${itemId}`); } catch { return null; }
}
async function absSaveProgress(itemId, currentTime, duration) {
if (!itemId || !S.abs.token) return;
try {
const progress = duration > 0 ? Math.min(1, currentTime / duration) : 0;
await absPatch(`/api/me/progress/${itemId}`, {
currentTime, duration, progress,
isFinished: progress >= 0.99,
lastUpdate: Date.now(),
});
} catch (e) { console.warn('ABS progress sync failed:', e.message); }
}
// ─── PLAYBACK SESSION ───
async function absStartSession(itemId) {
return absPost(`/api/items/${itemId}/play`, {
deviceInfo: { clientName: 'NovaSonic', clientVersion: '1.0' },
supportedMimeTypes: ['audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/ogg', 'audio/flac', 'audio/m4b'],
mediaPlayer: 'html5',
forceDirectPlay: true,
forceTranscode: false,
});
}
async function absCloseSession(sessionId) {
try { await absPost(`/api/session/${sessionId}/close`, {}); } catch {}
}
// ─── PLAYER INTERNALS ───
let _audio = null;
let _syncTimer = null;
let _absMiniVisible = false; // true = ABS bar covers the music player, only toggled on play start
let _sleepTimer = null;
let _sleepEndTime = null;
let _sleepTick = null;
function _getAudio() {
if (!_audio) {
_audio = document.getElementById('abs-audio');
_audio.addEventListener('timeupdate', _onTimeUpdate);
_audio.addEventListener('ended', _onTrackEnded);
_audio.addEventListener('play', () => { S.absPlayer.playing = true; _absMiniVisible = true; _renderControls(); _startSync(); });
_audio.addEventListener('pause', () => { S.absPlayer.playing = false; _renderControls(); _doSync(); });
}
return _audio;
}
function _globalTime() {
const ap = S.absPlayer;
const track = ap.audioTracks[ap.trackIdx];
return (track?.startOffset ?? 0) + (_audio?.currentTime ?? 0);
}
function _onTimeUpdate() {
const ap = S.absPlayer;
ap.currentTime = _globalTime();
_updateChapter();
_renderProgress();
}
function _onTrackEnded() {
const ap = S.absPlayer;
if (ap.trackIdx < ap.audioTracks.length - 1) {
ap.trackIdx++;
_loadTrack(ap.trackIdx, 0);
_audio.play().catch(() => {});
} else {
ap.playing = false;
_doSync(true);
_renderControls();
toast('📚 Hörbuch beendet');
}
}
function _loadTrack(idx, localOffset = 0) {
const ap = S.absPlayer;
const track = ap.audioTracks[idx];
if (!track) return;
ap.trackIdx = idx;
const sep = track.contentUrl.includes('?') ? '&' : '?';
_audio.src = `${S.abs.url}${track.contentUrl}${sep}token=${encodeURIComponent(S.abs.token)}`;
_audio.playbackRate = ap.speed;
_audio.currentTime = Math.max(0, localOffset);
}
function _findTrack(globalTime) {
const tracks = S.absPlayer.audioTracks;
if (!tracks.length) return { idx: 0, local: globalTime };
let idx = 0;
for (let i = 0; i < tracks.length; i++) {
if (globalTime >= tracks[i].startOffset) idx = i;
}
return { idx, local: Math.max(0, globalTime - (tracks[idx].startOffset ?? 0)) };
}
function _updateChapter() {
const ap = S.absPlayer;
if (!ap.chapters.length) return;
const t = ap.currentTime;
let idx = 0;
for (let i = 0; i < ap.chapters.length; i++) {
if (ap.chapters[i].start <= t) idx = i;
}
if (idx !== ap.chapterIdx) {
ap.chapterIdx = idx;
_renderChapterName();
_renderChapterList();
}
}
function _startSync() {
if (_syncTimer) return;
_syncTimer = setInterval(() => _doSync(), 30_000);
}
function _stopSync() { if (_syncTimer) { clearInterval(_syncTimer); _syncTimer = null; } }
function _doSync(finished = false) {
const ap = S.absPlayer;
if (ap.item) absSaveProgress(ap.item.id, ap.currentTime, ap.duration);
}
// ─── PUBLIC PLAYER ───
export async function absPlayItem(item) {
const ap = S.absPlayer;
const audio = _getAudio();
cancelMusicAutoplay(); // pause music + invalidate any stale canplay callbacks
if (ap._sessionId) { absCloseSession(ap._sessionId); ap._sessionId = null; }
_stopSync();
audio.pause();
toast('⏳ Lade Hörbuch…');
let session;
try {
session = await absStartSession(item.id);
} catch (e) {
toast(`❌ ${e.message}`);
return;
}
const tracks = session.audioTracks || [];
const chapters = session.chapters || item.media?.chapters || [];
const duration = tracks.reduce((s, t) => s + (t.duration ?? 0), 0) || (item.media?.duration ?? 0);
const saved = await absGetProgress(item.id);
const startTime = (saved?.currentTime && saved.currentTime > 10) ? saved.currentTime : 0;
ap.item = item;
ap._sessionId = session.id;
ap.audioTracks = tracks;
ap.chapters = chapters;
ap.duration = duration;
ap.currentTime = startTime;
ap.chapterIdx = -1;
ap.speed = ap.speed || 1.0;
if (tracks.length) {
const { idx, local } = _findTrack(startTime);
_loadTrack(idx, local);
} else if (item.media?.audioFiles?.[0]) {
const f = item.media.audioFiles[0];
_audio.src = `${S.abs.url}/api/items/${item.id}/file/${f.index ?? 0}?token=${encodeURIComponent(S.abs.token)}`;
_audio.playbackRate = ap.speed;
_audio.currentTime = startTime;
ap.duration = item.media.duration || 0;
}
_updateChapter();
absOpenPlayer();
_renderPlayer();
try { await audio.play(); } catch (e) { toast('Wiedergabe: ' + e.message); }
}
export function absTogglePlay() {
const audio = _getAudio();
if (S.absPlayer.playing) {
audio.pause();
} else {
if (S.audio && !S.audio.paused) S.audio.pause();
audio.play().catch(() => {});
}
}
export function absInterrupt() {
// Always hide the ABS bar when music takes over, regardless of ABS play state
if (_absMiniVisible) { _absMiniVisible = false; _renderMiniBar(); }
if (!S.absPlayer.item || !S.absPlayer.playing) return;
_getAudio().pause();
}
export function absSeek(globalTime) {
const ap = S.absPlayer;
globalTime = Math.max(0, Math.min(globalTime, ap.duration || Infinity));
ap.currentTime = globalTime;
if (ap.audioTracks.length) {
const { idx, local } = _findTrack(globalTime);
if (idx !== ap.trackIdx) {
_loadTrack(idx, local);
if (ap.playing) _audio.play().catch(() => {});
} else {
_audio.currentTime = local;
}
} else {
_getAudio().currentTime = globalTime;
}
_renderProgress();
}
export function absSkipSecs(secs) { absSeek(S.absPlayer.currentTime + secs); }
export function absNextChapter() {
const ap = S.absPlayer;
const next = ap.chapters[ap.chapterIdx + 1];
if (next) absSeek(next.start);
}
export function absPrevChapter() {
const ap = S.absPlayer;
const cur = ap.chapters[ap.chapterIdx];
if (cur && ap.currentTime - cur.start > 5) { absSeek(cur.start); return; }
const prev = ap.chapters[ap.chapterIdx - 1];
if (prev) absSeek(prev.start);
}
export function absSetSpeed(speed) {
S.absPlayer.speed = speed;
if (_audio) _audio.playbackRate = speed;
document.querySelectorAll('#abs-speed-picker button').forEach(b =>
b.classList.toggle('active', parseFloat(b.dataset.speed) === speed));
const lbl = document.getElementById('abs-speed-val');
if (lbl) lbl.textContent = `${speed}×`;
document.getElementById('abs-speed-picker')?.classList.remove('open');
}
export function absSleepIn(minutes) {
clearTimeout(_sleepTimer); clearInterval(_sleepTick);
_sleepTimer = null; _sleepTick = null; _sleepEndTime = null;
document.getElementById('abs-sleep-picker')?.classList.remove('open');
document.getElementById('abs-sleep-custom-row')?.classList.remove('active');
if (!minutes) { S.absPlayer.sleepRemaining = null; _renderSleepBtn(); return; }
_sleepEndTime = Date.now() + minutes * 60_000;
_updateSleepTick();
_sleepTimer = setTimeout(() => {
_getAudio().pause();
S.absPlayer.sleepRemaining = null; _sleepEndTime = null;
clearInterval(_sleepTick); _sleepTick = null;
_renderSleepBtn();
toast('😴 Sleep Timer: Pause');
}, minutes * 60_000);
_sleepTick = setInterval(_updateSleepTick, 1000);
_renderSleepBtn();
}
function _updateSleepTick() {
if (!_sleepEndTime) return;
S.absPlayer.sleepRemaining = Math.max(0, Math.round((_sleepEndTime - Date.now()) / 1000));
_renderSleepBtn();
}
// ─── OVERLAY ───
export function absOpenPlayer() {
S.absPlayer.open = true;
document.getElementById('abs-player')?.classList.add('open');
}
export function absClosePlayer() {
S.absPlayer.open = false;
document.getElementById('abs-player')?.classList.remove('open');
}
export function absToggleChapters() {
document.getElementById('abs-chapter-list')?.classList.toggle('open');
_renderChapterList();
}
export function absToggleSpeedPicker() {
document.getElementById('abs-sleep-picker')?.classList.remove('open');
document.getElementById('abs-speed-picker')?.classList.toggle('open');
}
export function absToggleSleepPicker() {
document.getElementById('abs-speed-picker')?.classList.remove('open');
document.getElementById('abs-sleep-picker')?.classList.toggle('open');
}
export function absSeekToChapter(idx) {
const ch = S.absPlayer.chapters[idx];
if (ch) absSeek(ch.start);
}
// ─── CHAPTER TRACK MODE ───
let _chapterTrackMode = localStorage.getItem('ns_abs_chtrack') === '1';
export function absToggleChapterTrack() {
_chapterTrackMode = !_chapterTrackMode;
localStorage.setItem('ns_abs_chtrack', _chapterTrackMode ? '1' : '0');
document.getElementById('abs-chtrack-btn')?.classList.toggle('active', _chapterTrackMode);
_renderProgress();
}
function _chapterWindow() {
const ap = S.absPlayer;
if (!_chapterTrackMode || ap.chapterIdx < 0 || !ap.chapters.length) return null;
const ch = ap.chapters[ap.chapterIdx];
if (!ch || ch.start == null) return null;
const nextCh = ap.chapters[ap.chapterIdx + 1];
const end = nextCh?.start ?? ch.end ?? ap.duration;
if (end <= ch.start) return null;
return { start: ch.start, end };
}
// ─── PROGRESS SCRUB ───
let _scrubbing = false;
export function absProgDown(e) { _scrubbing = true; _scrub(e); }
export function absProgMove(e) { if (_scrubbing) _scrub(e); }
export function absProgUp(e) { if (_scrubbing) { _scrubbing = false; _scrub(e); } }
function _scrub(e) {
const bar = document.getElementById('abs-prog-bar');
if (!bar) return;
const rect = bar.getBoundingClientRect();
const pct = Math.max(0, Math.min(1, ((e.touches?.[0]?.clientX ?? e.clientX) - rect.left) / rect.width));
const win = _chapterWindow();
absSeek(win ? win.start + pct * (win.end - win.start) : pct * S.absPlayer.duration);
}
// ─── RENDER HELPERS ───
function _renderMiniBar() {
const ap = S.absPlayer;
const bar = document.getElementById('abs-mini-bar');
if (!bar) return;
if (!ap.item || !_absMiniVisible) { bar.classList.remove('visible'); return; }
bar.classList.add('visible');
const meta = ap.item?.media?.metadata || {};
const cover = absCoverUrl(ap.item?.id);
const coverEl = document.getElementById('abs-mini-cover');
if (coverEl) {
coverEl.innerHTML = cover
? `<img src="${cover}" alt="" style="width:100%;height:100%;object-fit:cover;border-radius:6px" onerror="this.style.display='none'">`
: '📚';
}
const titleEl = document.getElementById('abs-mini-title');
if (titleEl) titleEl.textContent = meta.title || 'Unbekannt';
const ch = ap.chapters[ap.chapterIdx];
const chEl = document.getElementById('abs-mini-chapter');
if (chEl) chEl.textContent = ch?.title || meta.authorName || '';
const playBtn = document.getElementById('abs-mini-play');
if (playBtn) {
playBtn.innerHTML = ap.playing
? `<svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>`
: `<svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>`;
}
}
function _fmt(secs) {
if (!isFinite(secs) || secs < 0) secs = 0;
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = Math.floor(secs % 60);
return h > 0
? `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`
: `${m}:${String(s).padStart(2, '0')}`;
}
function _renderPlayer() {
const ap = S.absPlayer;
const meta = ap.item?.media?.metadata || {};
const cover = absCoverUrl(ap.item?.id);
const el = document.getElementById('abs-player');
if (!el) return;
const img = el.querySelector('#abs-cover');
if (img) { img.src = cover || ''; img.style.display = cover ? '' : 'none'; }
const pl = el.querySelector('#abs-cover-placeholder');
if (pl) pl.style.display = cover ? 'none' : 'flex';
el.querySelector('#abs-title').textContent = meta.title || 'Unbekannt';
el.querySelector('#abs-author').textContent = meta.authorName || '';
_renderProgress();
_renderControls();
_renderChapterName();
_renderSleepBtn();
_renderMiniBar();
document.getElementById('abs-chtrack-btn')?.classList.toggle('active', _chapterTrackMode);
}
function _renderProgress() {
const ap = S.absPlayer;
const win = _chapterWindow();
const dispCur = win ? Math.max(0, ap.currentTime - win.start) : ap.currentTime;
const dispDur = win ? win.end - win.start : ap.duration;
const pct = dispDur > 0 ? Math.min(100, (dispCur / dispDur) * 100) : 0;
const fill = document.getElementById('abs-prog-fill');
const thumb = document.getElementById('abs-prog-thumb');
if (fill) fill.style.width = `${pct}%`;
if (thumb) thumb.style.left = `${pct}%`;
const cur = document.getElementById('abs-time-cur');
const rem = document.getElementById('abs-time-rem');
if (cur) cur.textContent = _fmt(dispCur);
if (rem) rem.textContent = `-${_fmt(dispDur - dispCur)}`;
// mini bar strip always shows full-book progress
const miniPct = ap.duration > 0 ? Math.min(100, (ap.currentTime / ap.duration) * 100) : 0;
const miniFill = document.getElementById('abs-mini-prog-fill');
if (miniFill) miniFill.style.width = `${miniPct}%`;
}
function _renderControls() {
const ap = S.absPlayer;
const btn = document.getElementById('abs-playpause-btn');
if (!btn) return;
btn.innerHTML = ap.playing
? `<svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg>`
: `<svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>`;
const sv = document.getElementById('abs-speed-val');
if (sv) sv.textContent = `${ap.speed}×`;
_renderMiniBar();
}
function _renderChapterName() {
const ch = S.absPlayer.chapters[S.absPlayer.chapterIdx];
const el = document.getElementById('abs-chapter-name');
if (el) el.textContent = ch?.title || '';
_renderMiniBar();
}
function _renderChapterList() {
const ap = S.absPlayer;
const el = document.getElementById('abs-chapter-list');
if (!el || !el.classList.contains('open')) return;
el.innerHTML = ap.chapters.map((ch, i) => `
<div class="abs-ch-item${i === ap.chapterIdx ? ' active' : ''}" onclick="absSeekToChapter(${i})">
<span class="abs-ch-num">${i + 1}</span>
<span class="abs-ch-title">${esc(ch.title || `Kapitel ${i + 1}`)}</span>
<span class="abs-ch-start">${_fmt(ch.start)}</span>
</div>`).join('');
}
function _renderSleepBtn() {
const btn = document.getElementById('abs-sleep-btn');
if (!btn) return;
const rem = S.absPlayer.sleepRemaining;
const moonSvg = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>`;
if (rem != null) {
const m = Math.floor(rem / 60), s = String(rem % 60).padStart(2, '0');
btn.innerHTML = `${moonSvg}<span>${m}:${s}</span>`;
btn.classList.add('active');
} else {
btn.innerHTML = moonSvg;
btn.classList.remove('active');
}
}
// ─── BOOKS VIEW ───
export async function loadAbsBooks(libId, search = '') {
const grid = document.getElementById('abs-books-grid');
if (!grid) return;
grid.innerHTML = '<div class="abs-loading">Lade Bücher…</div>';
try {
const { items } = await absGetItems(libId, { search });
if (!items.length) {
grid.innerHTML = '<p class="abs-empty">Keine Bücher gefunden.</p>';
return;
}
grid.innerHTML = items.map(item => {
const meta = item.media?.metadata || {};
const cover = absCoverUrl(item.id);
const prog = item.userMediaProgress;
const pct = prog ? Math.round((prog.progress ?? 0) * 100) : 0;
return `
<div class="abs-book-card" onclick="absOpenBook('${item.id}')">
<div class="abs-book-cover-wrap">
${cover
? `<img src="${cover}" class="abs-book-cover" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">`
: ''}
<div class="abs-book-cover-ph" style="display:${cover ? 'none' : 'flex'}">📚</div>
${pct > 0 && pct < 99 ? `<div class="abs-book-prog-wrap"><div class="abs-book-prog-fill" style="width:${pct}%"></div></div>` : ''}
${pct >= 99 ? '<div class="abs-book-done">✓</div>' : ''}
</div>
<div class="abs-book-title">${esc(meta.title || 'Unbekannt')}</div>
<div class="abs-book-author">${esc(meta.authorName || '')}</div>
</div>`;
}).join('');
} catch (e) {
grid.innerHTML = `<p class="abs-error">Fehler: ${esc(e.message)}</p>`;
}
}
export function absOpenBook(itemId) {
const { navigate } = window;
navigate('abs-book-detail', { id: itemId });
}
export async function loadAbsBookDetail(itemId) {
const el = document.getElementById('abs-book-detail-content');
if (!el) return;
el.innerHTML = '<div class="abs-loading">Lade Buch…</div>';
try {
const [item, prog] = await Promise.all([absGetItem(itemId), absGetProgress(itemId)]);
window._absCurrentItem = item;
const meta = item.media?.metadata || {};
const cover = absCoverUrl(item.id);
const chapters = item.media?.chapters || [];
const duration = item.media?.duration ?? 0;
const curTime = prog?.currentTime ?? 0;
const pct = duration > 0 ? Math.round((curTime / duration) * 100) : 0;
el.innerHTML = `
<div class="abs-detail-header">
<div class="abs-detail-cover-wrap">
${cover
? `<img src="${cover}" class="abs-detail-cover" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">`
: ''}
<div class="abs-detail-cover-ph" style="display:${cover ? 'none' : 'flex'}">📚</div>
</div>
<div class="abs-detail-meta">
<h2 class="abs-detail-title">${esc(meta.title || 'Unbekannt')}</h2>
<div class="abs-detail-author">${esc(meta.authorName || '')}</div>
${meta.seriesName ? `<div class="abs-detail-series">${esc(meta.seriesName)}</div>` : ''}
${meta.publishedYear ? `<div class="abs-detail-year">${esc(String(meta.publishedYear))}</div>` : ''}
${duration ? `<div class="abs-detail-dur">${_fmt(duration)}</div>` : ''}
${pct > 0 ? `
<div class="abs-detail-progress-wrap">
<div class="abs-detail-progress-bar"><div style="width:${pct}%"></div></div>
<span>${pct}% gehört</span>
</div>` : ''}
<button class="abs-play-btn" onclick="absPlayItem(window._absCurrentItem)">
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
${curTime > 60 ? 'Weiterhören' : 'Abspielen'}
</button>
</div>
</div>
${meta.description ? `<div class="abs-detail-desc">${esc(meta.description)}</div>` : ''}
${chapters.length ? `
<div class="abs-detail-chapters">
<h3 class="abs-detail-chapters-title">Kapitel <span class="abs-ch-count">${chapters.length}</span></h3>
${chapters.map((ch, i) => `
<div class="abs-chapter-row" onclick="absPlayChapter(${ch.start})">
<span class="abs-ch-num">${i + 1}</span>
<span class="abs-ch-title">${esc(ch.title || `Kapitel ${i + 1}`)}</span>
<span class="abs-ch-start">${_fmt(ch.start)}</span>
</div>`).join('')}
</div>` : ''}`;
} catch (e) {
el.innerHTML = `<p class="abs-error">Fehler: ${esc(e.message)}</p>`;
}
}
export function absPlayChapter(startTime) {
if (!window._absCurrentItem) return;
absPlayItem(window._absCurrentItem).then(() => {
// Give audio time to load then seek
setTimeout(() => absSeek(startTime), 800);
});
}
// ─── SETTINGS ───
export function absInitFromStorage() {
try {
const d = JSON.parse(localStorage.getItem('ns_abs') || 'null');
if (d?.url && d?.token) {
S.abs.url = d.url;
S.abs.token = d.token;
S.abs.userId = d.userId || null;
S.abs.currentLibraryId = d.libId || null;
}
} catch {}
}
function absSaveToStorage() {
localStorage.setItem('ns_abs', JSON.stringify({
url: S.abs.url, token: S.abs.token,
userId: S.abs.userId, libId: S.abs.currentLibraryId,
}));
}
function _showAbsNavItem(show) {
document.getElementById('nav-abs-section')?.style && (document.getElementById('nav-abs-section').style.display = show ? '' : 'none');
const bnav = document.getElementById('bnav-audiobooks');
if (bnav) bnav.style.display = show ? '' : 'none';
}
function _setAbsStatusRow(state, msg) {
// state: 'connected' | 'error' | 'none'
const statusEl = document.getElementById('abs-s-status');
const dotEl = document.getElementById('abs-s-dot');
const btnEl = document.getElementById('abs-s-connect-btn');
if (statusEl) statusEl.textContent = msg || 'Nicht verbunden';
if (dotEl) {
dotEl.style.display = state === 'none' ? 'none' : 'block';
dotEl.className = 'status-dot' + (state === 'connected' ? ' ok' : state === 'error' ? ' err' : '');
}
if (btnEl) {
btnEl.disabled = false;
if (state === 'connected') {
btnEl.textContent = 'Trennen';
btnEl.style.color = 'var(--danger)';
btnEl.style.borderColor = 'rgba(224,85,85,0.3)';
} else {
btnEl.textContent = 'Verbinden';
btnEl.style.color = '';
btnEl.style.borderColor = '';
}
}
}
export function absOpenSettings() {
const urlEl = document.getElementById('abs-s-url');
if (urlEl) urlEl.value = S.abs.url || '';
if (S.abs.token) {
_setAbsStatusRow('connected', 'Verbunden · ' + (S.abs.url || ''));
} else {
_setAbsStatusRow('none', 'Nicht verbunden');
}
}
export function absToggleConnection() {
if (S.abs.token) absDisconnect(); else absConnectSettings();
}
export async function absConnectSettings() {
const url = document.getElementById('abs-s-url')?.value.trim().replace(/\/$/, '');
const apiKey = document.getElementById('abs-s-apikey')?.value.trim();
if (!url || !apiKey) { toast('❌ URL und API Key ausfüllen'); return; }
const btn = document.getElementById('abs-s-connect-btn');
if (btn) { btn.disabled = true; btn.textContent = 'Verbinde…'; }
try {
await absVerifyApiKey(url, apiKey);
const libs = await absGetLibraries();
if (!S.abs.currentLibraryId) S.abs.currentLibraryId = libs[0]?.id || null;
absSaveToStorage();
_renderLibPicker(libs);
_showAbsNavItem(true);
toast('✅ Audiobookshelf verbunden');
_setAbsStatusRow('connected', 'Verbunden · ' + url);
} catch (e) {
S.abs.token = null;
toast(`❌ ABS Verbindung fehlgeschlagen: ${e.message}`);
_setAbsStatusRow('error', 'Fehler: ' + e.message);
}
}
function _renderLibPicker(libs) {
const wrap = document.getElementById('abs-lib-picker');
if (!wrap) return;
wrap.style.display = libs.length > 1 ? '' : 'none';
const sel = wrap.querySelector('select');
if (sel) {
sel.innerHTML = libs.map(l =>
`<option value="${esc(l.id)}"${l.id === S.abs.currentLibraryId ? ' selected' : ''}>${esc(l.name)}</option>`
).join('');
}
}
export function absSetLibrary(libId) {
S.abs.currentLibraryId = libId;
absSaveToStorage();
}
export async function absLoadSettingsLibraries() {
if (!S.abs.token) return;
try {
const libs = await absGetLibraries();
_renderLibPicker(libs);
} catch {}
}
export function absDisconnect() {
S.abs.url = ''; S.abs.token = null;
S.abs.userId = null; S.abs.currentLibraryId = null;
localStorage.removeItem('ns_abs');
_showAbsNavItem(false);
toast('Audiobookshelf getrennt');
_setAbsStatusRow('none', 'Nicht verbunden');
}
+153
View File
@@ -0,0 +1,153 @@
import { S } from '../state.js';
import { esc, toast } from '../utils.js';
export function loadSoundCloudImporter() {
// Hint is managed by the unified importer input in spotify.js
}
export function clearSoundCloudPreview() {
// no-op — handled by onImporterInput
}
export async function resolveSoundCloudLink() {
const url = document.getElementById('sc-link-input')?.value.trim()
|| document.getElementById('importer-link-input')?.value.trim();
if (!url) return;
if (!url.includes('soundcloud.com')) { toast('⚠ Kein SoundCloud-Link'); return; }
if (!S.cfg.backendUrl) { toast('⚠ Backend URL in Einstellungen konfigurieren'); return; }
const preview = document.getElementById('sc-preview');
const inner = document.getElementById('sc-preview-inner');
const section = document.getElementById('sc-tracks-section');
preview.style.display = '';
section.style.display = 'none';
inner.innerHTML = '<div class="spinner"></div>';
try {
const res = await fetch(`${S.cfg.backendUrl}/api/soundcloud/resolve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
signal: AbortSignal.timeout(35000),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `HTTP ${res.status}`);
}
const data = await res.json();
window._scResolved = data;
_renderSoundCloudPreview(data);
} catch(e) {
if (e.name === 'TimeoutError' || e.name === 'AbortError') {
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">Zeitüberschreitung — Backend antwortet nicht. Läuft yt-dlp?</div>`;
return;
}
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">${esc(e.message)}</div>`;
}
}
export function scDlAll() {
const data = window._scResolved;
if (!data) return;
window.executeSpotifyDownload({
type: 'playlist',
title: data.name,
artist: data.artist,
artworkUrl: data.artworkUrl,
tracks: data.tracks,
});
}
export function scDlSingle() {
const data = window._scResolved;
if (!data?.tracks?.[0]) return;
const t = data.tracks[0];
window.executeSpotifyDownload({
type: 'track',
title: t.trackName,
artist: t.artistName,
artworkUrl: t.artworkUrl,
tracks: [t],
});
}
export function scDlTrack(idx) {
const data = window._scResolved;
const t = data?.tracks?.[idx];
if (!t) return;
window.executeSpotifyDownload({
type: 'track',
title: t.trackName,
artist: t.artistName,
artworkUrl: t.artworkUrl,
tracks: [t],
});
}
function _renderSoundCloudPreview(data) {
const inner = document.getElementById('sc-preview-inner');
const section = document.getElementById('sc-tracks-section');
const list = document.getElementById('sc-tracks-list');
const titleEl = document.getElementById('sc-tracks-title');
const count = data.tracks?.length || 0;
const art = data.artworkUrl || '';
let actionsHtml = '';
if (data.type === 'track' && count > 0) {
const t = data.tracks[0];
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600;margin-top:2px"
onclick="scDlSingle()">
⬇ Track laden
</button>`;
} else {
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600;margin-top:2px"
onclick="scDlAll()">
⬇ Alle ${count} Tracks laden
</button>`;
}
const artHtml = art
? `<img src="${art}" style="width:100%;height:100%;object-fit:cover" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">`
: '';
inner.innerHTML = `
<div style="display:flex;gap:16px;align-items:flex-start;background:var(--surface);border-radius:14px;padding:18px 16px;margin-bottom:4px;border:1px solid var(--border);border-top:3px solid #ff5500">
<div style="width:90px;height:90px;border-radius:10px;overflow:hidden;flex-shrink:0;background:var(--surface2);position:relative">
${artHtml}
<div style="width:100%;height:100%;display:${art ? 'none' : 'flex'};align-items:center;justify-content:center;font-size:32px;position:absolute;top:0;left:0">🎵</div>
</div>
<div style="flex:1;min-width:0">
<div style="font-size:10px;font-weight:700;color:#ff5500;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:5px">
SoundCloud ${data.type === 'playlist' ? 'Playlist' : 'Track'}
</div>
<div style="font-size:18px;font-weight:700;margin-bottom:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.2">${esc(data.name)}</div>
<div style="font-size:13px;color:var(--text2);margin-bottom:10px">${esc(data.artist)}${count > 1 ? `<span style="color:var(--text3)"> · ${count} Tracks</span>` : ''}</div>
${actionsHtml}
</div>
</div>`;
titleEl.textContent = `${count} Track${count !== 1 ? 's' : ''}`;
list.innerHTML = '';
(data.tracks || []).forEach((t, i) => {
const el = document.createElement('div');
el.className = 'gtrack-item';
const artT = t.artworkUrl || '';
el.innerHTML = `
<div class="gtrack-art">${artT ? `<img src="${artT}" loading="lazy">` : '<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:22px">🎵</div>'}</div>
<div class="gtrack-info">
<div class="gtrack-title">${esc(t.trackName || '—')}</div>
<div class="gtrack-sub">${esc(t.artistName || '—')}${t.genre ? ' · ' + esc(t.genre) : ''}${t.duration ? ' · ' + Math.round(t.duration / 60) + ' min' : ''}</div>
</div>
<div class="gtrack-actions">
<button class="icon-btn green" title="Herunterladen" onclick="event.stopPropagation();scDlTrack(${i})">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
</div>`;
list.appendChild(el);
});
section.style.display = '';
}
+365
View File
@@ -0,0 +1,365 @@
import { S } from '../state.js';
import { esc, toast } from '../utils.js';
import { itunesSearch } from '../api.js';
// Circular imports — safe (only used inside function bodies)
import { makeGlobalTrackItem } from '../ui/components.js';
import { openDlModal } from '../ui/ui.js';
// ─── UNIFIED IMPORTER INPUT ───
export function onImporterInput(val) {
// Always clear results when URL changes
document.getElementById('spotify-preview').style.display = 'none';
document.getElementById('sc-preview').style.display = 'none';
document.getElementById('yt-preview').style.display = 'none';
document.getElementById('importer-hint').style.display = val ? 'none' : '';
const badge = document.getElementById('importer-badge');
const btn = document.getElementById('importer-btn');
if (!badge || !btn) return;
if (val.includes('spotify.com')) {
badge.textContent = 'Spotify';
badge.style.background = 'rgba(29,185,84,.15)';
badge.style.color = '#1DB954';
btn.style.background = '#1DB954';
btn.style.color = '#000';
btn.style.borderColor = 'transparent';
} else if (val.includes('soundcloud.com')) {
badge.textContent = 'SoundCloud';
badge.style.background = 'rgba(255,85,0,.15)';
badge.style.color = '#ff5500';
btn.style.background = '#ff5500';
btn.style.color = '#fff';
btn.style.borderColor = 'transparent';
} else if (val.includes('youtube.com') || val.includes('youtu.be')) {
badge.textContent = 'YouTube';
badge.style.background = 'rgba(255,0,0,.15)';
badge.style.color = '#FF0000';
btn.style.background = '#FF0000';
btn.style.color = '#fff';
btn.style.borderColor = 'transparent';
} else {
badge.textContent = 'URL';
badge.style.background = '';
badge.style.color = '';
btn.style.background = '';
btn.style.color = '';
btn.style.borderColor = '';
}
}
export async function resolveImporterLink() {
const url = document.getElementById('importer-link-input')?.value.trim();
if (!url) return;
// Mirror to the hidden inputs so existing resolve functions pick it up
document.getElementById('spotify-link-input').value = url;
document.getElementById('sc-link-input').value = url;
document.getElementById('importer-hint').style.display = 'none';
if (url.includes('soundcloud.com')) {
window.resolveSoundCloudLink();
} else if (url.includes('youtube.com') || url.includes('youtu.be')) {
window.resolveYouTubeLink();
} else {
resolveSpotifyLink();
}
}
// ─── SPOTIFY IMPORTER PAGE ───
export function loadSpotifyImporter() {
const input = document.getElementById('importer-link-input');
if (!input?.value) {
document.getElementById('importer-hint').style.display = '';
document.getElementById('spotify-preview').style.display = 'none';
}
}
export function clearSpotifyPreview() {
// no-op — handled by onImporterInput
}
export async function resolveSpotifyLink() {
const url = document.getElementById('spotify-link-input')?.value.trim()
|| document.getElementById('importer-link-input')?.value.trim();
if (!url) return;
if (!S.cfg.backendUrl) { toast('⚠ Backend URL in Einstellungen konfigurieren'); return; }
const hint = document.getElementById('spotify-importer-hint');
const preview = document.getElementById('spotify-preview');
const inner = document.getElementById('spotify-preview-inner');
const section = document.getElementById('spotify-tracks-section');
if (hint) hint.style.display = 'none';
preview.style.display = '';
section.style.display = 'none';
inner.innerHTML = '<div class="spinner"></div>';
try {
const res = await fetch(`${S.cfg.backendUrl}/api/spotify/resolve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
signal: AbortSignal.timeout(30000),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
if (err.error === 'EDITORIAL_PLAYLIST') throw new Error('EDITORIAL_PLAYLIST');
if (err.error === 'RATE_LIMITED') throw new Error(`RATE_LIMITED:${err.retryAfter || 30}`);
throw new Error(err.error || err.message || `HTTP ${res.status}`);
}
const data = await res.json();
window._spotifyResolved = data;
if (data.skippedLocal > 0) toast(`${data.skippedLocal} lokale Datei(en) übersprungen (kein Stream verfügbar)`);
_renderSpotifyPreview(data);
} catch(e) {
if (e.name === 'TimeoutError' || e.name === 'AbortError') {
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">Zeitüberschreitung — der Server hat nicht rechtzeitig geantwortet. Läuft das Backend?</div>`;
return;
}
if (e.message.startsWith('RATE_LIMITED:')) {
const secs = parseInt(e.message.split(':')[1], 10) || 30;
_startRateLimitCountdown(inner, secs);
return;
}
if (e.message === 'EDITORIAL_PLAYLIST') {
inner.innerHTML = `<div style="padding:16px;background:var(--surface);border-radius:10px;border-left:3px solid #1DB954">
<div style="font-weight:600;margin-bottom:10px;color:#1DB954">💡 Editorial Playlist erkannt</div>
<div style="font-size:13px;line-height:1.6;color:var(--text2)">
Spotify hat den API-Zugriff auf eigene kuratierte Playlists
(wie "Today's Top Hits", "Discover Weekly" etc.) für Drittanbieter-Apps gesperrt.<br><br>
<strong style="color:var(--text)">Lösung:</strong>
<ol style="margin:8px 0 0 0;padding-left:20px">
<li>In Spotify die Playlist öffnen</li>
<li>Alle Tracks markieren (Strg+A)</li>
<li>Rechtsklick → "Zu Playlist hinzufügen" → "Neue Playlist"</li>
<li>Diese eigene Kopie hier importieren</li>
</ol>
</div>
</div>`;
return;
}
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">${esc(e.message)}</div>`;
}
}
export function spotifyDlAll(cbId, nameId) {
const data = window._spotifyResolved;
if (!data) return;
window.executeSpotifyDownload({
type: 'playlist',
title: document.getElementById(nameId)?.value || data.name,
artist: data.artist,
artworkUrl: data.artworkUrl,
tracks: data.tracks,
createPlaylist: document.getElementById(cbId)?.checked || false,
playlistName: document.getElementById(nameId)?.value || data.name,
});
}
function _renderSpotifyPreview(data) {
const inner = document.getElementById('spotify-preview-inner');
const section = document.getElementById('spotify-tracks-section');
const list = document.getElementById('spotify-tracks-list');
const titleEl = document.getElementById('spotify-tracks-title');
const typeLabel = { track: 'Spotify Track', album: 'Spotify Album', playlist: 'Spotify Playlist' }[data.type] || 'Spotify';
const art = (data.artworkUrl || '').replace(/\/\d+x\d+bb/, '/300x300bb').replace('100x100', '300x300');
const count = data.tracks?.length || 0;
const uid = Date.now();
const plCbId = `sp-cb-${uid}`, plNmId = `sp-pln-${uid}`;
let actionsHtml = '';
if (data.type === 'track' && count > 0) {
actionsHtml = `
<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:2px">
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600"
onclick="executeSpotifyDownload({type:'track',title:window._spotifyResolved.tracks[0].trackName,artist:window._spotifyResolved.tracks[0].artistName,artworkUrl:window._spotifyResolved.artworkUrl,tracks:window._spotifyResolved.tracks})">
⬇ Track laden
</button>
${data.tracks[0]?.collectionName ? `<button class="btn-outline" style="font-size:12px;padding:9px 14px"
onclick="openDlModal({artistName:window._spotifyResolved.tracks[0].artistName,trackName:window._spotifyResolved.tracks[0].collectionName,collectionName:window._spotifyResolved.tracks[0].collectionName,artworkUrl100:window._spotifyResolved.tracks[0].artworkUrl100||window._spotifyResolved.artworkUrl||'',isAlbum:true})">
💿 ${esc(data.tracks[0].collectionName)}
</button>` : ''}
</div>`;
} else if (data.type === 'album') {
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600;margin-top:2px"
onclick="executeSpotifyDownload({type:'playlist',title:window._spotifyResolved.name,artist:window._spotifyResolved.artist,artworkUrl:window._spotifyResolved.artworkUrl,tracks:window._spotifyResolved.tracks})">
⬇ Album laden (${count} Tracks)
</button>`;
} else if (data.type === 'playlist') {
actionsHtml = `
<div style="margin-top:6px">
<label id="${plCbId}_label" style="display:inline-flex;align-items:center;gap:8px;font-size:12px;cursor:pointer;margin-bottom:10px;background:var(--surface2);border:1px solid var(--border2);border-radius:20px;padding:6px 12px;transition:border-color .2s" onclick="void(0)">
<input type="checkbox" id="${plCbId}" style="width:14px;height:14px;accent-color:#1DB954;cursor:pointer" onchange="
document.getElementById('${plCbId}_wrap').style.display=this.checked?'':'none';
document.getElementById('${plCbId}_label').style.borderColor=this.checked?'#1DB954':'';
document.getElementById('${plCbId}_label').style.color=this.checked?'#1DB954':'';
">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>
Als Navidrome-Playlist speichern
</label>
<div id="${plCbId}_wrap" style="display:none;margin-bottom:10px">
<input type="text" id="${plNmId}" value="${esc(data.name)}" placeholder="Playlist-Name…"
style="background:var(--surface2);border:1px solid var(--border2);border-radius:8px;padding:8px 12px;font-size:13px;width:100%;box-sizing:border-box;color:var(--text);outline:none">
</div>
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600"
onclick="spotifyDlAll('${plCbId}','${plNmId}')">
⬇ Alle ${count} Tracks laden
</button>
</div>`;
}
const artSize = data.type === 'playlist' ? '80px' : '110px';
const artRadius = data.type === 'playlist' ? '8px' : '10px';
const artHtml = art
? `<img src="${art}" style="width:100%;height:100%;object-fit:cover" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">`
: '';
inner.innerHTML = `
<div style="display:flex;gap:16px;align-items:flex-start;background:var(--surface);border-radius:14px;padding:18px 16px;margin-bottom:4px;border:1px solid var(--border);border-top:3px solid #1DB954">
<div style="width:${artSize};height:${artSize};border-radius:${artRadius};overflow:hidden;flex-shrink:0;background:var(--surface2);position:relative">
${artHtml}
<div style="width:100%;height:100%;display:${art?'none':'flex'};align-items:center;justify-content:center;font-size:32px;position:absolute;top:0;left:0">🎵</div>
</div>
<div style="flex:1;min-width:0">
<div style="font-size:10px;font-weight:700;color:#1DB954;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:5px;display:flex;align-items:center;gap:5px">
<svg width="10" height="10" viewBox="0 0 24 24" fill="#1DB954"><circle cx="12" cy="12" r="10"/><path d="M8 11.973c2.5-1.473 5.5-.973 7.5.527M9.5 14.473c1.5-.973 3.5-.973 5 .027M7 9c3-1.5 6.5-1 9 1" stroke="#000" stroke-width="2" fill="none"/></svg>
${typeLabel}
</div>
<div style="font-size:18px;font-weight:700;margin-bottom:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:1.2">${esc(data.name)}</div>
<div style="font-size:13px;color:var(--text2);margin-bottom:10px">${esc(data.artist)}${count > 1 ? `<span style="color:var(--text3)"> · ${count} Tracks</span>` : ''}</div>
${actionsHtml}
</div>
</div>`;
titleEl.textContent = `${count} Tracks`;
list.innerHTML = '';
(data.tracks || []).forEach((t, i) => list.appendChild(makeGlobalTrackItem(t, i, data.tracks)));
section.style.display = '';
// Lazy-load correct per-track artwork and canonical names via iTunes in the background
if (count > 0 && S.cfg.backendUrl) {
_loadSpotifyTrackArtwork(data.tracks, list);
}
}
function _setEnrichStatus(done, current, total) {
const el = document.getElementById('spotify-enrich-status');
if (!el) return;
if (done) {
el.className = 'done';
el.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg> iTunes-Daten geladen';
el.style.display = 'flex';
el.style.opacity = '1';
setTimeout(() => {
el.style.opacity = '0';
setTimeout(() => { el.style.display = 'none'; el.className = ''; }, 400);
}, 2000);
} else {
el.className = '';
el.innerHTML = `<div class="enrich-spinner"></div> Lade iTunes-Daten… (${current}/${total})`;
el.style.display = 'flex';
el.style.opacity = '1';
}
}
async function _loadSpotifyTrackArtwork(tracks, listEl) {
const artEls = listEl.querySelectorAll('.gtrack-art');
// Show any Spotify artwork that's already present immediately
tracks.forEach((t, i) => {
const url = t.artworkUrl100 || t.artworkUrl60 || '';
if (!url) return;
const el = artEls[i];
if (!el) return;
_setArt(el, url);
});
// Enrich each track with iTunes data — same call as global search
const CONC = 4;
let enriched = 0;
_setEnrichStatus(false, 0, tracks.length);
for (let i = 0; i < tracks.length; i += CONC) {
const batch = tracks.slice(i, i + CONC);
await Promise.all(batch.map(async (t, bi) => {
const idx = i + bi;
try {
const firstArtist = (t.artistName || '').split(/\s*[,/•]\s*/)[0].trim();
const results = await itunesSearch(`${t.trackName} ${firstArtist}`, 'musicTrack', 1);
const match = results[0];
if (!match) return;
// Always safe to enrich: artwork, preview, explicit, iTunes artist name
if (match.artworkUrl100) t.artworkUrl100 = match.artworkUrl100;
if (match.trackExplicitness) t.trackExplicitness = match.trackExplicitness;
if (match.previewUrl) t.previewUrl = match.previewUrl;
// Store iTunes canonical name separately — keeps original Spotify/Japanese in artistName
// so the UI shows the original and YTM search uses the original channel name.
if (match.artistName) t.itunesArtistName = match.artistName;
// Only enrich album/duration if we're confident the iTunes match is the correct song.
// For Japanese titles we can't word-match, so we skip — the backend's lookupItunesTrackMeta
// handles it with better matching. For ASCII titles, require at least one shared word.
const JP_RE = /[ぁ-んァ-ン一-龯]/;
const isJapanese = JP_RE.test(t.trackName);
const _norm = s => new Set((s||'').toLowerCase().replace(/[^a-z0-9]/g,' ').split(/\s+/).filter(Boolean));
const titleMatch = !isJapanese && [..._norm(t.trackName)].some(w => _norm(match.trackName).has(w));
if (titleMatch) {
if (match.collectionName) t.collectionName = match.collectionName;
if (match.releaseDate) t.releaseDate = match.releaseDate;
if (match.trackNumber) t.trackNumber = match.trackNumber;
// Only use iTunes duration if it looks like a full song (> 30s) — jingles/previews
// returning a small trackTimeMillis would corrupt the yt-dlp duration filter.
if (match.trackTimeMillis > 30000) t.durationMs = match.trackTimeMillis;
}
if (window._spotifyResolved?.tracks?.[idx]) Object.assign(window._spotifyResolved.tracks[idx], t);
const url = match.artworkUrl100 || match.artworkUrl60 || '';
if (url) _setArt(artEls[idx], url);
if (match.previewUrl) {
const item = artEls[idx]?.closest('.gtrack-item');
if (item && !item.querySelector('.gtrack-actions .icon-btn.blue')) {
const actions = item.querySelector('.gtrack-actions');
if (actions) {
const btn = document.createElement('button');
btn.className = 'icon-btn blue';
btn.title = '30s Preview';
btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>';
btn.onclick = (e) => { e.stopPropagation(); window.playPreview(t); };
actions.insertBefore(btn, actions.firstChild);
item.onclick = () => window.playPreview(t);
}
}
}
} catch { /* non-critical */ }
enriched++;
_setEnrichStatus(false, enriched, tracks.length);
}));
}
_setEnrichStatus(true);
}
function _startRateLimitCountdown(inner, totalSecs) {
const endMs = Date.now() + totalSecs * 1000;
const render = (remaining) => {
const s = Math.max(0, Math.ceil(remaining / 1000));
const label = s >= 60 ? `${Math.ceil(s / 60)} Min.` : `${s}s`;
inner.innerHTML = `<div style="color:var(--text);padding:16px;background:var(--surface);border-radius:10px;border-left:3px solid var(--warning,#f59e0b)">
<div style="font-weight:600;margin-bottom:6px">⏳ Spotify Rate Limit</div>
<div style="font-size:13px;line-height:1.5;color:var(--text2)">
Bitte warte noch <strong id="sp-rl-countdown">${label}</strong> — nicht erneut versuchen, das setzt den Timer zurück.
</div>
</div>`;
};
render(totalSecs * 1000);
const iv = setInterval(() => {
const remaining = endMs - Date.now();
if (remaining <= 0) { clearInterval(iv); render(0); return; }
render(remaining);
}, 1000);
}
function _setArt(el, url) {
if (!el) return;
const img = document.createElement('img');
img.loading = 'lazy';
img.onerror = () => { el.innerHTML = '<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:22px">🎵</div>'; };
img.src = url;
el.innerHTML = ''; el.appendChild(img);
}
+1346
View File
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
import { S } from '../state.js';
import { esc, toast } from '../utils.js';
import { makeGlobalTrackItem } from '../ui/components.js';
export async function resolveYouTubeLink() {
const url = document.getElementById('importer-link-input')?.value.trim();
if (!url) return;
if (!S.cfg.backendUrl) { toast('⚠ Backend URL in Einstellungen konfigurieren'); return; }
const preview = document.getElementById('yt-preview');
const inner = document.getElementById('yt-preview-inner');
const section = document.getElementById('yt-tracks-section');
preview.style.display = '';
section.style.display = 'none';
inner.innerHTML = '<div class="spinner"></div>';
try {
const res = await fetch(`${S.cfg.backendUrl}/api/youtube/resolve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url }),
signal: AbortSignal.timeout(50000),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `HTTP ${res.status}`);
}
const data = await res.json();
window._ytResolved = data;
_renderYouTubePreview(data);
} catch (e) {
if (e.name === 'TimeoutError' || e.name === 'AbortError') {
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">Zeitüberschreitung — yt-dlp hat nicht rechtzeitig geantwortet.</div>`;
return;
}
inner.innerHTML = `<div style="color:var(--danger);padding:16px;background:var(--surface);border-radius:10px">${esc(e.message)}</div>`;
}
}
function _renderYouTubePreview(data) {
const inner = document.getElementById('yt-preview-inner');
const section = document.getElementById('yt-tracks-section');
const list = document.getElementById('yt-tracks-list');
const titleEl = document.getElementById('yt-tracks-title');
const typeLabel = data.type === 'playlist' ? 'YouTube Playlist' : 'YouTube';
const YT_RED = '#FF0000';
const art = (data.artworkUrl || '').replace(/\/hqdefault\.jpg/, '/maxresdefault.jpg');
const count = data.tracks?.length || 0;
let actionsHtml = '';
if (data.type === 'track' && count > 0) {
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600;margin-top:2px"
onclick="executeYouTubeDownload({type:'track',title:window._ytResolved.tracks[0].trackName,artist:window._ytResolved.tracks[0].artistName,artworkUrl:window._ytResolved.artworkUrl,tracks:window._ytResolved.tracks})">
⬇ Track laden
</button>`;
} else if (data.type === 'playlist') {
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 18px;font-weight:600;margin-top:2px"
onclick="executeYouTubeDownload({type:'playlist',title:window._ytResolved.name,artist:window._ytResolved.artist,artworkUrl:window._ytResolved.artworkUrl,tracks:window._ytResolved.tracks})">
⬇ Alle ${count} Tracks laden
</button>`;
}
const artHtml = art
? `<img src="${art}" style="width:100%;height:100%;object-fit:cover" onerror="this.style.display='none'">`
: '';
inner.innerHTML = `
<div style="display:flex;gap:16px;align-items:flex-start;background:var(--surface);border-radius:14px;padding:18px 16px;margin-bottom:4px;border:1px solid var(--border);border-top:3px solid ${YT_RED}">
<div style="width:110px;height:110px;border-radius:10px;overflow:hidden;flex-shrink:0;background:var(--surface2)">
${artHtml}
<div style="width:100%;height:100%;display:${art?'none':'flex'};align-items:center;justify-content:center;font-size:32px">▶</div>
</div>
<div style="flex:1;min-width:0">
<div style="font-size:10px;font-weight:700;color:${YT_RED};text-transform:uppercase;letter-spacing:1.5px;margin-bottom:5px">
${typeLabel}
</div>
<div style="font-size:18px;font-weight:700;margin-bottom:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(data.name)}</div>
<div style="font-size:13px;color:var(--text2);margin-bottom:10px">${esc(data.artist)}${count > 1 ? `<span style="color:var(--text3)"> · ${count} Tracks</span>` : ''}</div>
${actionsHtml}
</div>
</div>`;
if (count > 0) {
titleEl.textContent = `${count} Tracks`;
list.innerHTML = '';
(data.tracks || []).forEach((t, i) => list.appendChild(makeGlobalTrackItem(t, i, data.tracks)));
section.style.display = '';
}
}
export function executeYouTubeDownload(opts) {
if (!S.cfg.backendUrl) { toast('⚠ Kein Backend konfiguriert'); return; }
window.executeSpotifyDownload(opts);
}