polishing the edges
This commit is contained in:
@@ -1,372 +0,0 @@
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
// Define interfaces for API data
|
||||
interface Image {
|
||||
url: string;
|
||||
height?: number;
|
||||
width?: number;
|
||||
}
|
||||
|
||||
interface Artist {
|
||||
id: string;
|
||||
name: string;
|
||||
external_urls: {
|
||||
spotify: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface Track {
|
||||
id: string;
|
||||
name: string;
|
||||
artists: Artist[];
|
||||
duration_ms: number;
|
||||
explicit: boolean;
|
||||
external_urls: {
|
||||
spotify: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface Album {
|
||||
id: string;
|
||||
name: string;
|
||||
artists: Artist[];
|
||||
images: Image[];
|
||||
release_date: string;
|
||||
total_tracks: number;
|
||||
label: string;
|
||||
copyrights: { text: string; type: string }[];
|
||||
explicit: boolean;
|
||||
tracks: {
|
||||
items: Track[];
|
||||
// Add other properties from Spotify API if needed (e.g., total, limit, offset)
|
||||
};
|
||||
external_urls: {
|
||||
spotify: string;
|
||||
};
|
||||
// Add other album properties if available
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const pathSegments = window.location.pathname.split('/');
|
||||
const albumId = pathSegments[pathSegments.indexOf('album') + 1];
|
||||
|
||||
if (!albumId) {
|
||||
showError('No album ID provided.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch album info directly
|
||||
fetch(`/api/album/info?id=${encodeURIComponent(albumId)}`)
|
||||
.then(response => {
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
return response.json() as Promise<Album>; // Add Album type
|
||||
})
|
||||
.then(data => renderAlbum(data))
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showError('Failed to load album.');
|
||||
});
|
||||
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => {
|
||||
downloadQueue.toggleVisibility();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function renderAlbum(album: Album) {
|
||||
// Hide loading and error messages.
|
||||
const loadingEl = document.getElementById('loading');
|
||||
if (loadingEl) loadingEl.classList.add('hidden');
|
||||
|
||||
const errorSectionEl = document.getElementById('error'); // Renamed to avoid conflict with error var in catch
|
||||
if (errorSectionEl) errorSectionEl.classList.add('hidden');
|
||||
|
||||
// Check if album itself is marked explicit and filter is enabled
|
||||
const isExplicitFilterEnabled = downloadQueue.isExplicitFilterEnabled();
|
||||
if (isExplicitFilterEnabled && album.explicit) {
|
||||
// Show placeholder for explicit album
|
||||
const placeholderContent = `
|
||||
<div class="explicit-filter-placeholder">
|
||||
<h2>Explicit Content Filtered</h2>
|
||||
<p>This album contains explicit content and has been filtered based on your settings.</p>
|
||||
<p>The explicit content filter is controlled by environment variables.</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const contentContainer = document.getElementById('album-header');
|
||||
if (contentContainer) {
|
||||
contentContainer.innerHTML = placeholderContent;
|
||||
contentContainer.classList.remove('hidden');
|
||||
}
|
||||
|
||||
return; // Stop rendering the actual album content
|
||||
}
|
||||
|
||||
const baseUrl = window.location.origin;
|
||||
|
||||
// Set album header info.
|
||||
const albumNameEl = document.getElementById('album-name');
|
||||
if (albumNameEl) {
|
||||
albumNameEl.innerHTML =
|
||||
`<a href="${baseUrl}/album/${album.id || ''}">${album.name || 'Unknown Album'}</a>`;
|
||||
}
|
||||
|
||||
const albumArtistEl = document.getElementById('album-artist');
|
||||
if (albumArtistEl) {
|
||||
albumArtistEl.innerHTML =
|
||||
`By ${album.artists?.map(artist =>
|
||||
`<a href="${baseUrl}/artist/${artist?.id || ''}">${artist?.name || 'Unknown Artist'}</a>`
|
||||
).join(', ') || 'Unknown Artist'}`;
|
||||
}
|
||||
|
||||
const releaseYear = album.release_date ? new Date(album.release_date).getFullYear() : 'N/A';
|
||||
const albumStatsEl = document.getElementById('album-stats');
|
||||
if (albumStatsEl) {
|
||||
albumStatsEl.textContent =
|
||||
`${releaseYear} • ${album.total_tracks || '0'} songs • ${album.label || 'Unknown Label'}`;
|
||||
}
|
||||
|
||||
const albumCopyrightEl = document.getElementById('album-copyright');
|
||||
if (albumCopyrightEl) {
|
||||
albumCopyrightEl.textContent =
|
||||
album.copyrights?.map(c => c?.text || '').filter(text => text).join(' • ') || '';
|
||||
}
|
||||
|
||||
const imageSrc = album.images?.[0]?.url || '/static/images/placeholder.jpg';
|
||||
const albumImageEl = document.getElementById('album-image') as HTMLImageElement | null;
|
||||
if (albumImageEl) {
|
||||
albumImageEl.src = imageSrc;
|
||||
}
|
||||
|
||||
// Create (if needed) the Home Button.
|
||||
let homeButton = document.getElementById('homeButton') as HTMLButtonElement | null;
|
||||
if (!homeButton) {
|
||||
homeButton = document.createElement('button');
|
||||
homeButton.id = 'homeButton';
|
||||
homeButton.className = 'home-btn';
|
||||
|
||||
const homeIcon = document.createElement('img');
|
||||
homeIcon.src = '/static/images/home.svg';
|
||||
homeIcon.alt = 'Home';
|
||||
homeButton.appendChild(homeIcon);
|
||||
|
||||
// Insert as first child of album-header.
|
||||
const headerContainer = document.getElementById('album-header');
|
||||
if (headerContainer) { // Null check
|
||||
headerContainer.insertBefore(homeButton, headerContainer.firstChild);
|
||||
}
|
||||
}
|
||||
if (homeButton) { // Null check
|
||||
homeButton.addEventListener('click', () => {
|
||||
window.location.href = window.location.origin;
|
||||
});
|
||||
}
|
||||
|
||||
// Check if any track in the album is explicit when filter is enabled
|
||||
let hasExplicitTrack = false;
|
||||
if (isExplicitFilterEnabled && album.tracks?.items) {
|
||||
hasExplicitTrack = album.tracks.items.some(track => track && track.explicit);
|
||||
}
|
||||
|
||||
// Create (if needed) the Download Album Button.
|
||||
let downloadAlbumBtn = document.getElementById('downloadAlbumBtn') as HTMLButtonElement | null;
|
||||
if (!downloadAlbumBtn) {
|
||||
downloadAlbumBtn = document.createElement('button');
|
||||
downloadAlbumBtn.id = 'downloadAlbumBtn';
|
||||
downloadAlbumBtn.textContent = 'Download Full Album';
|
||||
downloadAlbumBtn.className = 'download-btn download-btn--main';
|
||||
const albumHeader = document.getElementById('album-header');
|
||||
if (albumHeader) albumHeader.appendChild(downloadAlbumBtn); // Null check
|
||||
}
|
||||
|
||||
if (downloadAlbumBtn) { // Null check for downloadAlbumBtn
|
||||
if (isExplicitFilterEnabled && hasExplicitTrack) {
|
||||
// Disable the album download button and display a message explaining why
|
||||
downloadAlbumBtn.disabled = true;
|
||||
downloadAlbumBtn.classList.add('download-btn--disabled');
|
||||
downloadAlbumBtn.innerHTML = `<span title="Cannot download entire album because it contains explicit tracks">Album Contains Explicit Tracks</span>`;
|
||||
} else {
|
||||
// Normal behavior when no explicit tracks are present
|
||||
downloadAlbumBtn.addEventListener('click', () => {
|
||||
// Remove any other download buttons (keeping the full-album button in place).
|
||||
document.querySelectorAll('.download-btn').forEach(btn => {
|
||||
if (btn.id !== 'downloadAlbumBtn') btn.remove();
|
||||
});
|
||||
|
||||
if (downloadAlbumBtn) { // Inner null check
|
||||
downloadAlbumBtn.disabled = true;
|
||||
downloadAlbumBtn.textContent = 'Queueing...';
|
||||
}
|
||||
|
||||
downloadWholeAlbum(album)
|
||||
.then(() => {
|
||||
if (downloadAlbumBtn) downloadAlbumBtn.textContent = 'Queued!'; // Inner null check
|
||||
})
|
||||
.catch(err => {
|
||||
showError('Failed to queue album download: ' + (err?.message || 'Unknown error'));
|
||||
if (downloadAlbumBtn) downloadAlbumBtn.disabled = false; // Inner null check
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Render each track.
|
||||
const tracksList = document.getElementById('tracks-list');
|
||||
if (tracksList) { // Null check
|
||||
tracksList.innerHTML = '';
|
||||
|
||||
if (album.tracks?.items) {
|
||||
album.tracks.items.forEach((track, index) => {
|
||||
if (!track) return; // Skip null or undefined tracks
|
||||
|
||||
// Skip explicit tracks if filter is enabled
|
||||
if (isExplicitFilterEnabled && track.explicit) {
|
||||
// Add a placeholder for filtered explicit tracks
|
||||
const trackElement = document.createElement('div');
|
||||
trackElement.className = 'track track-filtered';
|
||||
trackElement.innerHTML = `
|
||||
<div class="track-number">${index + 1}</div>
|
||||
<div class="track-info">
|
||||
<div class="track-name explicit-filtered">Explicit Content Filtered</div>
|
||||
<div class="track-artist">This track is not shown due to explicit content filter settings</div>
|
||||
</div>
|
||||
<div class="track-duration">--:--</div>
|
||||
`;
|
||||
tracksList.appendChild(trackElement);
|
||||
return;
|
||||
}
|
||||
|
||||
const trackElement = document.createElement('div');
|
||||
trackElement.className = 'track';
|
||||
trackElement.innerHTML = `
|
||||
<div class="track-number">${index + 1}</div>
|
||||
<div class="track-info">
|
||||
<div class="track-name">
|
||||
<a href="${baseUrl}/track/${track.id || ''}">${track.name || 'Unknown Track'}</a>
|
||||
</div>
|
||||
<div class="track-artist">
|
||||
${track.artists?.map(a =>
|
||||
`<a href="${baseUrl}/artist/${a?.id || ''}">${a?.name || 'Unknown Artist'}</a>`
|
||||
).join(', ') || 'Unknown Artist'}
|
||||
</div>
|
||||
</div>
|
||||
<div class="track-duration">${msToTime(track.duration_ms || 0)}</div>
|
||||
<button class="download-btn download-btn--circle"
|
||||
data-url="${track.external_urls?.spotify || ''}"
|
||||
data-type="track"
|
||||
data-name="${track.name || 'Unknown Track'}"
|
||||
title="Download">
|
||||
<img src="/static/images/download.svg" alt="Download">
|
||||
</button>
|
||||
`;
|
||||
tracksList.appendChild(trackElement);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Reveal header and track list.
|
||||
const albumHeaderEl = document.getElementById('album-header');
|
||||
if (albumHeaderEl) albumHeaderEl.classList.remove('hidden');
|
||||
|
||||
const tracksContainerEl = document.getElementById('tracks-container');
|
||||
if (tracksContainerEl) tracksContainerEl.classList.remove('hidden');
|
||||
attachDownloadListeners();
|
||||
|
||||
// If on a small screen, re-arrange the action buttons.
|
||||
if (window.innerWidth <= 480) {
|
||||
let actionsContainer = document.getElementById('album-actions');
|
||||
if (!actionsContainer) {
|
||||
actionsContainer = document.createElement('div');
|
||||
actionsContainer.id = 'album-actions';
|
||||
const albumHeader = document.getElementById('album-header');
|
||||
if (albumHeader) albumHeader.appendChild(actionsContainer); // Null check
|
||||
}
|
||||
if (actionsContainer) { // Null check for actionsContainer
|
||||
actionsContainer.innerHTML = ''; // Clear any previous content
|
||||
const homeBtn = document.getElementById('homeButton');
|
||||
if (homeBtn) actionsContainer.appendChild(homeBtn); // Null check
|
||||
|
||||
const dlAlbumBtn = document.getElementById('downloadAlbumBtn');
|
||||
if (dlAlbumBtn) actionsContainer.appendChild(dlAlbumBtn); // Null check
|
||||
|
||||
const queueToggle = document.querySelector('.queue-toggle');
|
||||
if (queueToggle) {
|
||||
actionsContainer.appendChild(queueToggle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadWholeAlbum(album: Album) {
|
||||
const url = album.external_urls?.spotify || '';
|
||||
if (!url) {
|
||||
throw new Error('Missing album URL');
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, 'album', { name: album.name || 'Unknown Album' });
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) { // Add type for error
|
||||
showError('Album download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function msToTime(duration: number): string {
|
||||
const minutes = Math.floor(duration / 60000);
|
||||
const seconds = ((duration % 60000) / 1000).toFixed(0);
|
||||
return `${minutes}:${seconds.padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function showError(message: string) {
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) { // Null check
|
||||
errorEl.textContent = message || 'An error occurred';
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function attachDownloadListeners() {
|
||||
document.querySelectorAll('.download-btn').forEach((btn) => {
|
||||
const button = btn as HTMLButtonElement; // Cast to HTMLButtonElement
|
||||
if (button.id === 'downloadAlbumBtn') return;
|
||||
button.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const currentTarget = e.currentTarget as HTMLButtonElement | null; // Cast currentTarget
|
||||
if (!currentTarget) return;
|
||||
|
||||
const url = currentTarget.dataset.url || '';
|
||||
const type = currentTarget.dataset.type || '';
|
||||
const name = currentTarget.dataset.name || extractName(url) || 'Unknown';
|
||||
// Remove the button immediately after click.
|
||||
currentTarget.remove();
|
||||
startDownload(url, type, { name }); // albumType will be undefined
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function startDownload(url: string, type: string, item: { name: string }, albumType?: string) { // Add types and make albumType optional
|
||||
if (!url) {
|
||||
showError('Missing URL for download');
|
||||
return Promise.reject(new Error('Missing URL for download')); // Return a rejected promise
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, type, item, albumType);
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) { // Add type for error
|
||||
showError('Download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function extractName(url: string | null | undefined): string { // Add type
|
||||
return url || 'Unknown';
|
||||
}
|
||||
@@ -1,460 +0,0 @@
|
||||
// Import the downloadQueue singleton
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
// Define interfaces for API data
|
||||
interface Image {
|
||||
url: string;
|
||||
height?: number;
|
||||
width?: number;
|
||||
}
|
||||
|
||||
interface Artist {
|
||||
id: string;
|
||||
name: string;
|
||||
external_urls: {
|
||||
spotify: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface Album {
|
||||
id: string;
|
||||
name: string;
|
||||
artists: Artist[];
|
||||
images: Image[];
|
||||
album_type: string; // "album", "single", "compilation"
|
||||
album_group?: string; // "album", "single", "compilation", "appears_on"
|
||||
external_urls: {
|
||||
spotify: string;
|
||||
};
|
||||
explicit?: boolean; // Added to handle explicit filter
|
||||
total_tracks?: number;
|
||||
release_date?: string;
|
||||
}
|
||||
|
||||
interface ArtistData {
|
||||
items: Album[];
|
||||
total: number;
|
||||
// Add other properties if available from the API
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const pathSegments = window.location.pathname.split('/');
|
||||
const artistId = pathSegments[pathSegments.indexOf('artist') + 1];
|
||||
|
||||
if (!artistId) {
|
||||
showError('No artist ID provided.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch artist info directly
|
||||
fetch(`/api/artist/info?id=${encodeURIComponent(artistId)}`)
|
||||
.then(response => {
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
return response.json() as Promise<ArtistData>;
|
||||
})
|
||||
.then(data => renderArtist(data, artistId))
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showError('Failed to load artist info.');
|
||||
});
|
||||
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => downloadQueue.toggleVisibility());
|
||||
}
|
||||
});
|
||||
|
||||
function renderArtist(artistData: ArtistData, artistId: string) {
|
||||
const loadingEl = document.getElementById('loading');
|
||||
if (loadingEl) loadingEl.classList.add('hidden');
|
||||
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) errorEl.classList.add('hidden');
|
||||
|
||||
// Check if explicit filter is enabled
|
||||
const isExplicitFilterEnabled = downloadQueue.isExplicitFilterEnabled();
|
||||
|
||||
const firstAlbum = artistData.items?.[0];
|
||||
const artistName = firstAlbum?.artists?.[0]?.name || 'Unknown Artist';
|
||||
const artistImageSrc = firstAlbum?.images?.[0]?.url || '/static/images/placeholder.jpg';
|
||||
|
||||
const artistNameEl = document.getElementById('artist-name');
|
||||
if (artistNameEl) {
|
||||
artistNameEl.innerHTML =
|
||||
`<a href="/artist/${artistId}" class="artist-link">${artistName}</a>`;
|
||||
}
|
||||
const artistStatsEl = document.getElementById('artist-stats');
|
||||
if (artistStatsEl) {
|
||||
artistStatsEl.textContent = `${artistData.total || '0'} albums`;
|
||||
}
|
||||
const artistImageEl = document.getElementById('artist-image') as HTMLImageElement | null;
|
||||
if (artistImageEl) {
|
||||
artistImageEl.src = artistImageSrc;
|
||||
}
|
||||
|
||||
// Define the artist URL (used by both full-discography and group downloads)
|
||||
const artistUrl = `https://open.spotify.com/artist/${artistId}`;
|
||||
|
||||
// Home Button
|
||||
let homeButton = document.getElementById('homeButton') as HTMLButtonElement | null;
|
||||
if (!homeButton) {
|
||||
homeButton = document.createElement('button');
|
||||
homeButton.id = 'homeButton';
|
||||
homeButton.className = 'home-btn';
|
||||
homeButton.innerHTML = `<img src="/static/images/home.svg" alt="Home">`;
|
||||
const artistHeader = document.getElementById('artist-header');
|
||||
if (artistHeader) artistHeader.prepend(homeButton);
|
||||
}
|
||||
if (homeButton) {
|
||||
homeButton.addEventListener('click', () => window.location.href = window.location.origin);
|
||||
}
|
||||
|
||||
// Download Whole Artist Button using the new artist API endpoint
|
||||
let downloadArtistBtn = document.getElementById('downloadArtistBtn') as HTMLButtonElement | null;
|
||||
if (!downloadArtistBtn) {
|
||||
downloadArtistBtn = document.createElement('button');
|
||||
downloadArtistBtn.id = 'downloadArtistBtn';
|
||||
downloadArtistBtn.className = 'download-btn download-btn--main';
|
||||
downloadArtistBtn.textContent = 'Download All Discography';
|
||||
const artistHeader = document.getElementById('artist-header');
|
||||
if (artistHeader) artistHeader.appendChild(downloadArtistBtn);
|
||||
}
|
||||
|
||||
// When explicit filter is enabled, disable all download buttons
|
||||
if (isExplicitFilterEnabled) {
|
||||
if (downloadArtistBtn) {
|
||||
// Disable the artist download button and display a message explaining why
|
||||
downloadArtistBtn.disabled = true;
|
||||
downloadArtistBtn.classList.add('download-btn--disabled');
|
||||
downloadArtistBtn.innerHTML = `<span title="Direct artist downloads are restricted when explicit filter is enabled. Please visit individual album pages.">Downloads Restricted</span>`;
|
||||
}
|
||||
} else {
|
||||
// Normal behavior when explicit filter is not enabled
|
||||
if (downloadArtistBtn) {
|
||||
downloadArtistBtn.addEventListener('click', () => {
|
||||
// Optionally remove other download buttons from individual albums.
|
||||
document.querySelectorAll('.download-btn:not(#downloadArtistBtn)').forEach(btn => btn.remove());
|
||||
if (downloadArtistBtn) {
|
||||
downloadArtistBtn.disabled = true;
|
||||
downloadArtistBtn.textContent = 'Queueing...';
|
||||
}
|
||||
|
||||
// Queue the entire discography (albums, singles, compilations, and appears_on)
|
||||
// Use our local startDownload function instead of downloadQueue.startArtistDownload
|
||||
startDownload(
|
||||
artistUrl,
|
||||
'artist',
|
||||
{ name: artistName, artist: artistName },
|
||||
'album,single,compilation,appears_on'
|
||||
)
|
||||
.then((taskIds) => {
|
||||
if (downloadArtistBtn) {
|
||||
downloadArtistBtn.textContent = 'Artist queued';
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
|
||||
// Optionally show number of albums queued
|
||||
if (Array.isArray(taskIds)) {
|
||||
downloadArtistBtn.title = `${taskIds.length} albums queued for download`;
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
if (downloadArtistBtn) {
|
||||
downloadArtistBtn.textContent = 'Download All Discography';
|
||||
downloadArtistBtn.disabled = false;
|
||||
}
|
||||
showError('Failed to queue artist download: ' + (err?.message || 'Unknown error'));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Group albums by type (album, single, compilation, etc.) and separate "appears_on" albums
|
||||
const albumGroups: Record<string, Album[]> = {};
|
||||
const appearingAlbums: Album[] = [];
|
||||
|
||||
(artistData.items || []).forEach(album => {
|
||||
if (!album) return;
|
||||
|
||||
// Skip explicit albums if filter is enabled
|
||||
if (isExplicitFilterEnabled && album.explicit) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is an "appears_on" album
|
||||
if (album.album_group === 'appears_on') {
|
||||
appearingAlbums.push(album);
|
||||
} else {
|
||||
// Group by album_type for the artist's own releases
|
||||
const type = (album.album_type || 'unknown').toLowerCase();
|
||||
if (!albumGroups[type]) albumGroups[type] = [];
|
||||
albumGroups[type].push(album);
|
||||
}
|
||||
});
|
||||
|
||||
// Render album groups
|
||||
const groupsContainer = document.getElementById('album-groups');
|
||||
if (groupsContainer) {
|
||||
groupsContainer.innerHTML = '';
|
||||
|
||||
// Render regular album groups first
|
||||
for (const [groupType, albums] of Object.entries(albumGroups)) {
|
||||
const groupSection = document.createElement('section');
|
||||
groupSection.className = 'album-group';
|
||||
|
||||
// If explicit filter is enabled, don't show the group download button
|
||||
const groupHeaderHTML = isExplicitFilterEnabled ?
|
||||
`<div class="album-group-header">
|
||||
<h3>${capitalize(groupType)}s</h3>
|
||||
<div class="download-note">Visit album pages to download content</div>
|
||||
</div>` :
|
||||
`<div class="album-group-header">
|
||||
<h3>${capitalize(groupType)}s</h3>
|
||||
<button class="download-btn download-btn--main group-download-btn"
|
||||
data-group-type="${groupType}">
|
||||
Download All ${capitalize(groupType)}s
|
||||
</button>
|
||||
</div>`;
|
||||
|
||||
groupSection.innerHTML = `
|
||||
${groupHeaderHTML}
|
||||
<div class="albums-list"></div>
|
||||
`;
|
||||
|
||||
const albumsContainer = groupSection.querySelector('.albums-list');
|
||||
if (albumsContainer) {
|
||||
albums.forEach(album => {
|
||||
if (!album) return;
|
||||
|
||||
const albumElement = document.createElement('div');
|
||||
albumElement.className = 'album-card';
|
||||
|
||||
// Create album card with or without download button based on explicit filter setting
|
||||
if (isExplicitFilterEnabled) {
|
||||
albumElement.innerHTML = `
|
||||
<a href="/album/${album.id || ''}" class="album-link">
|
||||
<img src="${album.images?.[1]?.url || album.images?.[0]?.url || '/static/images/placeholder.jpg'}"
|
||||
alt="Album cover"
|
||||
class="album-cover">
|
||||
</a>
|
||||
<div class="album-info">
|
||||
<div class="album-title">${album.name || 'Unknown Album'}</div>
|
||||
<div class="album-artist">${album.artists?.map(a => a?.name || 'Unknown Artist').join(', ') || 'Unknown Artist'}</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
albumElement.innerHTML = `
|
||||
<a href="/album/${album.id || ''}" class="album-link">
|
||||
<img src="${album.images?.[1]?.url || album.images?.[0]?.url || '/static/images/placeholder.jpg'}"
|
||||
alt="Album cover"
|
||||
class="album-cover">
|
||||
</a>
|
||||
<div class="album-info">
|
||||
<div class="album-title">${album.name || 'Unknown Album'}</div>
|
||||
<div class="album-artist">${album.artists?.map(a => a?.name || 'Unknown Artist').join(', ') || 'Unknown Artist'}</div>
|
||||
</div>
|
||||
<button class="download-btn download-btn--circle"
|
||||
data-url="${album.external_urls?.spotify || ''}"
|
||||
data-type="${album.album_type || 'album'}"
|
||||
data-name="${album.name || 'Unknown Album'}"
|
||||
title="Download">
|
||||
<img src="/static/images/download.svg" alt="Download">
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
albumsContainer.appendChild(albumElement);
|
||||
});
|
||||
}
|
||||
|
||||
groupsContainer.appendChild(groupSection);
|
||||
}
|
||||
|
||||
// Render "Featuring" section if there are any appearing albums
|
||||
if (appearingAlbums.length > 0) {
|
||||
const featuringSection = document.createElement('section');
|
||||
featuringSection.className = 'album-group';
|
||||
|
||||
const featuringHeaderHTML = isExplicitFilterEnabled ?
|
||||
`<div class="album-group-header">
|
||||
<h3>Featuring</h3>
|
||||
<div class="download-note">Visit album pages to download content</div>
|
||||
</div>` :
|
||||
`<div class="album-group-header">
|
||||
<h3>Featuring</h3>
|
||||
<button class="download-btn download-btn--main group-download-btn"
|
||||
data-group-type="appears_on">
|
||||
Download All Featuring Albums
|
||||
</button>
|
||||
</div>`;
|
||||
|
||||
featuringSection.innerHTML = `
|
||||
${featuringHeaderHTML}
|
||||
<div class="albums-list"></div>
|
||||
`;
|
||||
|
||||
const albumsContainer = featuringSection.querySelector('.albums-list');
|
||||
if (albumsContainer) {
|
||||
appearingAlbums.forEach(album => {
|
||||
if (!album) return;
|
||||
|
||||
const albumElement = document.createElement('div');
|
||||
albumElement.className = 'album-card';
|
||||
|
||||
// Create album card with or without download button based on explicit filter setting
|
||||
if (isExplicitFilterEnabled) {
|
||||
albumElement.innerHTML = `
|
||||
<a href="/album/${album.id || ''}" class="album-link">
|
||||
<img src="${album.images?.[1]?.url || album.images?.[0]?.url || '/static/images/placeholder.jpg'}"
|
||||
alt="Album cover"
|
||||
class="album-cover">
|
||||
</a>
|
||||
<div class="album-info">
|
||||
<div class="album-title">${album.name || 'Unknown Album'}</div>
|
||||
<div class="album-artist">${album.artists?.map(a => a?.name || 'Unknown Artist').join(', ') || 'Unknown Artist'}</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
albumElement.innerHTML = `
|
||||
<a href="/album/${album.id || ''}" class="album-link">
|
||||
<img src="${album.images?.[1]?.url || album.images?.[0]?.url || '/static/images/placeholder.jpg'}"
|
||||
alt="Album cover"
|
||||
class="album-cover">
|
||||
</a>
|
||||
<div class="album-info">
|
||||
<div class="album-title">${album.name || 'Unknown Album'}</div>
|
||||
<div class="album-artist">${album.artists?.map(a => a?.name || 'Unknown Artist').join(', ') || 'Unknown Artist'}</div>
|
||||
</div>
|
||||
<button class="download-btn download-btn--circle"
|
||||
data-url="${album.external_urls?.spotify || ''}"
|
||||
data-type="${album.album_type || 'album'}"
|
||||
data-name="${album.name || 'Unknown Album'}"
|
||||
title="Download">
|
||||
<img src="/static/images/download.svg" alt="Download">
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
albumsContainer.appendChild(albumElement);
|
||||
});
|
||||
}
|
||||
|
||||
// Add to the end so it appears at the bottom
|
||||
groupsContainer.appendChild(featuringSection);
|
||||
}
|
||||
}
|
||||
|
||||
const artistHeaderEl = document.getElementById('artist-header');
|
||||
if (artistHeaderEl) artistHeaderEl.classList.remove('hidden');
|
||||
|
||||
const albumsContainerEl = document.getElementById('albums-container');
|
||||
if (albumsContainerEl) albumsContainerEl.classList.remove('hidden');
|
||||
|
||||
// Only attach download listeners if explicit filter is not enabled
|
||||
if (!isExplicitFilterEnabled) {
|
||||
attachDownloadListeners();
|
||||
// Pass the artist URL and name so the group buttons can use the artist download function
|
||||
attachGroupDownloadListeners(artistUrl, artistName);
|
||||
}
|
||||
}
|
||||
|
||||
// Event listeners for group downloads using the artist download function
|
||||
function attachGroupDownloadListeners(artistUrl: string, artistName: string) {
|
||||
document.querySelectorAll('.group-download-btn').forEach(btn => {
|
||||
const button = btn as HTMLButtonElement; // Cast to HTMLButtonElement
|
||||
button.addEventListener('click', async (e) => {
|
||||
const target = e.target as HTMLButtonElement | null; // Cast target
|
||||
if (!target) return;
|
||||
|
||||
const groupType = target.dataset.groupType || 'album'; // e.g. "album", "single", "compilation", "appears_on"
|
||||
target.disabled = true;
|
||||
|
||||
// Custom text for the 'appears_on' group
|
||||
const displayType = groupType === 'appears_on' ? 'Featuring Albums' : `${capitalize(groupType)}s`;
|
||||
target.textContent = `Queueing all ${displayType}...`;
|
||||
|
||||
try {
|
||||
// Use our local startDownload function with the group type filter
|
||||
const taskIds = await startDownload(
|
||||
artistUrl,
|
||||
'artist',
|
||||
{ name: artistName || 'Unknown Artist', artist: artistName || 'Unknown Artist' },
|
||||
groupType // Only queue releases of this specific type.
|
||||
);
|
||||
|
||||
// Optionally show number of albums queued
|
||||
const totalQueued = Array.isArray(taskIds) ? taskIds.length : 0;
|
||||
target.textContent = `Queued all ${displayType}`;
|
||||
target.title = `${totalQueued} albums queued for download`;
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) { // Add type for error
|
||||
target.textContent = `Download All ${displayType}`;
|
||||
target.disabled = false;
|
||||
showError(`Failed to queue download for all ${groupType}: ${error?.message || 'Unknown error'}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Individual download handlers remain unchanged.
|
||||
function attachDownloadListeners() {
|
||||
document.querySelectorAll('.download-btn:not(.group-download-btn)').forEach(btn => {
|
||||
const button = btn as HTMLButtonElement; // Cast to HTMLButtonElement
|
||||
button.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
const currentTarget = e.currentTarget as HTMLButtonElement | null; // Cast currentTarget
|
||||
if (!currentTarget) return;
|
||||
|
||||
const url = currentTarget.dataset.url || '';
|
||||
const name = currentTarget.dataset.name || 'Unknown';
|
||||
// Always use 'album' type for individual album downloads regardless of category
|
||||
const type = 'album';
|
||||
|
||||
currentTarget.remove();
|
||||
// Use the centralized downloadQueue.download method
|
||||
downloadQueue.download(url, type, { name, type })
|
||||
.catch((err: any) => showError('Download failed: ' + (err?.message || 'Unknown error'))); // Add type for err
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add startDownload function (similar to track.js and main.js)
|
||||
/**
|
||||
* Starts the download process via centralized download queue
|
||||
*/
|
||||
async function startDownload(url: string, type: string, item: { name: string, artist?: string, type?: string }, albumType?: string) {
|
||||
if (!url || !type) {
|
||||
showError('Missing URL or type for download');
|
||||
return Promise.reject(new Error('Missing URL or type for download')); // Return a rejected promise
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method for all downloads including artist downloads
|
||||
const result = await downloadQueue.download(url, type, item, albumType);
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
|
||||
// Return the result for tracking
|
||||
return result;
|
||||
} catch (error: any) { // Add type for error
|
||||
showError('Download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// UI Helpers
|
||||
function showError(message: string) {
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) {
|
||||
errorEl.textContent = message || 'An error occurred';
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function capitalize(str: string) {
|
||||
return str ? str.charAt(0).toUpperCase() + str.slice(1) : '';
|
||||
}
|
||||
@@ -1,841 +0,0 @@
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
const serviceConfig: Record<string, any> = {
|
||||
spotify: {
|
||||
fields: [
|
||||
{ id: 'username', label: 'Username', type: 'text' },
|
||||
{ id: 'credentials', label: 'Credentials', type: 'text' }
|
||||
],
|
||||
validator: (data) => ({
|
||||
username: data.username,
|
||||
credentials: data.credentials
|
||||
}),
|
||||
// Adding search credentials fields
|
||||
searchFields: [
|
||||
{ id: 'client_id', label: 'Client ID', type: 'text' },
|
||||
{ id: 'client_secret', label: 'Client Secret', type: 'password' }
|
||||
],
|
||||
searchValidator: (data) => ({
|
||||
client_id: data.client_id,
|
||||
client_secret: data.client_secret
|
||||
})
|
||||
},
|
||||
deezer: {
|
||||
fields: [
|
||||
{ id: 'arl', label: 'ARL', type: 'text' }
|
||||
],
|
||||
validator: (data) => ({
|
||||
arl: data.arl
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let currentService = 'spotify';
|
||||
let currentCredential: string | null = null;
|
||||
let isEditingSearch = false;
|
||||
|
||||
// Global variables to hold the active accounts from the config response.
|
||||
let activeSpotifyAccount = '';
|
||||
let activeDeezerAccount = '';
|
||||
|
||||
async function loadConfig() {
|
||||
try {
|
||||
const response = await fetch('/api/config');
|
||||
if (!response.ok) throw new Error('Failed to load config');
|
||||
|
||||
const savedConfig = await response.json();
|
||||
|
||||
// Set default service selection
|
||||
const defaultServiceSelect = document.getElementById('defaultServiceSelect') as HTMLSelectElement | null;
|
||||
if (defaultServiceSelect) defaultServiceSelect.value = savedConfig.service || 'spotify';
|
||||
|
||||
// Update the service-specific options based on selected service
|
||||
updateServiceSpecificOptions();
|
||||
|
||||
// Use the "spotify" and "deezer" properties from the API response to set the active accounts.
|
||||
activeSpotifyAccount = savedConfig.spotify || '';
|
||||
activeDeezerAccount = savedConfig.deezer || '';
|
||||
|
||||
// (Optionally, if the account selects already exist you can set their values here,
|
||||
// but updateAccountSelectors() will rebuild the options and set the proper values.)
|
||||
const spotifySelect = document.getElementById('spotifyAccountSelect') as HTMLSelectElement | null;
|
||||
const deezerSelect = document.getElementById('deezerAccountSelect') as HTMLSelectElement | null;
|
||||
if (spotifySelect) spotifySelect.value = activeSpotifyAccount;
|
||||
if (deezerSelect) deezerSelect.value = activeDeezerAccount;
|
||||
|
||||
// Update other configuration fields.
|
||||
const fallbackToggle = document.getElementById('fallbackToggle') as HTMLInputElement | null;
|
||||
if (fallbackToggle) fallbackToggle.checked = !!savedConfig.fallback;
|
||||
const spotifyQualitySelect = document.getElementById('spotifyQualitySelect') as HTMLSelectElement | null;
|
||||
if (spotifyQualitySelect) spotifyQualitySelect.value = savedConfig.spotifyQuality || 'NORMAL';
|
||||
const deezerQualitySelect = document.getElementById('deezerQualitySelect') as HTMLSelectElement | null;
|
||||
if (deezerQualitySelect) deezerQualitySelect.value = savedConfig.deezerQuality || 'MP3_128';
|
||||
const realTimeToggle = document.getElementById('realTimeToggle') as HTMLInputElement | null;
|
||||
if (realTimeToggle) realTimeToggle.checked = !!savedConfig.realTime;
|
||||
const customDirFormat = document.getElementById('customDirFormat') as HTMLInputElement | null;
|
||||
if (customDirFormat) customDirFormat.value = savedConfig.customDirFormat || '%ar_album%/%album%';
|
||||
const customTrackFormat = document.getElementById('customTrackFormat') as HTMLInputElement | null;
|
||||
if (customTrackFormat) customTrackFormat.value = savedConfig.customTrackFormat || '%tracknum%. %music%';
|
||||
const maxConcurrentDownloads = document.getElementById('maxConcurrentDownloads') as HTMLInputElement | null;
|
||||
if (maxConcurrentDownloads) maxConcurrentDownloads.value = savedConfig.maxConcurrentDownloads || '3';
|
||||
const maxRetries = document.getElementById('maxRetries') as HTMLInputElement | null;
|
||||
if (maxRetries) maxRetries.value = savedConfig.maxRetries || '3';
|
||||
const retryDelaySeconds = document.getElementById('retryDelaySeconds') as HTMLInputElement | null;
|
||||
if (retryDelaySeconds) retryDelaySeconds.value = savedConfig.retryDelaySeconds || '5';
|
||||
const retryDelayIncrease = document.getElementById('retryDelayIncrease') as HTMLInputElement | null;
|
||||
if (retryDelayIncrease) retryDelayIncrease.value = savedConfig.retry_delay_increase || '5';
|
||||
const tracknumPaddingToggle = document.getElementById('tracknumPaddingToggle') as HTMLInputElement | null;
|
||||
if (tracknumPaddingToggle) tracknumPaddingToggle.checked = savedConfig.tracknum_padding === undefined ? true : !!savedConfig.tracknum_padding;
|
||||
|
||||
// Update explicit filter status
|
||||
updateExplicitFilterStatus(savedConfig.explicitFilter);
|
||||
} catch (error: any) {
|
||||
showConfigError('Error loading config: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
try {
|
||||
await initConfig();
|
||||
setupServiceTabs();
|
||||
setupEventListeners();
|
||||
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => {
|
||||
downloadQueue.toggleVisibility();
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
});
|
||||
|
||||
async function initConfig() {
|
||||
await loadConfig();
|
||||
await updateAccountSelectors();
|
||||
loadCredentials(currentService);
|
||||
updateFormFields();
|
||||
}
|
||||
|
||||
function setupServiceTabs() {
|
||||
const serviceTabs = document.querySelectorAll('.tab-button');
|
||||
serviceTabs.forEach(tab => {
|
||||
tab.addEventListener('click', () => {
|
||||
serviceTabs.forEach(t => t.classList.remove('active'));
|
||||
tab.classList.add('active');
|
||||
currentService = (tab as HTMLElement).dataset.service || 'spotify';
|
||||
loadCredentials(currentService);
|
||||
updateFormFields();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function setupEventListeners() {
|
||||
(document.getElementById('credentialForm') as HTMLFormElement | null)?.addEventListener('submit', handleCredentialSubmit);
|
||||
|
||||
// Config change listeners
|
||||
(document.getElementById('defaultServiceSelect') as HTMLSelectElement | null)?.addEventListener('change', function() {
|
||||
updateServiceSpecificOptions();
|
||||
saveConfig();
|
||||
});
|
||||
(document.getElementById('fallbackToggle') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('realTimeToggle') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('spotifyQualitySelect') as HTMLSelectElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('deezerQualitySelect') as HTMLSelectElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('tracknumPaddingToggle') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('maxRetries') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('retryDelaySeconds') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
|
||||
// Update active account globals when the account selector is changed.
|
||||
(document.getElementById('spotifyAccountSelect') as HTMLSelectElement | null)?.addEventListener('change', (e: Event) => {
|
||||
activeSpotifyAccount = (e.target as HTMLSelectElement).value;
|
||||
saveConfig();
|
||||
});
|
||||
(document.getElementById('deezerAccountSelect') as HTMLSelectElement | null)?.addEventListener('change', (e: Event) => {
|
||||
activeDeezerAccount = (e.target as HTMLSelectElement).value;
|
||||
saveConfig();
|
||||
});
|
||||
|
||||
// Formatting settings
|
||||
(document.getElementById('customDirFormat') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
(document.getElementById('customTrackFormat') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
|
||||
// Copy to clipboard when selecting placeholders
|
||||
(document.getElementById('dirFormatHelp') as HTMLSelectElement | null)?.addEventListener('change', function() {
|
||||
copyPlaceholderToClipboard(this as HTMLSelectElement);
|
||||
});
|
||||
(document.getElementById('trackFormatHelp') as HTMLSelectElement | null)?.addEventListener('change', function() {
|
||||
copyPlaceholderToClipboard(this as HTMLSelectElement);
|
||||
});
|
||||
|
||||
// Max concurrent downloads change listener
|
||||
(document.getElementById('maxConcurrentDownloads') as HTMLInputElement | null)?.addEventListener('change', saveConfig);
|
||||
}
|
||||
|
||||
function updateServiceSpecificOptions() {
|
||||
// Get the selected service
|
||||
const selectedService = (document.getElementById('defaultServiceSelect') as HTMLSelectElement | null)?.value;
|
||||
|
||||
// Get all service-specific sections
|
||||
const spotifyOptions = document.querySelectorAll('.config-item.spotify-specific');
|
||||
const deezerOptions = document.querySelectorAll('.config-item.deezer-specific');
|
||||
|
||||
// Handle Spotify specific options
|
||||
if (selectedService === 'spotify') {
|
||||
// Highlight Spotify section
|
||||
(document.getElementById('spotifyQualitySelect') as HTMLElement | null)?.closest('.config-item')?.classList.add('highlighted-option');
|
||||
(document.getElementById('spotifyAccountSelect') as HTMLElement | null)?.closest('.config-item')?.classList.add('highlighted-option');
|
||||
|
||||
// Remove highlight from Deezer
|
||||
(document.getElementById('deezerQualitySelect') as HTMLElement | null)?.closest('.config-item')?.classList.remove('highlighted-option');
|
||||
(document.getElementById('deezerAccountSelect') as HTMLElement | null)?.closest('.config-item')?.classList.remove('highlighted-option');
|
||||
}
|
||||
// Handle Deezer specific options (for future use)
|
||||
else if (selectedService === 'deezer') {
|
||||
// Highlight Deezer section
|
||||
(document.getElementById('deezerQualitySelect') as HTMLElement | null)?.closest('.config-item')?.classList.add('highlighted-option');
|
||||
(document.getElementById('deezerAccountSelect') as HTMLElement | null)?.closest('.config-item')?.classList.add('highlighted-option');
|
||||
|
||||
// Remove highlight from Spotify
|
||||
(document.getElementById('spotifyQualitySelect') as HTMLElement | null)?.closest('.config-item')?.classList.remove('highlighted-option');
|
||||
(document.getElementById('spotifyAccountSelect') as HTMLElement | null)?.closest('.config-item')?.classList.remove('highlighted-option');
|
||||
}
|
||||
}
|
||||
|
||||
async function updateAccountSelectors() {
|
||||
try {
|
||||
const [spotifyResponse, deezerResponse] = await Promise.all([
|
||||
fetch('/api/credentials/spotify'),
|
||||
fetch('/api/credentials/deezer')
|
||||
]);
|
||||
|
||||
const spotifyAccounts = await spotifyResponse.json();
|
||||
const deezerAccounts = await deezerResponse.json();
|
||||
|
||||
// Get the select elements
|
||||
const spotifySelect = document.getElementById('spotifyAccountSelect') as HTMLSelectElement | null;
|
||||
const deezerSelect = document.getElementById('deezerAccountSelect') as HTMLSelectElement | null;
|
||||
|
||||
// Rebuild the Spotify selector options
|
||||
if (spotifySelect) {
|
||||
spotifySelect.innerHTML = spotifyAccounts
|
||||
.map((a: string) => `<option value="${a}">${a}</option>`)
|
||||
.join('');
|
||||
|
||||
// Use the active account loaded from the config (activeSpotifyAccount)
|
||||
if (spotifyAccounts.includes(activeSpotifyAccount)) {
|
||||
spotifySelect.value = activeSpotifyAccount;
|
||||
} else if (spotifyAccounts.length > 0) {
|
||||
spotifySelect.value = spotifyAccounts[0];
|
||||
activeSpotifyAccount = spotifyAccounts[0];
|
||||
await saveConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild the Deezer selector options
|
||||
if (deezerSelect) {
|
||||
deezerSelect.innerHTML = deezerAccounts
|
||||
.map((a: string) => `<option value="${a}">${a}</option>`)
|
||||
.join('');
|
||||
|
||||
if (deezerAccounts.includes(activeDeezerAccount)) {
|
||||
deezerSelect.value = activeDeezerAccount;
|
||||
} else if (deezerAccounts.length > 0) {
|
||||
deezerSelect.value = deezerAccounts[0];
|
||||
activeDeezerAccount = deezerAccounts[0];
|
||||
await saveConfig();
|
||||
}
|
||||
}
|
||||
|
||||
// Handle empty account lists
|
||||
[spotifySelect, deezerSelect].forEach((select, index) => {
|
||||
const accounts = index === 0 ? spotifyAccounts : deezerAccounts;
|
||||
if (select && accounts.length === 0) {
|
||||
select.innerHTML = '<option value="">No accounts available</option>';
|
||||
select.value = '';
|
||||
}
|
||||
});
|
||||
} catch (error: any) {
|
||||
showConfigError('Error updating accounts: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadCredentials(service: string) {
|
||||
try {
|
||||
const response = await fetch(`/api/credentials/all/${service}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load credentials: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const credentials = await response.json();
|
||||
renderCredentialsList(service, credentials);
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCredentialsList(service: string, credentials: any[]) {
|
||||
const list = document.querySelector('.credentials-list') as HTMLElement | null;
|
||||
if (!list) return;
|
||||
list.innerHTML = '';
|
||||
|
||||
if (!credentials.length) {
|
||||
list.innerHTML = '<div class="no-credentials">No accounts found. Add a new account below.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
credentials.forEach(credData => {
|
||||
const credItem = document.createElement('div');
|
||||
credItem.className = 'credential-item';
|
||||
|
||||
const hasSearchCreds = credData.search && Object.keys(credData.search).length > 0;
|
||||
|
||||
credItem.innerHTML = `
|
||||
<div class="credential-info">
|
||||
<span class="credential-name">${credData.name}</span>
|
||||
${service === 'spotify' ?
|
||||
`<div class="search-credentials-status ${hasSearchCreds ? 'has-api' : 'no-api'}">
|
||||
${hasSearchCreds ? 'API Configured' : 'No API Credentials'}
|
||||
</div>` : ''}
|
||||
</div>
|
||||
<div class="credential-actions">
|
||||
<button class="edit-btn" data-name="${credData.name}" data-service="${service}">Edit Account</button>
|
||||
${service === 'spotify' ?
|
||||
`<button class="edit-search-btn" data-name="${credData.name}" data-service="${service}">
|
||||
${hasSearchCreds ? 'Edit API' : 'Add API'}
|
||||
</button>` : ''}
|
||||
<button class="delete-btn" data-name="${credData.name}" data-service="${service}">Delete</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
list.appendChild(credItem);
|
||||
});
|
||||
|
||||
// Set up event handlers
|
||||
list.querySelectorAll('.delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', handleDeleteCredential as EventListener);
|
||||
});
|
||||
|
||||
list.querySelectorAll('.edit-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
isEditingSearch = false;
|
||||
handleEditCredential(e as MouseEvent);
|
||||
});
|
||||
});
|
||||
|
||||
if (service === 'spotify') {
|
||||
list.querySelectorAll('.edit-search-btn').forEach(btn => {
|
||||
btn.addEventListener('click', handleEditSearchCredential as EventListener);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteCredential(e: Event) {
|
||||
try {
|
||||
const target = e.target as HTMLElement;
|
||||
const service = target.dataset.service;
|
||||
const name = target.dataset.name;
|
||||
|
||||
if (!service || !name) {
|
||||
throw new Error('Missing credential information');
|
||||
}
|
||||
|
||||
if (!confirm(`Are you sure you want to delete the ${name} account?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/credentials/${service}/${name}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete credential');
|
||||
}
|
||||
|
||||
// If the deleted credential is the active account, clear the selection.
|
||||
const accountSelect = document.getElementById(`${service}AccountSelect`) as HTMLSelectElement | null;
|
||||
if (accountSelect && accountSelect.value === name) {
|
||||
accountSelect.value = '';
|
||||
if (service === 'spotify') {
|
||||
activeSpotifyAccount = '';
|
||||
} else if (service === 'deezer') {
|
||||
activeDeezerAccount = '';
|
||||
}
|
||||
await saveConfig();
|
||||
}
|
||||
|
||||
loadCredentials(service);
|
||||
await updateAccountSelectors();
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEditCredential(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement;
|
||||
const service = target.dataset.service;
|
||||
const name = target.dataset.name;
|
||||
|
||||
try {
|
||||
(document.querySelector(`[data-service="${service}"]`) as HTMLElement | null)?.click();
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
const response = await fetch(`/api/credentials/${service}/${name}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load credential: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
currentCredential = name ? name : null;
|
||||
const credentialNameInput = document.getElementById('credentialName') as HTMLInputElement | null;
|
||||
if (credentialNameInput) {
|
||||
credentialNameInput.value = name || '';
|
||||
credentialNameInput.disabled = true;
|
||||
}
|
||||
(document.getElementById('formTitle') as HTMLElement | null)!.textContent = `Edit ${service!.charAt(0).toUpperCase() + service!.slice(1)} Account`;
|
||||
(document.getElementById('submitCredentialBtn') as HTMLElement | null)!.textContent = 'Update Account';
|
||||
|
||||
// Show regular fields
|
||||
populateFormFields(service!, data);
|
||||
toggleSearchFieldsVisibility(false);
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleEditSearchCredential(e: Event) {
|
||||
const target = e.target as HTMLElement;
|
||||
const service = target.dataset.service;
|
||||
const name = target.dataset.name;
|
||||
|
||||
try {
|
||||
if (service !== 'spotify') {
|
||||
throw new Error('Search credentials are only available for Spotify');
|
||||
}
|
||||
|
||||
(document.querySelector(`[data-service="${service}"]`) as HTMLElement | null)?.click();
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
isEditingSearch = true;
|
||||
currentCredential = name ? name : null;
|
||||
const credentialNameInput = document.getElementById('credentialName') as HTMLInputElement | null;
|
||||
if (credentialNameInput) {
|
||||
credentialNameInput.value = name || '';
|
||||
credentialNameInput.disabled = true;
|
||||
}
|
||||
(document.getElementById('formTitle')as HTMLElement | null)!.textContent = `Spotify API Credentials for ${name}`;
|
||||
(document.getElementById('submitCredentialBtn') as HTMLElement | null)!.textContent = 'Save API Credentials';
|
||||
|
||||
// Try to load existing search credentials
|
||||
try {
|
||||
const searchResponse = await fetch(`/api/credentials/${service}/${name}?type=search`);
|
||||
if (searchResponse.ok) {
|
||||
const searchData = await searchResponse.json();
|
||||
// Populate search fields
|
||||
serviceConfig[service].searchFields.forEach((field: { id: string; }) => {
|
||||
const element = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (element) element.value = searchData[field.id] || '';
|
||||
});
|
||||
} else {
|
||||
// Clear search fields if no existing search credentials
|
||||
serviceConfig[service].searchFields.forEach((field: { id: string; }) => {
|
||||
const element = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (element) element.value = '';
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// Clear search fields if there was an error
|
||||
serviceConfig[service].searchFields.forEach((field: { id: string; }) => {
|
||||
const element = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (element) element.value = '';
|
||||
});
|
||||
}
|
||||
|
||||
// Hide regular account fields, show search fields
|
||||
toggleSearchFieldsVisibility(true);
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSearchFieldsVisibility(showSearchFields: boolean) {
|
||||
const serviceFieldsDiv = document.getElementById('serviceFields') as HTMLElement | null;
|
||||
const searchFieldsDiv = document.getElementById('searchFields') as HTMLElement | null;
|
||||
|
||||
if (showSearchFields) {
|
||||
// Hide regular fields and remove 'required' attribute
|
||||
if(serviceFieldsDiv) serviceFieldsDiv.style.display = 'none';
|
||||
// Remove required attribute from service fields
|
||||
serviceConfig[currentService].fields.forEach((field: { id: string }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (input) input.removeAttribute('required');
|
||||
});
|
||||
|
||||
// Show search fields and add 'required' attribute
|
||||
if(searchFieldsDiv) searchFieldsDiv.style.display = 'block';
|
||||
// Make search fields required
|
||||
if (currentService === 'spotify' && serviceConfig[currentService].searchFields) {
|
||||
serviceConfig[currentService].searchFields.forEach((field: { id: string }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (input) input.setAttribute('required', '');
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Show regular fields and add 'required' attribute
|
||||
if(serviceFieldsDiv) serviceFieldsDiv.style.display = 'block';
|
||||
// Make service fields required
|
||||
serviceConfig[currentService].fields.forEach((field: { id: string }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (input) input.setAttribute('required', '');
|
||||
});
|
||||
|
||||
// Hide search fields and remove 'required' attribute
|
||||
if(searchFieldsDiv) searchFieldsDiv.style.display = 'none';
|
||||
// Remove required from search fields
|
||||
if (currentService === 'spotify' && serviceConfig[currentService].searchFields) {
|
||||
serviceConfig[currentService].searchFields.forEach((field: { id: string }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (input) input.removeAttribute('required');
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateFormFields() {
|
||||
const serviceFieldsDiv = document.getElementById('serviceFields') as HTMLElement | null;
|
||||
const searchFieldsDiv = document.getElementById('searchFields') as HTMLElement | null;
|
||||
|
||||
// Clear any existing fields
|
||||
if(serviceFieldsDiv) serviceFieldsDiv.innerHTML = '';
|
||||
if(searchFieldsDiv) searchFieldsDiv.innerHTML = '';
|
||||
|
||||
// Add regular account fields
|
||||
serviceConfig[currentService].fields.forEach((field: { className: string; label: string; type: string; id: string; }) => {
|
||||
const fieldDiv = document.createElement('div');
|
||||
fieldDiv.className = 'form-group';
|
||||
fieldDiv.innerHTML = `
|
||||
<label>${field.label}:</label>
|
||||
<input type="${field.type}"
|
||||
id="${field.id}"
|
||||
name="${field.id}"
|
||||
required
|
||||
${field.type === 'password' ? 'autocomplete="new-password"' : ''}>
|
||||
`;
|
||||
serviceFieldsDiv?.appendChild(fieldDiv);
|
||||
});
|
||||
|
||||
// Add search fields for Spotify
|
||||
if (currentService === 'spotify' && serviceConfig[currentService].searchFields) {
|
||||
serviceConfig[currentService].searchFields.forEach((field: { className: string; label: string; type: string; id: string; }) => {
|
||||
const fieldDiv = document.createElement('div');
|
||||
fieldDiv.className = 'form-group';
|
||||
fieldDiv.innerHTML = `
|
||||
<label>${field.label}:</label>
|
||||
<input type="${field.type}"
|
||||
id="${field.id}"
|
||||
name="${field.id}"
|
||||
required
|
||||
${field.type === 'password' ? 'autocomplete="new-password"' : ''}>
|
||||
`;
|
||||
searchFieldsDiv?.appendChild(fieldDiv);
|
||||
});
|
||||
}
|
||||
|
||||
// Reset form title and button text
|
||||
(document.getElementById('formTitle') as HTMLElement | null)!.textContent = `Add New ${currentService.charAt(0).toUpperCase() + currentService.slice(1)} Account`;
|
||||
(document.getElementById('submitCredentialBtn') as HTMLElement | null)!.textContent = 'Save Account';
|
||||
|
||||
// Initially show regular fields, hide search fields
|
||||
toggleSearchFieldsVisibility(false);
|
||||
isEditingSearch = false;
|
||||
}
|
||||
|
||||
function populateFormFields(service: string, data: Record<string, string>) {
|
||||
serviceConfig[service].fields.forEach((field: { id: string; }) => {
|
||||
const element = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
if (element) element.value = data[field.id] || '';
|
||||
});
|
||||
}
|
||||
|
||||
async function handleCredentialSubmit(e: Event) {
|
||||
e.preventDefault();
|
||||
const service = (document.querySelector('.tab-button.active') as HTMLElement | null)?.dataset.service;
|
||||
const nameInput = document.getElementById('credentialName') as HTMLInputElement | null;
|
||||
const name = nameInput?.value.trim();
|
||||
|
||||
try {
|
||||
if (!currentCredential && !name) {
|
||||
throw new Error('Credential name is required');
|
||||
}
|
||||
if (!service) {
|
||||
throw new Error('Service not selected');
|
||||
}
|
||||
|
||||
const endpointName = currentCredential || name;
|
||||
let method: string, data: any, endpoint: string;
|
||||
|
||||
if (isEditingSearch && service === 'spotify') {
|
||||
// Handle search credentials
|
||||
const formData: Record<string, string> = {};
|
||||
let isValid = true;
|
||||
let firstInvalidField: HTMLInputElement | null = null;
|
||||
|
||||
// Manually validate search fields
|
||||
serviceConfig[service!].searchFields.forEach((field: { id: string; }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
const value = input ? input.value.trim() : '';
|
||||
formData[field.id] = value;
|
||||
|
||||
if (!value) {
|
||||
isValid = false;
|
||||
if (!firstInvalidField && input) firstInvalidField = input;
|
||||
}
|
||||
});
|
||||
|
||||
if (!isValid) {
|
||||
if (firstInvalidField) (firstInvalidField as HTMLInputElement).focus();
|
||||
throw new Error('All fields are required');
|
||||
}
|
||||
|
||||
data = serviceConfig[service!].searchValidator(formData);
|
||||
endpoint = `/api/credentials/${service}/${endpointName}?type=search`;
|
||||
|
||||
// Check if search credentials already exist for this account
|
||||
const checkResponse = await fetch(endpoint);
|
||||
method = checkResponse.ok ? 'PUT' : 'POST';
|
||||
} else {
|
||||
// Handle regular account credentials
|
||||
const formData: Record<string, string> = {};
|
||||
let isValid = true;
|
||||
let firstInvalidField: HTMLInputElement | null = null;
|
||||
|
||||
// Manually validate account fields
|
||||
serviceConfig[service!].fields.forEach((field: { id: string; }) => {
|
||||
const input = document.getElementById(field.id) as HTMLInputElement | null;
|
||||
const value = input ? input.value.trim() : '';
|
||||
formData[field.id] = value;
|
||||
|
||||
if (!value) {
|
||||
isValid = false;
|
||||
if (!firstInvalidField && input) firstInvalidField = input;
|
||||
}
|
||||
});
|
||||
|
||||
if (!isValid) {
|
||||
if (firstInvalidField) (firstInvalidField as HTMLInputElement).focus();
|
||||
throw new Error('All fields are required');
|
||||
}
|
||||
|
||||
data = serviceConfig[service!].validator(formData);
|
||||
endpoint = `/api/credentials/${service}/${endpointName}`;
|
||||
method = currentCredential ? 'PUT' : 'POST';
|
||||
}
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to save credentials');
|
||||
}
|
||||
|
||||
await updateAccountSelectors();
|
||||
await saveConfig();
|
||||
loadCredentials(service!);
|
||||
resetForm();
|
||||
|
||||
// Show success message
|
||||
showConfigSuccess(isEditingSearch ? 'API credentials saved successfully' : 'Account saved successfully');
|
||||
} catch (error: any) {
|
||||
showConfigError(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
currentCredential = null;
|
||||
isEditingSearch = false;
|
||||
const nameInput = document.getElementById('credentialName') as HTMLInputElement | null;
|
||||
if (nameInput) {
|
||||
nameInput.value = '';
|
||||
nameInput.disabled = false;
|
||||
}
|
||||
(document.getElementById('credentialForm') as HTMLFormElement | null)?.reset();
|
||||
|
||||
// Reset form title and button text
|
||||
const serviceName = currentService.charAt(0).toUpperCase() + currentService.slice(1);
|
||||
(document.getElementById('formTitle') as HTMLElement | null)!.textContent = `Add New ${serviceName} Account`;
|
||||
(document.getElementById('submitCredentialBtn') as HTMLElement | null)!.textContent = 'Save Account';
|
||||
|
||||
// Show regular account fields, hide search fields
|
||||
toggleSearchFieldsVisibility(false);
|
||||
}
|
||||
|
||||
async function saveConfig() {
|
||||
// Read active account values directly from the DOM (or from the globals which are kept in sync)
|
||||
const config = {
|
||||
service: (document.getElementById('defaultServiceSelect') as HTMLSelectElement | null)?.value,
|
||||
spotify: (document.getElementById('spotifyAccountSelect') as HTMLSelectElement | null)?.value,
|
||||
deezer: (document.getElementById('deezerAccountSelect') as HTMLSelectElement | null)?.value,
|
||||
fallback: (document.getElementById('fallbackToggle') as HTMLInputElement | null)?.checked,
|
||||
spotifyQuality: (document.getElementById('spotifyQualitySelect') as HTMLSelectElement | null)?.value,
|
||||
deezerQuality: (document.getElementById('deezerQualitySelect') as HTMLSelectElement | null)?.value,
|
||||
realTime: (document.getElementById('realTimeToggle') as HTMLInputElement | null)?.checked,
|
||||
customDirFormat: (document.getElementById('customDirFormat') as HTMLInputElement | null)?.value,
|
||||
customTrackFormat: (document.getElementById('customTrackFormat') as HTMLInputElement | null)?.value,
|
||||
maxConcurrentDownloads: parseInt((document.getElementById('maxConcurrentDownloads') as HTMLInputElement | null)?.value || '3', 10) || 3,
|
||||
maxRetries: parseInt((document.getElementById('maxRetries') as HTMLInputElement | null)?.value || '3', 10) || 3,
|
||||
retryDelaySeconds: parseInt((document.getElementById('retryDelaySeconds') as HTMLInputElement | null)?.value || '5', 10) || 5,
|
||||
retry_delay_increase: parseInt((document.getElementById('retryDelayIncrease') as HTMLInputElement | null)?.value || '5', 10) || 5,
|
||||
tracknum_padding: (document.getElementById('tracknumPaddingToggle') as HTMLInputElement | null)?.checked
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/config', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(config)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Failed to save config');
|
||||
}
|
||||
|
||||
const savedConfig = await response.json();
|
||||
|
||||
// Set default service selection
|
||||
const defaultServiceSelect = document.getElementById('defaultServiceSelect') as HTMLSelectElement | null;
|
||||
if (defaultServiceSelect) defaultServiceSelect.value = savedConfig.service || 'spotify';
|
||||
|
||||
// Update the service-specific options based on selected service
|
||||
updateServiceSpecificOptions();
|
||||
|
||||
// Use the "spotify" and "deezer" properties from the API response to set the active accounts.
|
||||
activeSpotifyAccount = savedConfig.spotify || '';
|
||||
activeDeezerAccount = savedConfig.deezer || '';
|
||||
|
||||
// (Optionally, if the account selects already exist you can set their values here,
|
||||
// but updateAccountSelectors() will rebuild the options and set the proper values.)
|
||||
const spotifySelect = document.getElementById('spotifyAccountSelect') as HTMLSelectElement | null;
|
||||
const deezerSelect = document.getElementById('deezerAccountSelect') as HTMLSelectElement | null;
|
||||
if (spotifySelect) spotifySelect.value = activeSpotifyAccount;
|
||||
if (deezerSelect) deezerSelect.value = activeDeezerAccount;
|
||||
|
||||
// Update other configuration fields.
|
||||
const fallbackToggle = document.getElementById('fallbackToggle') as HTMLInputElement | null;
|
||||
if (fallbackToggle) fallbackToggle.checked = !!savedConfig.fallback;
|
||||
const spotifyQualitySelect = document.getElementById('spotifyQualitySelect') as HTMLSelectElement | null;
|
||||
if (spotifyQualitySelect) spotifyQualitySelect.value = savedConfig.spotifyQuality || 'NORMAL';
|
||||
const deezerQualitySelect = document.getElementById('deezerQualitySelect') as HTMLSelectElement | null;
|
||||
if (deezerQualitySelect) deezerQualitySelect.value = savedConfig.deezerQuality || 'MP3_128';
|
||||
const realTimeToggle = document.getElementById('realTimeToggle') as HTMLInputElement | null;
|
||||
if (realTimeToggle) realTimeToggle.checked = !!savedConfig.realTime;
|
||||
const customDirFormat = document.getElementById('customDirFormat') as HTMLInputElement | null;
|
||||
if (customDirFormat) customDirFormat.value = savedConfig.customDirFormat || '%ar_album%/%album%';
|
||||
const customTrackFormat = document.getElementById('customTrackFormat') as HTMLInputElement | null;
|
||||
if (customTrackFormat) customTrackFormat.value = savedConfig.customTrackFormat || '%tracknum%. %music%';
|
||||
const maxConcurrentDownloads = document.getElementById('maxConcurrentDownloads') as HTMLInputElement | null;
|
||||
if (maxConcurrentDownloads) maxConcurrentDownloads.value = savedConfig.maxConcurrentDownloads || '3';
|
||||
const maxRetries = document.getElementById('maxRetries') as HTMLInputElement | null;
|
||||
if (maxRetries) maxRetries.value = savedConfig.maxRetries || '3';
|
||||
const retryDelaySeconds = document.getElementById('retryDelaySeconds') as HTMLInputElement | null;
|
||||
if (retryDelaySeconds) retryDelaySeconds.value = savedConfig.retryDelaySeconds || '5';
|
||||
const retryDelayIncrease = document.getElementById('retryDelayIncrease') as HTMLInputElement | null;
|
||||
if (retryDelayIncrease) retryDelayIncrease.value = savedConfig.retry_delay_increase || '5';
|
||||
const tracknumPaddingToggle = document.getElementById('tracknumPaddingToggle') as HTMLInputElement | null;
|
||||
if (tracknumPaddingToggle) tracknumPaddingToggle.checked = savedConfig.tracknum_padding === undefined ? true : !!savedConfig.tracknum_padding;
|
||||
|
||||
// Update explicit filter status
|
||||
updateExplicitFilterStatus(savedConfig.explicitFilter);
|
||||
} catch (error: any) {
|
||||
showConfigError('Error loading config: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function updateExplicitFilterStatus(isEnabled: boolean) {
|
||||
const statusElement = document.getElementById('explicitFilterStatus');
|
||||
if (statusElement) {
|
||||
// Remove existing classes
|
||||
statusElement.classList.remove('enabled', 'disabled');
|
||||
|
||||
// Add appropriate class and text based on whether filter is enabled
|
||||
if (isEnabled) {
|
||||
statusElement.textContent = 'Enabled';
|
||||
statusElement.classList.add('enabled');
|
||||
} else {
|
||||
statusElement.textContent = 'Disabled';
|
||||
statusElement.classList.add('disabled');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showConfigError(message: string) {
|
||||
const errorDiv = document.getElementById('configError');
|
||||
if (errorDiv) errorDiv.textContent = message;
|
||||
setTimeout(() => { if (errorDiv) errorDiv.textContent = '' }, 5000);
|
||||
}
|
||||
|
||||
function showConfigSuccess(message: string) {
|
||||
const successDiv = document.getElementById('configSuccess');
|
||||
if (successDiv) successDiv.textContent = message;
|
||||
setTimeout(() => { if (successDiv) successDiv.textContent = '' }, 5000);
|
||||
}
|
||||
|
||||
// Function to copy the selected placeholder to clipboard
|
||||
function copyPlaceholderToClipboard(select: HTMLSelectElement) {
|
||||
const placeholder = select.value;
|
||||
|
||||
if (!placeholder) return; // If nothing selected
|
||||
|
||||
// Copy to clipboard
|
||||
navigator.clipboard.writeText(placeholder)
|
||||
.then(() => {
|
||||
// Show success notification
|
||||
showCopyNotification(`Copied ${placeholder} to clipboard`);
|
||||
|
||||
// Reset select to default after a short delay
|
||||
setTimeout(() => {
|
||||
select.selectedIndex = 0;
|
||||
}, 500);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Failed to copy: ', err);
|
||||
});
|
||||
}
|
||||
|
||||
// Function to show a notification when copying
|
||||
function showCopyNotification(message: string) {
|
||||
// Check if notification container exists, create if not
|
||||
let notificationContainer = document.getElementById('copyNotificationContainer');
|
||||
if (!notificationContainer) {
|
||||
notificationContainer = document.createElement('div');
|
||||
notificationContainer.id = 'copyNotificationContainer';
|
||||
document.body.appendChild(notificationContainer);
|
||||
}
|
||||
|
||||
// Create notification element
|
||||
const notification = document.createElement('div');
|
||||
notification.className = 'copy-notification';
|
||||
notification.textContent = message;
|
||||
|
||||
// Add to container
|
||||
notificationContainer.appendChild(notification);
|
||||
|
||||
// Trigger animation
|
||||
setTimeout(() => {
|
||||
notification.classList.add('show');
|
||||
}, 10);
|
||||
|
||||
// Remove after animation completes
|
||||
setTimeout(() => {
|
||||
notification.classList.remove('show');
|
||||
setTimeout(() => {
|
||||
notificationContainer.removeChild(notification);
|
||||
}, 300);
|
||||
}, 2000);
|
||||
}
|
||||
@@ -1,474 +0,0 @@
|
||||
// main.ts
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// DOM elements
|
||||
const searchInput = document.getElementById('searchInput') as HTMLInputElement | null;
|
||||
const searchButton = document.getElementById('searchButton') as HTMLButtonElement | null;
|
||||
const searchType = document.getElementById('searchType') as HTMLSelectElement | null;
|
||||
const resultsContainer = document.getElementById('resultsContainer');
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
const emptyState = document.getElementById('emptyState');
|
||||
const loadingResults = document.getElementById('loadingResults');
|
||||
|
||||
// Initialize the queue
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => {
|
||||
downloadQueue.toggleVisibility();
|
||||
});
|
||||
}
|
||||
|
||||
// Add event listeners
|
||||
if (searchButton) {
|
||||
searchButton.addEventListener('click', performSearch);
|
||||
}
|
||||
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('keypress', function(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
performSearch();
|
||||
}
|
||||
});
|
||||
|
||||
// Auto-detect and handle pasted Spotify URLs
|
||||
searchInput.addEventListener('input', function(e: Event) {
|
||||
const target = e.target as HTMLInputElement;
|
||||
const inputVal = target.value.trim();
|
||||
if (isSpotifyUrl(inputVal)) {
|
||||
const details = getSpotifyResourceDetails(inputVal);
|
||||
if (details && searchType) {
|
||||
searchType.value = details.type;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Restore last search type if no URL override
|
||||
const savedType = localStorage.getItem('lastSearchType');
|
||||
if (searchType && savedType && ['track','album','playlist','artist'].includes(savedType)) {
|
||||
searchType.value = savedType;
|
||||
}
|
||||
// Save last selection on change
|
||||
if (searchType) {
|
||||
searchType.addEventListener('change', () => {
|
||||
localStorage.setItem('lastSearchType', searchType.value);
|
||||
});
|
||||
}
|
||||
|
||||
// Check for URL parameters
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const query = urlParams.get('q');
|
||||
const type = urlParams.get('type');
|
||||
|
||||
if (query && searchInput) {
|
||||
searchInput.value = query;
|
||||
if (type && searchType && ['track', 'album', 'playlist', 'artist'].includes(type)) {
|
||||
searchType.value = type;
|
||||
}
|
||||
performSearch();
|
||||
} else {
|
||||
// Show empty state if no query
|
||||
showEmptyState(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs the search based on input values
|
||||
*/
|
||||
async function performSearch() {
|
||||
const currentQuery = searchInput?.value.trim();
|
||||
if (!currentQuery) return;
|
||||
|
||||
// Handle direct Spotify URLs
|
||||
if (isSpotifyUrl(currentQuery)) {
|
||||
const details = getSpotifyResourceDetails(currentQuery);
|
||||
if (details && details.id) {
|
||||
// Redirect to the appropriate page
|
||||
window.location.href = `/${details.type}/${details.id}`;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Update URL without reloading page
|
||||
const currentSearchType = searchType?.value || 'track';
|
||||
const newUrl = `${window.location.pathname}?q=${encodeURIComponent(currentQuery)}&type=${currentSearchType}`;
|
||||
window.history.pushState({ path: newUrl }, '', newUrl);
|
||||
|
||||
// Show loading state
|
||||
showEmptyState(false);
|
||||
showLoading(true);
|
||||
if(resultsContainer) resultsContainer.innerHTML = '';
|
||||
|
||||
try {
|
||||
const url = `/api/search?q=${encodeURIComponent(currentQuery)}&search_type=${currentSearchType}&limit=40`;
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Hide loading indicator
|
||||
showLoading(false);
|
||||
|
||||
// Render results
|
||||
if (data && data.items && data.items.length > 0) {
|
||||
if(resultsContainer) resultsContainer.innerHTML = '';
|
||||
|
||||
// Filter out items with null/undefined essential display parameters
|
||||
const validItems = filterValidItems(data.items, currentSearchType);
|
||||
|
||||
if (validItems.length === 0) {
|
||||
// No valid items found after filtering
|
||||
if(resultsContainer) resultsContainer.innerHTML = `
|
||||
<div class="empty-search-results">
|
||||
<p>No valid results found for "${currentQuery}"</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
validItems.forEach((item, index) => {
|
||||
const cardElement = createResultCard(item, currentSearchType, index);
|
||||
|
||||
// Store the item data directly on the button element
|
||||
const downloadBtn = cardElement.querySelector('.download-btn') as HTMLButtonElement | null;
|
||||
if (downloadBtn) {
|
||||
downloadBtn.dataset.itemIndex = index.toString();
|
||||
}
|
||||
|
||||
if(resultsContainer) resultsContainer.appendChild(cardElement);
|
||||
});
|
||||
|
||||
// Attach download handlers to the newly created cards
|
||||
attachDownloadListeners(validItems);
|
||||
} else {
|
||||
// No results found
|
||||
if(resultsContainer) resultsContainer.innerHTML = `
|
||||
<div class="empty-search-results">
|
||||
<p>No results found for "${currentQuery}"</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Error:', error);
|
||||
showLoading(false);
|
||||
if(resultsContainer) resultsContainer.innerHTML = `
|
||||
<div class="error">
|
||||
<p>Error searching: ${error.message}</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out items with null/undefined essential display parameters based on search type
|
||||
*/
|
||||
function filterValidItems(items: any[], type: string) {
|
||||
if (!items) return [];
|
||||
|
||||
return items.filter(item => {
|
||||
// Skip null/undefined items
|
||||
if (!item) return false;
|
||||
|
||||
// Skip explicit content if filter is enabled
|
||||
if (downloadQueue.isExplicitFilterEnabled() && item.explicit === true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check essential parameters based on search type
|
||||
switch (type) {
|
||||
case 'track':
|
||||
// For tracks, we need name, artists, and album
|
||||
return (
|
||||
item.name &&
|
||||
item.artists &&
|
||||
item.artists.length > 0 &&
|
||||
item.artists[0] &&
|
||||
item.artists[0].name &&
|
||||
item.album &&
|
||||
item.album.name &&
|
||||
item.external_urls &&
|
||||
item.external_urls.spotify
|
||||
);
|
||||
|
||||
case 'album':
|
||||
// For albums, we need name, artists, and cover image
|
||||
return (
|
||||
item.name &&
|
||||
item.artists &&
|
||||
item.artists.length > 0 &&
|
||||
item.artists[0] &&
|
||||
item.artists[0].name &&
|
||||
item.external_urls &&
|
||||
item.external_urls.spotify
|
||||
);
|
||||
|
||||
case 'playlist':
|
||||
// For playlists, we need name, owner, and tracks
|
||||
return (
|
||||
item.name &&
|
||||
item.owner &&
|
||||
item.owner.display_name &&
|
||||
item.tracks &&
|
||||
item.external_urls &&
|
||||
item.external_urls.spotify
|
||||
);
|
||||
|
||||
case 'artist':
|
||||
// For artists, we need name
|
||||
return (
|
||||
item.name &&
|
||||
item.external_urls &&
|
||||
item.external_urls.spotify
|
||||
);
|
||||
|
||||
default:
|
||||
// Default case - just check if the item exists
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches download handlers to result cards
|
||||
*/
|
||||
function attachDownloadListeners(items: any[]) {
|
||||
document.querySelectorAll('.download-btn').forEach((btnElm) => {
|
||||
const btn = btnElm as HTMLButtonElement;
|
||||
btn.addEventListener('click', (e: Event) => {
|
||||
e.stopPropagation();
|
||||
|
||||
// Get the item index from the button's dataset
|
||||
const itemIndexStr = btn.dataset.itemIndex;
|
||||
if (!itemIndexStr) return;
|
||||
const itemIndex = parseInt(itemIndexStr, 10);
|
||||
|
||||
// Get the corresponding item
|
||||
const item = items[itemIndex];
|
||||
if (!item) return;
|
||||
|
||||
const currentSearchType = searchType?.value || 'track';
|
||||
let url;
|
||||
|
||||
// Determine the URL based on item type
|
||||
if (item.external_urls && item.external_urls.spotify) {
|
||||
url = item.external_urls.spotify;
|
||||
} else if (item.href) {
|
||||
url = item.href;
|
||||
} else {
|
||||
showError('Could not determine download URL');
|
||||
return;
|
||||
}
|
||||
|
||||
// Prepare metadata for the download
|
||||
const metadata = {
|
||||
name: item.name || 'Unknown',
|
||||
artist: item.artists ? item.artists[0]?.name : undefined
|
||||
};
|
||||
|
||||
// Disable the button and update text
|
||||
btn.disabled = true;
|
||||
|
||||
// For artist downloads, show a different message since it will queue multiple albums
|
||||
if (currentSearchType === 'artist') {
|
||||
btn.innerHTML = 'Queueing albums...';
|
||||
} else {
|
||||
btn.innerHTML = 'Queueing...';
|
||||
}
|
||||
|
||||
// Start the download
|
||||
startDownload(url, currentSearchType, metadata, item.album ? item.album.album_type : null)
|
||||
.then(() => {
|
||||
// For artists, show how many albums were queued
|
||||
if (currentSearchType === 'artist') {
|
||||
btn.innerHTML = 'Albums queued!';
|
||||
// Open the queue automatically for artist downloads
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} else {
|
||||
btn.innerHTML = 'Queued!';
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = 'Download';
|
||||
showError('Failed to queue download: ' + error.message);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the download process via API
|
||||
*/
|
||||
async function startDownload(url: string, type: string, item: any, albumType: string | null) {
|
||||
if (!url || !type) {
|
||||
showError('Missing URL or type for download');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, type, item, albumType);
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) {
|
||||
showError('Download failed: ' + (error.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows an error message
|
||||
*/
|
||||
function showError(message: string) {
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'error';
|
||||
errorDiv.textContent = message;
|
||||
document.body.appendChild(errorDiv);
|
||||
|
||||
// Auto-remove after 5 seconds
|
||||
setTimeout(() => errorDiv.remove(), 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a success message
|
||||
*/
|
||||
function showSuccess(message: string) {
|
||||
const successDiv = document.createElement('div');
|
||||
successDiv.className = 'success';
|
||||
successDiv.textContent = message;
|
||||
document.body.appendChild(successDiv);
|
||||
|
||||
// Auto-remove after 5 seconds
|
||||
setTimeout(() => successDiv.remove(), 5000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a string is a valid Spotify URL
|
||||
*/
|
||||
function isSpotifyUrl(url: string): boolean {
|
||||
return url.includes('open.spotify.com') ||
|
||||
url.includes('spotify:') ||
|
||||
url.includes('link.tospotify.com');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts details from a Spotify URL
|
||||
*/
|
||||
function getSpotifyResourceDetails(url: string): { type: string; id: string } | null {
|
||||
// Allow optional path segments (e.g. intl-fr) before resource type
|
||||
const regex = /spotify\.com\/(?:[^\/]+\/)??(track|album|playlist|artist)\/([a-zA-Z0-9]+)/i;
|
||||
const match = url.match(regex);
|
||||
|
||||
if (match) {
|
||||
return {
|
||||
type: match[1],
|
||||
id: match[2]
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats milliseconds to MM:SS
|
||||
*/
|
||||
function msToMinutesSeconds(ms: number | undefined): string {
|
||||
if (!ms) return '0:00';
|
||||
|
||||
const minutes = Math.floor(ms / 60000);
|
||||
const seconds = ((ms % 60000) / 1000).toFixed(0);
|
||||
return `${minutes}:${seconds.padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a result card element
|
||||
*/
|
||||
function createResultCard(item: any, type: string, index: number): HTMLDivElement {
|
||||
const cardElement = document.createElement('div');
|
||||
cardElement.className = 'result-card';
|
||||
|
||||
// Set cursor to pointer for clickable cards
|
||||
cardElement.style.cursor = 'pointer';
|
||||
|
||||
// Get the appropriate image URL
|
||||
let imageUrl = '/static/images/placeholder.jpg';
|
||||
if (item.album && item.album.images && item.album.images.length > 0) {
|
||||
imageUrl = item.album.images[0].url;
|
||||
} else if (item.images && item.images.length > 0) {
|
||||
imageUrl = item.images[0].url;
|
||||
}
|
||||
|
||||
// Get the appropriate details based on type
|
||||
let subtitle = '';
|
||||
let details = '';
|
||||
|
||||
switch (type) {
|
||||
case 'track':
|
||||
subtitle = item.artists ? item.artists.map(a => a.name).join(', ') : 'Unknown Artist';
|
||||
details = item.album ? `<span>${item.album.name}</span><span class="duration">${msToMinutesSeconds(item.duration_ms)}</span>` : '';
|
||||
break;
|
||||
case 'album':
|
||||
subtitle = item.artists ? item.artists.map(a => a.name).join(', ') : 'Unknown Artist';
|
||||
details = `<span>${item.total_tracks || 0} tracks</span><span>${item.release_date ? new Date(item.release_date).getFullYear() : ''}</span>`;
|
||||
break;
|
||||
case 'playlist':
|
||||
subtitle = `By ${item.owner ? item.owner.display_name : 'Unknown'}`;
|
||||
details = `<span>${item.tracks && item.tracks.total ? item.tracks.total : 0} tracks</span>`;
|
||||
break;
|
||||
case 'artist':
|
||||
subtitle = 'Artist';
|
||||
details = item.genres ? `<span>${item.genres.slice(0, 2).join(', ')}</span>` : '';
|
||||
break;
|
||||
}
|
||||
|
||||
// Build the HTML
|
||||
cardElement.innerHTML = `
|
||||
<div class="album-art-wrapper">
|
||||
<img class="album-art" src="${imageUrl}" alt="${item.name || 'Item'}" onerror="this.src='/static/images/placeholder.jpg'">
|
||||
</div>
|
||||
<div class="track-title">${item.name || 'Unknown'}</div>
|
||||
<div class="track-artist">${subtitle}</div>
|
||||
<div class="track-details">${details}</div>
|
||||
<button class="download-btn btn-primary" data-item-index="${index}">
|
||||
<img src="/static/images/download.svg" alt="Download" />
|
||||
Download
|
||||
</button>
|
||||
`;
|
||||
|
||||
// Add click event to navigate to the item's detail page
|
||||
cardElement.addEventListener('click', (e: MouseEvent) => {
|
||||
// Don't trigger if the download button was clicked
|
||||
const target = e.target as HTMLElement;
|
||||
if (target.classList.contains('download-btn') ||
|
||||
target.parentElement?.classList.contains('download-btn')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.id) {
|
||||
window.location.href = `/${type}/${item.id}`;
|
||||
}
|
||||
});
|
||||
|
||||
return cardElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show/hide the empty state
|
||||
*/
|
||||
function showEmptyState(show: boolean) {
|
||||
if (emptyState) {
|
||||
emptyState.style.display = show ? 'flex' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show/hide the loading indicator
|
||||
*/
|
||||
function showLoading(show: boolean) {
|
||||
if (loadingResults) {
|
||||
loadingResults.classList.toggle('hidden', !show);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,413 +0,0 @@
|
||||
// Import the downloadQueue singleton from your working queue.js implementation.
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Parse playlist ID from URL
|
||||
const pathSegments = window.location.pathname.split('/');
|
||||
const playlistId = pathSegments[pathSegments.indexOf('playlist') + 1];
|
||||
|
||||
if (!playlistId) {
|
||||
showError('No playlist ID provided.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch playlist info directly
|
||||
fetch(`/api/playlist/info?id=${encodeURIComponent(playlistId)}`)
|
||||
.then(response => {
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
return response.json();
|
||||
})
|
||||
.then(data => renderPlaylist(data))
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showError('Failed to load playlist.');
|
||||
});
|
||||
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => {
|
||||
downloadQueue.toggleVisibility();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Renders playlist header and tracks.
|
||||
*/
|
||||
function renderPlaylist(playlist: any) {
|
||||
// Hide loading and error messages
|
||||
const loadingEl = document.getElementById('loading');
|
||||
if (loadingEl) loadingEl.classList.add('hidden');
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) errorEl.classList.add('hidden');
|
||||
|
||||
// Check if explicit filter is enabled
|
||||
const isExplicitFilterEnabled = downloadQueue.isExplicitFilterEnabled();
|
||||
|
||||
// Update header info
|
||||
const playlistNameEl = document.getElementById('playlist-name');
|
||||
if (playlistNameEl) playlistNameEl.textContent = playlist.name || 'Unknown Playlist';
|
||||
const playlistOwnerEl = document.getElementById('playlist-owner');
|
||||
if (playlistOwnerEl) playlistOwnerEl.textContent = `By ${playlist.owner?.display_name || 'Unknown User'}`;
|
||||
const playlistStatsEl = document.getElementById('playlist-stats');
|
||||
if (playlistStatsEl) playlistStatsEl.textContent =
|
||||
`${playlist.followers?.total || '0'} followers • ${playlist.tracks?.total || '0'} songs`;
|
||||
const playlistDescriptionEl = document.getElementById('playlist-description');
|
||||
if (playlistDescriptionEl) playlistDescriptionEl.textContent = playlist.description || '';
|
||||
const image = playlist.images?.[0]?.url || '/static/images/placeholder.jpg';
|
||||
const playlistImageEl = document.getElementById('playlist-image') as HTMLImageElement;
|
||||
if (playlistImageEl) playlistImageEl.src = image;
|
||||
|
||||
// --- Add Home Button ---
|
||||
let homeButton = document.getElementById('homeButton') as HTMLButtonElement;
|
||||
if (!homeButton) {
|
||||
homeButton = document.createElement('button');
|
||||
homeButton.id = 'homeButton';
|
||||
homeButton.className = 'home-btn';
|
||||
// Use an <img> tag to display the SVG icon.
|
||||
homeButton.innerHTML = `<img src="/static/images/home.svg" alt="Home">`;
|
||||
// Insert the home button at the beginning of the header container.
|
||||
const headerContainer = document.getElementById('playlist-header');
|
||||
if (headerContainer) {
|
||||
headerContainer.insertBefore(homeButton, headerContainer.firstChild);
|
||||
}
|
||||
}
|
||||
homeButton.addEventListener('click', () => {
|
||||
// Navigate to the site's base URL.
|
||||
window.location.href = window.location.origin;
|
||||
});
|
||||
|
||||
// Check if any track in the playlist is explicit when filter is enabled
|
||||
let hasExplicitTrack = false;
|
||||
if (isExplicitFilterEnabled && playlist.tracks?.items) {
|
||||
hasExplicitTrack = playlist.tracks.items.some(item => item?.track && item.track.explicit);
|
||||
}
|
||||
|
||||
// --- Add "Download Whole Playlist" Button ---
|
||||
let downloadPlaylistBtn = document.getElementById('downloadPlaylistBtn') as HTMLButtonElement;
|
||||
if (!downloadPlaylistBtn) {
|
||||
downloadPlaylistBtn = document.createElement('button');
|
||||
downloadPlaylistBtn.id = 'downloadPlaylistBtn';
|
||||
downloadPlaylistBtn.textContent = 'Download Whole Playlist';
|
||||
downloadPlaylistBtn.className = 'download-btn download-btn--main';
|
||||
// Insert the button into the header container.
|
||||
const headerContainer = document.getElementById('playlist-header');
|
||||
if (headerContainer) {
|
||||
headerContainer.appendChild(downloadPlaylistBtn);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Add "Download Playlist's Albums" Button ---
|
||||
let downloadAlbumsBtn = document.getElementById('downloadAlbumsBtn') as HTMLButtonElement;
|
||||
if (!downloadAlbumsBtn) {
|
||||
downloadAlbumsBtn = document.createElement('button');
|
||||
downloadAlbumsBtn.id = 'downloadAlbumsBtn';
|
||||
downloadAlbumsBtn.textContent = "Download Playlist's Albums";
|
||||
downloadAlbumsBtn.className = 'download-btn download-btn--main';
|
||||
// Insert the new button into the header container.
|
||||
const headerContainer = document.getElementById('playlist-header');
|
||||
if (headerContainer) {
|
||||
headerContainer.appendChild(downloadAlbumsBtn);
|
||||
}
|
||||
}
|
||||
|
||||
if (isExplicitFilterEnabled && hasExplicitTrack) {
|
||||
// Disable both playlist buttons and display messages explaining why
|
||||
if (downloadPlaylistBtn) {
|
||||
downloadPlaylistBtn.disabled = true;
|
||||
downloadPlaylistBtn.classList.add('download-btn--disabled');
|
||||
downloadPlaylistBtn.innerHTML = `<span title="Cannot download entire playlist because it contains explicit tracks">Playlist Contains Explicit Tracks</span>`;
|
||||
}
|
||||
|
||||
if (downloadAlbumsBtn) {
|
||||
downloadAlbumsBtn.disabled = true;
|
||||
downloadAlbumsBtn.classList.add('download-btn--disabled');
|
||||
downloadAlbumsBtn.innerHTML = `<span title="Cannot download albums from this playlist because it contains explicit tracks">Albums Access Restricted</span>`;
|
||||
}
|
||||
} else {
|
||||
// Normal behavior when no explicit tracks are present
|
||||
if (downloadPlaylistBtn) {
|
||||
downloadPlaylistBtn.addEventListener('click', () => {
|
||||
// Remove individual track download buttons (but leave the whole playlist button).
|
||||
document.querySelectorAll('.download-btn').forEach(btn => {
|
||||
if (btn.id !== 'downloadPlaylistBtn') {
|
||||
btn.remove();
|
||||
}
|
||||
});
|
||||
|
||||
// Disable the whole playlist button to prevent repeated clicks.
|
||||
downloadPlaylistBtn.disabled = true;
|
||||
downloadPlaylistBtn.textContent = 'Queueing...';
|
||||
|
||||
// Initiate the playlist download.
|
||||
downloadWholePlaylist(playlist).then(() => {
|
||||
downloadPlaylistBtn.textContent = 'Queued!';
|
||||
}).catch((err: any) => {
|
||||
showError('Failed to queue playlist download: ' + (err?.message || 'Unknown error'));
|
||||
downloadPlaylistBtn.disabled = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (downloadAlbumsBtn) {
|
||||
downloadAlbumsBtn.addEventListener('click', () => {
|
||||
// Remove individual track download buttons (but leave this album button).
|
||||
document.querySelectorAll('.download-btn').forEach(btn => {
|
||||
if (btn.id !== 'downloadAlbumsBtn') btn.remove();
|
||||
});
|
||||
|
||||
downloadAlbumsBtn.disabled = true;
|
||||
downloadAlbumsBtn.textContent = 'Queueing...';
|
||||
|
||||
downloadPlaylistAlbums(playlist)
|
||||
.then(() => {
|
||||
if (downloadAlbumsBtn) downloadAlbumsBtn.textContent = 'Queued!';
|
||||
})
|
||||
.catch((err: any) => {
|
||||
showError('Failed to queue album downloads: ' + (err?.message || 'Unknown error'));
|
||||
if (downloadAlbumsBtn) downloadAlbumsBtn.disabled = false;
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Render tracks list
|
||||
const tracksList = document.getElementById('tracks-list');
|
||||
if (!tracksList) return;
|
||||
|
||||
tracksList.innerHTML = ''; // Clear any existing content
|
||||
|
||||
if (playlist.tracks?.items) {
|
||||
playlist.tracks.items.forEach((item, index) => {
|
||||
if (!item || !item.track) return; // Skip null/undefined tracks
|
||||
|
||||
const track = item.track;
|
||||
|
||||
// Skip explicit tracks if filter is enabled
|
||||
if (isExplicitFilterEnabled && track.explicit) {
|
||||
// Add a placeholder for filtered explicit tracks
|
||||
const trackElement = document.createElement('div');
|
||||
trackElement.className = 'track track-filtered';
|
||||
trackElement.innerHTML = `
|
||||
<div class="track-number">${index + 1}</div>
|
||||
<div class="track-info">
|
||||
<div class="track-name explicit-filtered">Explicit Content Filtered</div>
|
||||
<div class="track-artist">This track is not shown due to explicit content filter settings</div>
|
||||
</div>
|
||||
<div class="track-album">Not available</div>
|
||||
<div class="track-duration">--:--</div>
|
||||
`;
|
||||
tracksList.appendChild(trackElement);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create links for track, artist, and album using their IDs.
|
||||
const trackLink = `/track/${track.id || ''}`;
|
||||
const artistLink = `/artist/${track.artists?.[0]?.id || ''}`;
|
||||
const albumLink = `/album/${track.album?.id || ''}`;
|
||||
|
||||
const trackElement = document.createElement('div');
|
||||
trackElement.className = 'track';
|
||||
trackElement.innerHTML = `
|
||||
<div class="track-number">${index + 1}</div>
|
||||
<div class="track-info">
|
||||
<div class="track-name">
|
||||
<a href="${trackLink}" title="View track details">${track.name || 'Unknown Track'}</a>
|
||||
</div>
|
||||
<div class="track-artist">
|
||||
<a href="${artistLink}" title="View artist details">${track.artists?.[0]?.name || 'Unknown Artist'}</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="track-album">
|
||||
<a href="${albumLink}" title="View album details">${track.album?.name || 'Unknown Album'}</a>
|
||||
</div>
|
||||
<div class="track-duration">${msToTime(track.duration_ms || 0)}</div>
|
||||
<button class="download-btn download-btn--circle"
|
||||
data-url="${track.external_urls?.spotify || ''}"
|
||||
data-type="track"
|
||||
data-name="${track.name || 'Unknown Track'}"
|
||||
title="Download">
|
||||
<img src="/static/images/download.svg" alt="Download">
|
||||
</button>
|
||||
`;
|
||||
tracksList.appendChild(trackElement);
|
||||
});
|
||||
}
|
||||
|
||||
// Reveal header and tracks container
|
||||
const playlistHeaderEl = document.getElementById('playlist-header');
|
||||
if (playlistHeaderEl) playlistHeaderEl.classList.remove('hidden');
|
||||
const tracksContainerEl = document.getElementById('tracks-container');
|
||||
if (tracksContainerEl) tracksContainerEl.classList.remove('hidden');
|
||||
|
||||
// Attach download listeners to newly rendered download buttons
|
||||
attachDownloadListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts milliseconds to minutes:seconds.
|
||||
*/
|
||||
function msToTime(duration: number) {
|
||||
if (!duration || isNaN(duration)) return '0:00';
|
||||
|
||||
const minutes = Math.floor(duration / 60000);
|
||||
const seconds = ((duration % 60000) / 1000).toFixed(0);
|
||||
return `${minutes}:${seconds.padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays an error message in the UI.
|
||||
*/
|
||||
function showError(message: string) {
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) {
|
||||
errorEl.textContent = message || 'An error occurred';
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches event listeners to all individual download buttons.
|
||||
*/
|
||||
function attachDownloadListeners() {
|
||||
document.querySelectorAll('.download-btn').forEach((btn) => {
|
||||
// Skip the whole playlist and album download buttons.
|
||||
if (btn.id === 'downloadPlaylistBtn' || btn.id === 'downloadAlbumsBtn') return;
|
||||
btn.addEventListener('click', (e: Event) => {
|
||||
e.stopPropagation();
|
||||
const currentTarget = e.currentTarget as HTMLButtonElement;
|
||||
const url = currentTarget.dataset.url || '';
|
||||
const type = currentTarget.dataset.type || '';
|
||||
const name = currentTarget.dataset.name || extractName(url) || 'Unknown';
|
||||
// Remove the button immediately after click.
|
||||
currentTarget.remove();
|
||||
startDownload(url, type, { name }, ''); // Added empty string for albumType
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates the whole playlist download by calling the playlist endpoint.
|
||||
*/
|
||||
async function downloadWholePlaylist(playlist: any) {
|
||||
if (!playlist) {
|
||||
throw new Error('Invalid playlist data');
|
||||
}
|
||||
|
||||
const url = playlist.external_urls?.spotify || '';
|
||||
if (!url) {
|
||||
throw new Error('Missing playlist URL');
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, 'playlist', { name: playlist.name || 'Unknown Playlist' });
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) {
|
||||
showError('Playlist download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates album downloads for each unique album in the playlist,
|
||||
* adding a 20ms delay between each album download and updating the button
|
||||
* with the progress (queued_albums/total_albums).
|
||||
*/
|
||||
async function downloadPlaylistAlbums(playlist: any) {
|
||||
if (!playlist?.tracks?.items) {
|
||||
showError('No tracks found in this playlist.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Build a map of unique albums (using album ID as the key).
|
||||
const albumMap = new Map();
|
||||
playlist.tracks.items.forEach(item => {
|
||||
if (!item?.track?.album) return;
|
||||
|
||||
const album = item.track.album;
|
||||
if (album && album.id) {
|
||||
albumMap.set(album.id, album);
|
||||
}
|
||||
});
|
||||
|
||||
const uniqueAlbums = Array.from(albumMap.values());
|
||||
const totalAlbums = uniqueAlbums.length;
|
||||
if (totalAlbums === 0) {
|
||||
showError('No albums found in this playlist.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a reference to the "Download Playlist's Albums" button.
|
||||
const downloadAlbumsBtn = document.getElementById('downloadAlbumsBtn') as HTMLButtonElement | null;
|
||||
if (downloadAlbumsBtn) {
|
||||
// Initialize the progress display.
|
||||
downloadAlbumsBtn.textContent = `0/${totalAlbums}`;
|
||||
}
|
||||
|
||||
try {
|
||||
// Process each album sequentially.
|
||||
for (let i = 0; i < totalAlbums; i++) {
|
||||
const album = uniqueAlbums[i];
|
||||
if (!album) continue;
|
||||
|
||||
const albumUrl = album.external_urls?.spotify || '';
|
||||
if (!albumUrl) continue;
|
||||
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(
|
||||
albumUrl,
|
||||
'album',
|
||||
{ name: album.name || 'Unknown Album' }
|
||||
);
|
||||
|
||||
// Update button text with current progress.
|
||||
if (downloadAlbumsBtn) {
|
||||
downloadAlbumsBtn.textContent = `${i + 1}/${totalAlbums}`;
|
||||
}
|
||||
|
||||
// Wait 20 milliseconds before processing the next album.
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
|
||||
// Once all albums have been queued, update the button text.
|
||||
if (downloadAlbumsBtn) {
|
||||
downloadAlbumsBtn.textContent = 'Queued!';
|
||||
}
|
||||
|
||||
// Make the queue visible after queueing all albums
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) {
|
||||
// Propagate any errors encountered.
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the download process using the centralized download method from the queue.
|
||||
*/
|
||||
async function startDownload(url: string, type: string, item: any, albumType?: string) {
|
||||
if (!url || !type) {
|
||||
showError('Missing URL or type for download');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, type, item, albumType);
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) {
|
||||
showError('Download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A helper function to extract a display name from the URL.
|
||||
*/
|
||||
function extractName(url: string | null): string {
|
||||
return url || 'Unknown';
|
||||
}
|
||||
2709
static/js/queue.ts
2709
static/js/queue.ts
File diff suppressed because it is too large
Load Diff
@@ -1,215 +0,0 @@
|
||||
// Import the downloadQueue singleton from your working queue.js implementation.
|
||||
import { downloadQueue } from './queue.js';
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Parse track ID from URL. Expecting URL in the form /track/{id}
|
||||
const pathSegments = window.location.pathname.split('/');
|
||||
const trackId = pathSegments[pathSegments.indexOf('track') + 1];
|
||||
|
||||
if (!trackId) {
|
||||
showError('No track ID provided.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch track info directly
|
||||
fetch(`/api/track/info?id=${encodeURIComponent(trackId)}`)
|
||||
.then(response => {
|
||||
if (!response.ok) throw new Error('Network response was not ok');
|
||||
return response.json();
|
||||
})
|
||||
.then(data => renderTrack(data))
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showError('Error loading track');
|
||||
});
|
||||
|
||||
// Attach event listener to the queue icon to toggle the download queue
|
||||
const queueIcon = document.getElementById('queueIcon');
|
||||
if (queueIcon) {
|
||||
queueIcon.addEventListener('click', () => {
|
||||
downloadQueue.toggleVisibility();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Renders the track header information.
|
||||
*/
|
||||
function renderTrack(track: any) {
|
||||
// Hide the loading and error messages.
|
||||
const loadingEl = document.getElementById('loading');
|
||||
if (loadingEl) loadingEl.classList.add('hidden');
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) errorEl.classList.add('hidden');
|
||||
|
||||
// Check if track is explicit and if explicit filter is enabled
|
||||
if (track.explicit && downloadQueue.isExplicitFilterEnabled()) {
|
||||
// Show placeholder for explicit content
|
||||
const loadingElExplicit = document.getElementById('loading');
|
||||
if (loadingElExplicit) loadingElExplicit.classList.add('hidden');
|
||||
|
||||
const placeholderContent = `
|
||||
<div class="explicit-filter-placeholder">
|
||||
<h2>Explicit Content Filtered</h2>
|
||||
<p>This track contains explicit content and has been filtered based on your settings.</p>
|
||||
<p>The explicit content filter is controlled by environment variables.</p>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const contentContainer = document.getElementById('track-header');
|
||||
if (contentContainer) {
|
||||
contentContainer.innerHTML = placeholderContent;
|
||||
contentContainer.classList.remove('hidden');
|
||||
}
|
||||
|
||||
return; // Stop rendering the actual track content
|
||||
}
|
||||
|
||||
// Update track information fields.
|
||||
const trackNameEl = document.getElementById('track-name');
|
||||
if (trackNameEl) {
|
||||
trackNameEl.innerHTML =
|
||||
`<a href="/track/${track.id || ''}" title="View track details">${track.name || 'Unknown Track'}</a>`;
|
||||
}
|
||||
|
||||
const trackArtistEl = document.getElementById('track-artist');
|
||||
if (trackArtistEl) {
|
||||
trackArtistEl.innerHTML =
|
||||
`By ${track.artists?.map((a: any) =>
|
||||
`<a href="/artist/${a?.id || ''}" title="View artist details">${a?.name || 'Unknown Artist'}</a>`
|
||||
).join(', ') || 'Unknown Artist'}`;
|
||||
}
|
||||
|
||||
const trackAlbumEl = document.getElementById('track-album');
|
||||
if (trackAlbumEl) {
|
||||
trackAlbumEl.innerHTML =
|
||||
`Album: <a href="/album/${track.album?.id || ''}" title="View album details">${track.album?.name || 'Unknown Album'}</a> (${track.album?.album_type || 'album'})`;
|
||||
}
|
||||
|
||||
const trackDurationEl = document.getElementById('track-duration');
|
||||
if (trackDurationEl) {
|
||||
trackDurationEl.textContent =
|
||||
`Duration: ${msToTime(track.duration_ms || 0)}`;
|
||||
}
|
||||
|
||||
const trackExplicitEl = document.getElementById('track-explicit');
|
||||
if (trackExplicitEl) {
|
||||
trackExplicitEl.textContent =
|
||||
track.explicit ? 'Explicit' : 'Clean';
|
||||
}
|
||||
|
||||
const imageUrl = (track.album?.images && track.album.images[0])
|
||||
? track.album.images[0].url
|
||||
: '/static/images/placeholder.jpg';
|
||||
const trackAlbumImageEl = document.getElementById('track-album-image') as HTMLImageElement;
|
||||
if (trackAlbumImageEl) trackAlbumImageEl.src = imageUrl;
|
||||
|
||||
// --- Insert Home Button (if not already present) ---
|
||||
let homeButton = document.getElementById('homeButton') as HTMLButtonElement;
|
||||
if (!homeButton) {
|
||||
homeButton = document.createElement('button');
|
||||
homeButton.id = 'homeButton';
|
||||
homeButton.className = 'home-btn';
|
||||
homeButton.innerHTML = `<img src="/static/images/home.svg" alt="Home" />`;
|
||||
// Prepend the home button into the header.
|
||||
const trackHeader = document.getElementById('track-header');
|
||||
if (trackHeader) {
|
||||
trackHeader.insertBefore(homeButton, trackHeader.firstChild);
|
||||
}
|
||||
}
|
||||
homeButton.addEventListener('click', () => {
|
||||
window.location.href = window.location.origin;
|
||||
});
|
||||
|
||||
// --- Move the Download Button from #actions into #track-header ---
|
||||
let downloadBtn = document.getElementById('downloadTrackBtn') as HTMLButtonElement;
|
||||
if (downloadBtn) {
|
||||
// Remove the parent container (#actions) if needed.
|
||||
const actionsContainer = document.getElementById('actions');
|
||||
if (actionsContainer) {
|
||||
actionsContainer.parentNode?.removeChild(actionsContainer);
|
||||
}
|
||||
// Set the inner HTML to use the download.svg icon.
|
||||
downloadBtn.innerHTML = `<img src="/static/images/download.svg" alt="Download">`;
|
||||
// Append the download button to the track header so it appears at the right.
|
||||
const trackHeader = document.getElementById('track-header');
|
||||
if (trackHeader) {
|
||||
trackHeader.appendChild(downloadBtn);
|
||||
}
|
||||
}
|
||||
|
||||
if (downloadBtn) {
|
||||
downloadBtn.addEventListener('click', () => {
|
||||
downloadBtn.disabled = true;
|
||||
downloadBtn.innerHTML = `<span>Queueing...</span>`;
|
||||
|
||||
const trackUrl = track.external_urls?.spotify || '';
|
||||
if (!trackUrl) {
|
||||
showError('Missing track URL');
|
||||
downloadBtn.disabled = false;
|
||||
downloadBtn.innerHTML = `<img src="/static/images/download.svg" alt="Download">`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Use the centralized downloadQueue.download method
|
||||
downloadQueue.download(trackUrl, 'track', { name: track.name || 'Unknown Track', artist: track.artists?.[0]?.name })
|
||||
.then(() => {
|
||||
downloadBtn.innerHTML = `<span>Queued!</span>`;
|
||||
// Make the queue visible to show the download
|
||||
downloadQueue.toggleVisibility(true);
|
||||
})
|
||||
.catch((err: any) => {
|
||||
showError('Failed to queue track download: ' + (err?.message || 'Unknown error'));
|
||||
downloadBtn.disabled = false;
|
||||
downloadBtn.innerHTML = `<img src="/static/images/download.svg" alt="Download">`;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Reveal the header now that track info is loaded.
|
||||
const trackHeaderEl = document.getElementById('track-header');
|
||||
if (trackHeaderEl) trackHeaderEl.classList.remove('hidden');
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts milliseconds to minutes:seconds.
|
||||
*/
|
||||
function msToTime(duration: number) {
|
||||
if (!duration || isNaN(duration)) return '0:00';
|
||||
|
||||
const minutes = Math.floor(duration / 60000);
|
||||
const seconds = Math.floor((duration % 60000) / 1000);
|
||||
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays an error message in the UI.
|
||||
*/
|
||||
function showError(message: string) {
|
||||
const errorEl = document.getElementById('error');
|
||||
if (errorEl) {
|
||||
errorEl.textContent = message || 'An error occurred';
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the download process by calling the centralized downloadQueue method
|
||||
*/
|
||||
async function startDownload(url: string, type: string, item: any) {
|
||||
if (!url || !type) {
|
||||
showError('Missing URL or type for download');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Use the centralized downloadQueue.download method
|
||||
await downloadQueue.download(url, type, item);
|
||||
|
||||
// Make the queue visible after queueing
|
||||
downloadQueue.toggleVisibility(true);
|
||||
} catch (error: any) {
|
||||
showError('Download failed: ' + (error?.message || 'Unknown error'));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user