feat: Spotify Importer — link → yt-dlp download + optional Navidrome playlist

- New 'Spotify Importer' page under Entdecken (sidebar + mobile nav)
- Backend: POST /api/spotify/resolve — resolves track/album/playlist URLs via Spotify API
- Backend: new 'playlist' download type accepting pre-resolved track list (no iTunes re-fetch)
- Frontend: paste Spotify link → preview with cover, type badge, track list
  - Track: single download or full album via iTunes fallback
  - Album: download all tracks with Spotify metadata
  - Playlist: download all tracks + optional 'Als Navidrome-Playlist speichern' checkbox
- Navidrome playlist creation: searches library by title/artist after download, creates playlist
- Spotify Client ID + Secret stored in app settings (setup screen + settings modal)
- iTunes metadata tags kept for all downloaded files (existing pipeline unchanged)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
HoneyandClaude Sonnet 4.6 committed 2026-04-27 00:56:11 +02:00
1 parent 9f68deea94
commit f7a5247f17
6 files changed
+398 -18

No files matched your search

+13 -10
View File
@@ -14,7 +14,7 @@ import {
navigate, _navGoBack, _navLoad, loadHomeData, onLocalSearch, onMobileSearch,
onGlobalSearch, s_goArtist, s_goAlbum, playerBarGoArtist, playerBarGoAlbum,
searchSimilarArtist, searchAndPreview, loadItunesAlbum, expandArtistBio,
loadRandom,
loadRandom, loadSpotifyImporter, resolveSpotifyLink, clearSpotifyPreview, spotifyDlAll,
} from './views.js';
import {
openNowPlaying, closeNowPlaying, switchNpTab, npGoArtist, npGoAlbum,
@@ -22,23 +22,25 @@ import {
checkBackend, openSidebar, closeSidebar, switchNavMode, showCtxMenu,
openPlModal, closePlModal, addSongsToPlaylist, createAndAddPlaylist,
createPlaylistPrompt, showSongInfo, closeInfoModal, openDlModal, closeDlModal,
selectDlType, executeDownload, openEditPlModal, closeEditPlModal,
selectDlType, executeDownload, executeSpotifyDownload, openEditPlModal, closeEditPlModal,
saveEditPlaylist, editPlUploadCover, editPlCoverSelected, editPlRemoveCover,
toggleMobileSearch, closeMobileSearch, switchSetupTab,
} from './ui.js';
// ─── CONNECT ───
async function doConnect() {
const url = document.getElementById('srv-url').value.trim().replace(/\/$/,'');
const user = document.getElementById('srv-user').value.trim();
const pass = document.getElementById('srv-pass').value;
const lfKey = document.getElementById('lastfm-key').value.trim();
const backUrl = document.getElementById('backend-url').value.trim().replace(/\/$/,'');
const url = document.getElementById('srv-url').value.trim().replace(/\/$/,'');
const user = document.getElementById('srv-user').value.trim();
const pass = document.getElementById('srv-pass').value;
const lfKey = document.getElementById('lastfm-key').value.trim();
const backUrl = document.getElementById('backend-url').value.trim().replace(/\/$/,'');
const spId = document.getElementById('spotify-client-id').value.trim();
const spSecret = document.getElementById('spotify-client-secret').value.trim();
if(!url || !user || !pass) { _showSetupError('Bitte Server-URL, Benutzernamen und Passwort ausfüllen.'); return; }
const btn = document.getElementById('btn-connect');
btn.disabled=true; btn.textContent='Verbinde…';
document.getElementById('setup-error').style.display='none';
S.cfg = {url, user, pass, lastfmKey:lfKey, backendUrl:backUrl};
S.cfg = {url, user, pass, lastfmKey:lfKey, backendUrl:backUrl, spotifyClientId:spId, spotifyClientSecret:spSecret};
try {
await api('ping');
localStorage.setItem('ns_cfg', JSON.stringify(S.cfg));
@@ -55,7 +57,7 @@ function disconnect() {
localStorage.removeItem('ns_cfg');
localStorage.removeItem('ns_last_played');
sessionStorage.removeItem('ns_nav');
S.cfg = {url:'', user:'', pass:'', lastfmKey:'', backendUrl:''};
S.cfg = {url:'', user:'', pass:'', lastfmKey:'', backendUrl:'', spotifyClientId:'', spotifyClientSecret:''};
S.queue=[]; S.qIdx=-1; S._navStack=[]; S._navCursor=-1;
S.audio.pause(); S.audio.src='';
document.getElementById('app').style.display='none';
@@ -183,7 +185,8 @@ Object.assign(window, {
openSettings, closeSettings, saveSettings, checkBackend,
openSidebar, closeSidebar, switchNavMode, showCtxMenu,
// Views
loadRandom,
loadRandom, loadSpotifyImporter, resolveSpotifyLink, clearSpotifyPreview, spotifyDlAll,
executeSpotifyDownload,
openPlModal, closePlModal, addSongsToPlaylist, createAndAddPlaylist, createPlaylistPrompt,
showSongInfo, closeInfoModal,
openDlModal, closeDlModal, selectDlType, executeDownload,
+1 -1
View File
@@ -1,6 +1,6 @@
// Shared mutable state — imported as { S } in every module
export const S = {
cfg: { url: '', user: '', pass: '', lastfmKey: '', backendUrl: '' },
cfg: { url: '', user: '', pass: '', lastfmKey: '', backendUrl: '', spotifyClientId: '', spotifyClientSecret: '' },
// Playback
queue: [],
+70 -4
View File
@@ -59,8 +59,10 @@ export function openSettings() {
document.getElementById('s-url').value = S.cfg.url || '';
document.getElementById('s-user').value = S.cfg.user || '';
document.getElementById('s-pass').value = '';
document.getElementById('s-lastfm').value = S.cfg.lastfmKey || '';
document.getElementById('s-backend').value = S.cfg.backendUrl || '';
document.getElementById('s-lastfm').value = S.cfg.lastfmKey || '';
document.getElementById('s-backend').value = S.cfg.backendUrl || '';
document.getElementById('s-spotify-id').value = S.cfg.spotifyClientId || '';
document.getElementById('s-spotify-secret').value = '';
document.getElementById('settings-modal').classList.add('open');
checkBackend();
}
@@ -70,8 +72,11 @@ export function saveSettings() {
S.cfg.url = document.getElementById('s-url').value.trim().replace(/\/$/,'');
S.cfg.user = document.getElementById('s-user').value.trim();
if(pass) S.cfg.pass = pass;
S.cfg.lastfmKey = document.getElementById('s-lastfm').value.trim();
S.cfg.backendUrl = document.getElementById('s-backend').value.trim().replace(/\/$/,'');
S.cfg.lastfmKey = document.getElementById('s-lastfm').value.trim();
S.cfg.backendUrl = document.getElementById('s-backend').value.trim().replace(/\/$/,'');
S.cfg.spotifyClientId = document.getElementById('s-spotify-id').value.trim();
const spSec = document.getElementById('s-spotify-secret').value;
if (spSec) S.cfg.spotifyClientSecret = spSec;
localStorage.setItem('ns_cfg', JSON.stringify(S.cfg));
closeSettings(); toast('✅ Gespeichert');
}
@@ -278,6 +283,67 @@ export async function executeDownload() {
}
}
// ─── SPOTIFY DOWNLOAD ───
export async function executeSpotifyDownload({ type, title, artist, artworkUrl, tracks, createPlaylist, playlistName }) {
if (!S.cfg.backendUrl) { toast('⚠ Kein Backend konfiguriert'); return; }
const jobId = 'job_' + Date.now();
addJob(jobId, title, artist);
try {
const res = await fetch(`${S.cfg.backendUrl}/api/download`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jobId, type, title, artist, artworkUrl, tracks }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
pollJob(jobId);
if (createPlaylist && playlistName && tracks?.length) {
_pollAndCreatePlaylist(jobId, tracks, playlistName);
}
} catch(e) {
updateJob(jobId, 'error', 'Backend-Verbindung fehlgeschlagen: ' + e.message);
toast('❌ Backend nicht erreichbar: ' + e.message);
}
}
async function _pollAndCreatePlaylist(jobId, tracks, playlistName) {
while (true) {
await new Promise(r => setTimeout(r, 2500));
const job = S.jobs[jobId];
if (!job || job.status === 'done' || job.status === 'error') break;
}
if (S.jobs[jobId]?.status !== 'done') return;
await _createNdPlaylist(tracks, playlistName);
}
async function _createNdPlaylist(tracks, name) {
try {
toast('🎵 Erstelle Navidrome-Playlist…');
const songIds = [];
const norm = s => s?.toLowerCase().trim() || '';
for (const t of tracks) {
if (!t.trackName) continue;
try {
const r = await api('search3', `&query=${encodeURIComponent(t.trackName)}&songCount=5&albumCount=0&artistCount=0`);
const songs = r.searchResult3?.song || [];
const match = songs.find(s =>
norm(s.title) === norm(t.trackName) &&
norm(s.artist).split(' ')[0] === norm(t.artistName).split(' ')[0]
) || songs.find(s => norm(s.title) === norm(t.trackName));
if (match) songIds.push(match.id);
} catch {}
}
if (!songIds.length) {
toast('⚠ Keine Tracks in Navidrome gefunden — zuerst Library scannen, dann Playlist manuell anlegen');
return;
}
const songParams = songIds.map(id => `&songId=${encodeURIComponent(id)}`).join('');
await api('createPlaylist', `&name=${encodeURIComponent(name)}${songParams}`);
toast(`✅ Playlist "${name}" mit ${songIds.length}/${tracks.length} Tracks erstellt`);
} catch(e) {
toast('Playlist-Erstellung fehlgeschlagen: ' + e.message);
}
}
// ─── JOBS ───
function addJob(id, title, artist) {
S.jobs[id] = {title, artist, progress:0, status:'pending'};
+139 -3
View File
@@ -26,12 +26,12 @@ export function _navLoad() {
export function navigate(page, data=null) {
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.querySelectorAll('.nav-item,.bnav-item').forEach(n => n.classList.remove('active','active-blue'));
const cls = ['discover','new-releases','recommendations'].includes(page) ? 'active-blue' : 'active';
const cls = ['discover','new-releases','recommendations','spotify-importer'].includes(page) ? 'active-blue' : 'active';
document.querySelectorAll(`[data-page="${page}"]`).forEach(el => el.classList.add(cls));
const pageEl = document.getElementById(`page-${page}`);
if(pageEl) { pageEl.classList.add('active'); document.getElementById('main-content').scrollTop = 0; }
closeSidebar();
if(['discover','new-releases','recommendations','random'].includes(page)) switchNavMode('discover');
if(['discover','new-releases','recommendations','random','spotify-importer'].includes(page)) switchNavMode('discover');
else if(['home','artists','albums','starred','playlists'].includes(page)) switchNavMode('library');
if(page==='artists' && !document.getElementById('artists-grid').children.length) loadArtists();
@@ -45,7 +45,8 @@ export function navigate(page, data=null) {
if(page==='new-releases') loadNewReleases();
if(page==='playlists') loadPlaylists();
if(page==='playlist-detail' && data) loadPlaylistDetail(data);
if(page==='recommendations') loadRecommendations();
if(page==='recommendations') loadRecommendations();
if(page==='spotify-importer') loadSpotifyImporter();
if(!S._navJumping) {
S._navStack = S._navStack.slice(0, S._navCursor + 1);
@@ -894,6 +895,141 @@ async function loadItunesFallbackRecommendations(el, artist, title, html) {
sec.appendChild(list); el.appendChild(sec);
}
// ─── SPOTIFY IMPORTER ───
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; }
if (!S.cfg.spotifyClientId) { toast('⚠ Spotify Client ID in Einstellungen eintragen'); return; }
if (!S.cfg.spotifyClientSecret) { toast('⚠ Spotify Client Secret in Einstellungen eintragen'); 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, clientId: S.cfg.spotifyClientId, clientSecret: S.cfg.spotifyClientSecret }),
});
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;
// Import executeSpotifyDownload from ui.js at call time (avoid circular at module level)
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 = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 16px"
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 herunterladen
</button>
<button class="btn-outline" style="font-size:12px;padding:9px 14px;margin-left:6px"
onclick="openDlModal({artistName:window._spotifyResolved.tracks[0].artistName,trackName:window._spotifyResolved.tracks[0].collectionName||window._spotifyResolved.tracks[0].trackName,collectionName:window._spotifyResolved.tracks[0].collectionName||'',artworkUrl100:window._spotifyResolved.tracks[0].artworkUrl100||window._spotifyResolved.artworkUrl||'',isAlbum:true})">
💿 Album
</button>`;
} else if (data.type === 'album') {
actionsHtml = `
<button class="btn-outline blue" style="font-size:13px;padding:9px 16px"
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:2px">
<label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;margin-bottom:8px">
<input type="checkbox" id="${plCbId}" style="width:15px;height:15px;accent-color:#1DB954" onchange="document.getElementById('${plCbId}_wrap').style.display=this.checked?'':'none'">
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 16px"
onclick="spotifyDlAll('${plCbId}','${plNmId}')">
⬇ Alle ${count} Tracks herunterladen
</button>
</div>`;
}
inner.innerHTML = `
<div style="display:flex;gap:16px;align-items:flex-start;background:var(--surface);border-radius:14px;padding:16px;margin-bottom:4px;border:1px solid var(--border)">
<div style="width:90px;height:90px;border-radius:10px;overflow:hidden;flex-shrink:0;background:var(--surface2)">
${art ? `<img src="${art}" style="width:100%;height:100%;object-fit:cover" onerror="this.parentNode.innerHTML='<div style=\\'width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:32px\\'>🎵</div>'">` : '<div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-size:32px">🎵</div>'}
</div>
<div style="flex:1;min-width:0">
<div style="font-size:11px;font-weight:600;color:#1DB954;text-transform:uppercase;letter-spacing:1px;margin-bottom:4px">${typeLabel}</div>
<div style="font-size:17px;font-weight:700;margin-bottom:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(data.name)}</div>
<div style="font-size:13px;color:var(--text2);margin-bottom:12px">${esc(data.artist)}${count > 1 ? ` · ${count} Tracks` : ''}</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 = '';
}
// ─── HELPERS ───
export function expandArtistBio() {
const el = document.getElementById('artist-bio-text');