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

+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);
}