Files
NovaSonic/src/spotify.js
T
HoneyandClaude Sonnet 4.6 2b6870583b fix: handle iTunes rate-limit empty responses, reduce Spotify artwork concurrency
- itunesSearch: use r.text() + JSON.parse so empty body (rate-limit) returns [] instead of throwing
- reduce Spotify artwork batch size 8→4 to avoid hammering iTunes and affecting global search

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 00:54:53 +02:00

207 lines
11 KiB
JavaScript

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 './components.js';
import { openDlModal } from './ui.js';
// ─── SPOTIFY IMPORTER PAGE ───
export function loadSpotifyImporter() {
if (!document.getElementById('spotify-link-input')?.value) {
const hint = document.getElementById('spotify-importer-hint');
const preview = document.getElementById('spotify-preview');
if (hint) hint.style.display = '';
if (preview) preview.style.display = 'none';
}
}
export function clearSpotifyPreview() {
if (!document.getElementById('spotify-link-input')?.value) {
const hint = document.getElementById('spotify-importer-hint');
const preview = document.getElementById('spotify-preview');
if (hint) hint.style.display = '';
if (preview) preview.style.display = 'none';
}
}
export async function resolveSpotifyLink() {
const url = document.getElementById('spotify-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 }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `HTTP ${res.status}`);
}
const data = await res.json();
window._spotifyResolved = data;
_renderSpotifyPreview(data);
} catch(e) {
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 via iTunes in the background
if ((data.type === 'playlist' || data.type === 'album') && count > 0 && S.cfg.backendUrl) {
_loadSpotifyTrackArtwork(data.tracks, list);
}
}
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;
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;
// Enrich track object so downloads get correct metadata
if (match.artworkUrl100) t.artworkUrl100 = match.artworkUrl100;
if (match.collectionName) t.collectionName = match.collectionName;
if (match.releaseDate) t.releaseDate = match.releaseDate;
if (match.trackNumber) t.trackNumber = match.trackNumber;
if (match.trackExplicitness) t.trackExplicitness = match.trackExplicitness;
if (window._spotifyResolved?.tracks?.[idx]) Object.assign(window._spotifyResolved.tracks[idx], t);
const url = match.artworkUrl100 || match.artworkUrl60 || '';
if (url) _setArt(artEls[idx], url);
} catch { /* non-critical */ }
}));
}
}
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);
}