feat: 实现网易云音乐同步服务核心功能与UI改进
添加完整的网易云音乐同步到Navidrome的功能实现,包括: 1. 新增Docker支持与相关配置文件 2. 实现歌单同步逻辑与Navidrome API集成 3. 改进前端UI界面与交互体验 4. 添加状态监控与错误处理机制 5. 实现定时同步功能与进度显示
This commit is contained in:
@@ -1,30 +1,59 @@
|
||||
const API_BASE = '/api';
|
||||
|
||||
let playlists = [];
|
||||
let pollingInterval = null;
|
||||
|
||||
function showError(message) {
|
||||
const errorDiv = document.getElementById('errorMessage');
|
||||
errorDiv.textContent = message;
|
||||
errorDiv.style.display = 'block';
|
||||
setTimeout(() => {
|
||||
errorDiv.style.display = 'none';
|
||||
}, 5000);
|
||||
}
|
||||
// Toast Notification System
|
||||
function showToast(message, type = 'info') {
|
||||
const container = document.getElementById('toast-container');
|
||||
const toast = document.createElement('div');
|
||||
|
||||
const colors = {
|
||||
info: 'bg-blue-500/80 border-blue-500/50',
|
||||
success: 'bg-green-500/80 border-green-500/50',
|
||||
error: 'bg-red-500/80 border-red-500/50',
|
||||
warning: 'bg-yellow-500/80 border-yellow-500/50'
|
||||
};
|
||||
|
||||
function showSuccess(message) {
|
||||
const successDiv = document.getElementById('successMessage');
|
||||
successDiv.textContent = message;
|
||||
successDiv.style.display = 'block';
|
||||
const icons = {
|
||||
info: 'fa-circle-info',
|
||||
success: 'fa-circle-check',
|
||||
error: 'fa-circle-exclamation',
|
||||
warning: 'fa-triangle-exclamation'
|
||||
};
|
||||
|
||||
toast.className = `glass-panel ${colors[type] || colors.info} border text-white px-4 py-3 rounded-xl flex items-center gap-3 shadow-xl transform transition-all duration-300 translate-x-full opacity-0`;
|
||||
toast.innerHTML = `
|
||||
<i class="fa-solid ${icons[type] || icons.info}"></i>
|
||||
<span class="text-sm font-medium">${message}</span>
|
||||
`;
|
||||
|
||||
container.appendChild(toast);
|
||||
|
||||
// Animation in
|
||||
requestAnimationFrame(() => {
|
||||
toast.classList.remove('translate-x-full', 'opacity-0');
|
||||
});
|
||||
|
||||
// Remove after delay
|
||||
setTimeout(() => {
|
||||
successDiv.style.display = 'none';
|
||||
toast.classList.add('translate-x-full', 'opacity-0');
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Format Utilities
|
||||
function formatTimestamp(timestamp) {
|
||||
if (!timestamp) return '从未同步';
|
||||
const date = new Date(timestamp);
|
||||
const now = new Date();
|
||||
const diff = now - date;
|
||||
|
||||
if (diff < 60000) return '刚刚';
|
||||
if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
|
||||
if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
|
||||
|
||||
return date.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
@@ -32,98 +61,182 @@ function formatTimestamp(timestamp) {
|
||||
});
|
||||
}
|
||||
|
||||
function getStatusClass(status) {
|
||||
function getStatusConfig(status) {
|
||||
switch (status) {
|
||||
case 'syncing':
|
||||
return 'status-syncing';
|
||||
return { text: '同步中', class: 'bg-yellow-500/80 text-white border-yellow-400/50 animate-pulse' };
|
||||
case 'success':
|
||||
return 'status-success';
|
||||
return { text: '已同步', class: 'bg-green-500/80 text-white border-green-400/50' };
|
||||
case 'failed':
|
||||
case 'error':
|
||||
return 'status-error';
|
||||
return { text: '失败', class: 'bg-red-500/80 text-white border-red-400/50' };
|
||||
default:
|
||||
return 'status-idle';
|
||||
return { text: '待同步', class: 'bg-gray-500/50 text-gray-300 border-gray-400/30' };
|
||||
}
|
||||
}
|
||||
|
||||
function getStatusText(status) {
|
||||
switch (status) {
|
||||
case 'syncing':
|
||||
return '同步中';
|
||||
case 'success':
|
||||
return '同步成功';
|
||||
case 'error':
|
||||
return '同步失败';
|
||||
default:
|
||||
return '待同步';
|
||||
}
|
||||
}
|
||||
|
||||
function renderPlaylists() {
|
||||
const container = document.getElementById('playlistList');
|
||||
|
||||
if (playlists.length === 0) {
|
||||
container.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M9 18V5l12-2v13"/>
|
||||
<circle cx="6" cy="18" r="3"/>
|
||||
<circle cx="18" cy="16" r="3"/>
|
||||
</svg>
|
||||
<p>还没有添加任何歌单</p>
|
||||
<p>在上方输入网易云音乐歌单ID或分享链接开始同步</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = playlists.map(playlist => `
|
||||
<div class="playlist-item">
|
||||
<div class="playlist-info">
|
||||
<div class="playlist-name">${playlist.name}</div>
|
||||
<div class="playlist-meta">
|
||||
<span>🆔 ${playlist.neteaseId}</span>
|
||||
<span>🎵 ${playlist.songs.length} 首歌曲</span>
|
||||
<span>⏰ ${formatTimestamp(playlist.lastSyncTime)}</span>
|
||||
<span class="status-badge ${getStatusClass(playlist.status)}">${getStatusText(playlist.status)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="playlist-actions">
|
||||
<button class="btn-sync" onclick="syncPlaylist('${playlist.id}')" ${playlist.status === 'syncing' ? 'disabled' : ''}>
|
||||
${playlist.status === 'syncing' ? '<span class="spinner"></span>' : '立即同步'}
|
||||
</button>
|
||||
<button class="btn-delete" onclick="deletePlaylist('${playlist.id}')">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// Core Logic
|
||||
async function loadPlaylists() {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/playlists`);
|
||||
if (!response.ok) throw new Error('加载歌单失败');
|
||||
playlists = await response.json();
|
||||
const data = await response.json();
|
||||
|
||||
// Deep compare to avoid unnecessary re-renders if nothing changed
|
||||
// For simplicity, we just check length and status of syncing items
|
||||
// But to ensure progress bars update smoothly, we re-render or update existing
|
||||
// Here we'll re-render for simplicity as the list is likely small
|
||||
playlists = data;
|
||||
updateStats();
|
||||
renderPlaylists();
|
||||
|
||||
// Adjust polling based on activity
|
||||
const anySyncing = playlists.some(p => p.status === 'syncing');
|
||||
adjustPolling(anySyncing);
|
||||
|
||||
} catch (error) {
|
||||
console.error('加载歌单失败:', error);
|
||||
showError('加载歌单失败: ' + error.message);
|
||||
showToast(error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function adjustPolling(isActive) {
|
||||
if (isActive && !pollingInterval) {
|
||||
pollingInterval = setInterval(loadPlaylists, 2000);
|
||||
} else if (!isActive && pollingInterval) {
|
||||
clearInterval(pollingInterval);
|
||||
pollingInterval = null;
|
||||
// Poll infrequently when idle just in case
|
||||
pollingInterval = setInterval(loadPlaylists, 10000);
|
||||
} else if (!pollingInterval) {
|
||||
// Default idle polling
|
||||
pollingInterval = setInterval(loadPlaylists, 10000);
|
||||
}
|
||||
}
|
||||
|
||||
function updateStats() {
|
||||
const total = playlists.length;
|
||||
const synced = playlists.filter(p => p.status === 'success').length;
|
||||
const syncing = playlists.filter(p => p.status === 'syncing').length;
|
||||
const songs = playlists.reduce((acc, curr) => acc + (curr.songs?.length || 0), 0);
|
||||
|
||||
// Animate numbers
|
||||
animateValue('stat-total', parseInt(document.getElementById('stat-total').innerText), total, 500);
|
||||
animateValue('stat-synced', parseInt(document.getElementById('stat-synced').innerText), synced, 500);
|
||||
animateValue('stat-songs', parseInt(document.getElementById('stat-songs').innerText), songs, 500);
|
||||
animateValue('stat-syncing', parseInt(document.getElementById('stat-syncing').innerText), syncing, 500);
|
||||
|
||||
const statsContainer = document.getElementById('stats-container');
|
||||
if (total > 0) {
|
||||
statsContainer.classList.remove('hidden');
|
||||
} else {
|
||||
statsContainer.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function animateValue(id, start, end, duration) {
|
||||
if (start === end) return;
|
||||
const obj = document.getElementById(id);
|
||||
const range = end - start;
|
||||
let current = start;
|
||||
const increment = end > start ? 1 : -1;
|
||||
const stepTime = Math.abs(Math.floor(duration / range));
|
||||
|
||||
const timer = setInterval(() => {
|
||||
current += increment;
|
||||
obj.innerHTML = current;
|
||||
if (current == end) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
}, Math.max(stepTime, 20)); // Cap speed
|
||||
}
|
||||
|
||||
function renderPlaylists() {
|
||||
const grid = document.getElementById('playlist-grid');
|
||||
const emptyState = document.getElementById('empty-state');
|
||||
const template = document.getElementById('playlist-card-template');
|
||||
|
||||
if (playlists.length === 0) {
|
||||
grid.innerHTML = '';
|
||||
emptyState.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
|
||||
emptyState.classList.add('hidden');
|
||||
|
||||
// We want to preserve existing elements to keep animations smooth if possible
|
||||
// But full re-render is safer for state consistency.
|
||||
// Optimization: Diffing by ID could be done here.
|
||||
|
||||
grid.innerHTML = ''; // Simple clear for now
|
||||
|
||||
playlists.forEach(playlist => {
|
||||
const clone = template.content.cloneNode(true);
|
||||
const card = clone.querySelector('div'); // The root div
|
||||
|
||||
// Data binding
|
||||
const img = clone.querySelector('.playlist-cover');
|
||||
img.src = playlist.cover || 'https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg'; // Fallback image
|
||||
img.alt = playlist.name;
|
||||
|
||||
clone.querySelector('.playlist-name').textContent = playlist.name;
|
||||
clone.querySelector('.playlist-count').textContent = (playlist.songs || []).length;
|
||||
clone.querySelector('.playlist-date').textContent = formatTimestamp(playlist.lastSyncTime);
|
||||
clone.querySelector('.playlist-id').textContent = `ID: ${playlist.neteaseId}`;
|
||||
clone.querySelector('.playlist-link').href = `https://music.163.com/#/playlist?id=${playlist.neteaseId}`;
|
||||
|
||||
// Status Badge
|
||||
const statusConfig = getStatusConfig(playlist.status);
|
||||
const badge = clone.querySelector('.playlist-status');
|
||||
badge.textContent = statusConfig.text;
|
||||
badge.className = `playlist-status px-2.5 py-1 rounded-full text-xs font-medium backdrop-blur-md border ${statusConfig.class}`;
|
||||
|
||||
// Actions
|
||||
const syncBtn = clone.querySelector('.action-sync');
|
||||
const deleteBtn = clone.querySelector('.action-delete');
|
||||
|
||||
syncBtn.onclick = () => syncPlaylist(playlist.id);
|
||||
deleteBtn.onclick = () => deletePlaylist(playlist.id);
|
||||
|
||||
if (playlist.status === 'syncing') {
|
||||
syncBtn.disabled = true;
|
||||
syncBtn.classList.add('opacity-50', 'cursor-not-allowed');
|
||||
syncBtn.querySelector('i').classList.add('fa-spin');
|
||||
|
||||
// Show Progress Overlay
|
||||
const overlay = clone.querySelector('.sync-overlay');
|
||||
overlay.classList.remove('translate-y-full');
|
||||
|
||||
clone.querySelector('.sync-message').textContent = playlist.syncMessage || '同步中...';
|
||||
clone.querySelector('.sync-percent').textContent = `${playlist.syncProgress || 0}%`;
|
||||
clone.querySelector('.sync-progress-bar').style.width = `${playlist.syncProgress || 0}%`;
|
||||
} else {
|
||||
// Hide overlay is default by CSS class
|
||||
}
|
||||
|
||||
grid.appendChild(clone);
|
||||
});
|
||||
}
|
||||
|
||||
// Actions
|
||||
async function addPlaylist() {
|
||||
const input = document.getElementById('playlistInput');
|
||||
const value = input.value.trim();
|
||||
|
||||
if (!value) {
|
||||
showError('请输入歌单ID或分享链接');
|
||||
showToast('请输入歌单 ID 或链接', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = document.querySelector('button[onclick="addPlaylist()"]');
|
||||
const originalIcon = btn.innerHTML;
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> 处理中...';
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/playlists`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: value })
|
||||
});
|
||||
|
||||
@@ -132,33 +245,36 @@ async function addPlaylist() {
|
||||
throw new Error(error.error || '添加歌单失败');
|
||||
}
|
||||
|
||||
const playlist = await response.json();
|
||||
playlists.push(playlist);
|
||||
renderPlaylists();
|
||||
await loadPlaylists(); // Refresh list
|
||||
input.value = '';
|
||||
showSuccess('歌单添加成功');
|
||||
showToast('歌单添加成功', 'success');
|
||||
} catch (error) {
|
||||
console.error('添加歌单失败:', error);
|
||||
showError('添加歌单失败: ' + error.message);
|
||||
showToast(error.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = originalIcon;
|
||||
}
|
||||
}
|
||||
|
||||
async function deletePlaylist(id) {
|
||||
if (!confirm('确定要删除这个歌单吗?')) return;
|
||||
if (!confirm('确定要移除这个歌单吗?')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/playlists/${id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('删除歌单失败');
|
||||
if (!response.ok) throw new Error('删除失败');
|
||||
|
||||
showToast('歌单已移除', 'success');
|
||||
// Optimistic update
|
||||
playlists = playlists.filter(p => p.id !== id);
|
||||
updateStats();
|
||||
renderPlaylists();
|
||||
showSuccess('歌单删除成功');
|
||||
} catch (error) {
|
||||
console.error('删除歌单失败:', error);
|
||||
showError('删除歌单失败: ' + error.message);
|
||||
showToast(error.message, 'error');
|
||||
loadPlaylists(); // Revert on error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,50 +286,19 @@ async function syncPlaylist(id) {
|
||||
|
||||
if (!response.ok) throw new Error('启动同步失败');
|
||||
|
||||
const playlist = await response.json();
|
||||
const index = playlists.findIndex(p => p.id === id);
|
||||
if (index !== -1) {
|
||||
playlists[index] = playlist;
|
||||
}
|
||||
renderPlaylists();
|
||||
showSuccess('同步已启动');
|
||||
showToast('已启动同步任务', 'info');
|
||||
loadPlaylists(); // Update UI immediately to show syncing state
|
||||
} catch (error) {
|
||||
console.error('启动同步失败:', error);
|
||||
showError('启动同步失败: ' + error.message);
|
||||
showToast(error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function updatePlaylistStatus(id) {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/status/${id}`);
|
||||
if (!response.ok) return;
|
||||
|
||||
const playlist = await response.json();
|
||||
const index = playlists.findIndex(p => p.id === id);
|
||||
if (index !== -1) {
|
||||
playlists[index] = playlist;
|
||||
renderPlaylists();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新状态失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function startStatusPolling() {
|
||||
setInterval(() => {
|
||||
playlists.forEach(playlist => {
|
||||
if (playlist.status === 'syncing') {
|
||||
updatePlaylistStatus(playlist.id);
|
||||
}
|
||||
});
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// Input Handler
|
||||
document.getElementById('playlistInput').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
addPlaylist();
|
||||
}
|
||||
});
|
||||
|
||||
loadPlaylists();
|
||||
startStatusPolling();
|
||||
// Initial Load
|
||||
loadPlaylists();
|
||||
Reference in New Issue
Block a user