Compare commits

...

4 Commits

17 changed files with 1425 additions and 308 deletions

View File

@@ -40,6 +40,7 @@ module.exports = {
'vue/multi-word-component-names': 'off',
'no-nested-ternary': 'off',
'no-console': 'off',
'no-await-in-loop': 'off',
'no-continue': 'off',
'no-restricted-syntax': 'off',
'no-return-assign': 'off',

View File

@@ -1,8 +1,8 @@
# 更新日志
## [v3.4.0] - 2025-01-11
## [v3.5.0] - 2025-01-12
### ✨ 新功能
- 添加捐赠支持列表
- 添加收藏列表 批量下载功能
- 优化搜藏列表 可本地和线上收藏合并 如果收藏失败 会自动收藏到本地
- 添加下载管理 进度显示 播放下载的音乐
- 添加缓存管理 清理缓存
- 优化下载格式问题 支持下载其他格式 ps:其实之前只是后缀名问题

View File

@@ -3,13 +3,15 @@
- 音乐推荐
- 网易云登录
- 播放历史
- 播放历史 歌曲收藏
- 桌面歌词
- 歌单 mv 搜索 专辑等功能
- 识别无法播放歌曲 并解析播放
- 主题切换 更新检测
- 本地服务 不依赖线上服务
- 可听周杰伦(搜索专辑)
- 支持歌曲下载(歌曲右键)
- 支持音质选择网易云VIP
## 项目简介
一个基于 electron typescript vue3 的桌面音乐播放器 适配 web端 桌面端 web移动端
@@ -40,49 +42,6 @@ QQ群:789288579
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: |
| <img src="https://github.com/algerkong/algerkong/blob/main/wechat.jpg?raw=true" alt="WeChat QRcode" width=200> | <img src="https://github.com/algerkong/algerkong/blob/main/alipay.jpg?raw=true" alt="Wechat QRcode" width=200> |
## 项目运行
```bash
# 安装依赖
npm install
# 运行项目 web
npm run dev
# 运行项目 electron
npm run start
# 打包项目 web
npm run build
# 打包项目 electron
npm run win ...
# 具体看 package.json
```
#### 注意
- 本地运行需要配置 .env.development 文件
- 打包需要配置 .env.production 文件
```bash
# .env.development
VITE_API_LOCAL = /api
VITE_API_MUSIC_PROXY = /music
VITE_API_PROXY_MUSIC = /music_proxy
# 你的接口地址 (必填)
VITE_API = ***
# 音乐po接口地址
VITE_API_MUSIC = ***
VITE_API_PROXY = ***
# .env.production
# 你的接口地址 (必填)
VITE_API = ***
# 音乐po接口地址
VITE_API_MUSIC = ***
# 代理地址
VITE_API_PROXY = ***
```
## Stargazers over time
[![Stargazers over time](https://starchart.cc/algerkong/AlgerMusicPlayer.svg?variant=adaptive)](https://starchart.cc/algerkong/AlgerMusicPlayer)

View File

@@ -1,6 +1,6 @@
{
"name": "AlgerMusicPlayer",
"version": "3.4.0",
"version": "3.5.0",
"description": "Alger Music Player",
"author": "Alger <algerkc@qq.com>",
"main": "./out/main/index.js",

View File

@@ -1,13 +1,53 @@
import axios from 'axios';
import { app, dialog, ipcMain, shell } from 'electron';
import { app, dialog, ipcMain, protocol, shell } from 'electron';
import Store from 'electron-store';
import * as fs from 'fs';
import * as path from 'path';
const MAX_CONCURRENT_DOWNLOADS = 3;
const downloadQueue: { url: string; filename: string; songInfo: any; type?: string }[] = [];
let activeDownloads = 0;
// 创建一个store实例用于存储下载历史
const downloadStore = new Store({
name: 'downloads',
defaults: {
history: []
}
});
// 创建一个store实例用于存储音频缓存
const audioCacheStore = new Store({
name: 'audioCache',
defaults: {
cache: {}
}
});
/**
* 初始化文件管理相关的IPC监听
*/
export function initializeFileManager() {
// 注册本地文件协议
protocol.registerFileProtocol('local', (request, callback) => {
try {
const decodedUrl = decodeURIComponent(request.url);
const filePath = decodedUrl.replace('local://', '');
// 检查文件是否存在
if (!fs.existsSync(filePath)) {
console.error('File not found:', filePath);
callback({ error: -6 }); // net::ERR_FILE_NOT_FOUND
return;
}
callback({ path: filePath });
} catch (error) {
console.error('Error handling local protocol:', error);
callback({ error: -2 }); // net::FAILED
}
});
// 通用的选择目录处理
ipcMain.handle('select-directory', async () => {
const result = await dialog.showOpenDialog({
@@ -18,12 +58,194 @@ export function initializeFileManager() {
});
// 通用的打开目录处理
ipcMain.on('open-directory', (_, path) => {
shell.openPath(path);
ipcMain.on('open-directory', (_, filePath) => {
try {
if (fs.statSync(filePath).isDirectory()) {
shell.openPath(filePath);
} else {
shell.showItemInFolder(filePath);
}
} catch (error) {
console.error('Error opening path:', error);
}
});
// 下载音乐处理
ipcMain.on('download-music', downloadMusic);
ipcMain.on('download-music', handleDownloadRequest);
// 检查文件是否已下载
ipcMain.handle('check-music-downloaded', (_, filename: string) => {
const store = new Store();
const downloadPath = (store.get('set.downloadPath') as string) || app.getPath('downloads');
const filePath = path.join(downloadPath, `${filename}.mp3`);
return fs.existsSync(filePath);
});
// 删除已下载的音乐
ipcMain.handle('delete-downloaded-music', async (_, filePath: string) => {
try {
if (fs.existsSync(filePath)) {
// 先删除文件
try {
await fs.promises.unlink(filePath);
} catch (error) {
console.error('Error deleting file:', error);
}
// 删除对应的歌曲信息
const store = new Store();
const songInfos = store.get('downloadedSongs', {}) as Record<string, any>;
delete songInfos[filePath];
store.set('downloadedSongs', songInfos);
return true;
}
return false;
} catch (error) {
console.error('Error deleting file:', error);
return false;
}
});
// 获取已下载音乐列表
ipcMain.handle('get-downloaded-music', () => {
try {
const store = new Store();
const songInfos = store.get('downloadedSongs', {}) as Record<string, any>;
// 过滤出实际存在的文件
const validSongs = Object.entries(songInfos)
.filter(([path]) => fs.existsSync(path))
.map(([_, info]) => info)
.sort((a, b) => (b.downloadTime || 0) - (a.downloadTime || 0));
// 更新存储,移除不存在的文件记录
const newSongInfos = validSongs.reduce((acc, song) => {
acc[song.path] = song;
return acc;
}, {});
store.set('downloadedSongs', newSongInfos);
return validSongs;
} catch (error) {
console.error('Error getting downloaded music:', error);
return [];
}
});
// 检查歌曲是否已下载并返回本地路径
ipcMain.handle('check-song-downloaded', (_, songId: number) => {
const store = new Store();
const songInfos = store.get('downloadedSongs', {}) as Record<string, any>;
// 通过ID查找已下载的歌曲
for (const [path, info] of Object.entries(songInfos)) {
if (info.id === songId && fs.existsSync(path)) {
return {
isDownloaded: true,
localPath: `local://${path}`,
songInfo: info
};
}
}
return {
isDownloaded: false,
localPath: '',
songInfo: null
};
});
// 添加清除下载历史的处理函数
ipcMain.on('clear-downloads-history', () => {
downloadStore.set('history', []);
});
// 添加清除音频缓存的处理函数
ipcMain.on('clear-audio-cache', () => {
audioCacheStore.set('cache', {});
// 清除临时音频文件目录
const tempDir = path.join(app.getPath('userData'), 'AudioCache');
if (fs.existsSync(tempDir)) {
try {
fs.readdirSync(tempDir).forEach((file) => {
const filePath = path.join(tempDir, file);
if (file.endsWith('.mp3') || file.endsWith('.m4a')) {
fs.unlinkSync(filePath);
}
});
} catch (error) {
console.error('清除音频缓存文件失败:', error);
}
}
});
}
/**
* 处理下载请求
*/
function handleDownloadRequest(
event: Electron.IpcMainEvent,
{
url,
filename,
songInfo,
type
}: { url: string; filename: string; songInfo?: any; type?: string }
) {
// 检查是否已经在队列中或正在下载
if (downloadQueue.some((item) => item.filename === filename)) {
event.reply('music-download-error', {
filename,
error: '该歌曲已在下载队列中'
});
return;
}
// 检查是否已下载
const store = new Store();
const songInfos = store.get('downloadedSongs', {}) as Record<string, any>;
// 检查是否已下载通过ID
const isDownloaded =
songInfo?.id && Object.values(songInfos).some((info: any) => info.id === songInfo.id);
if (isDownloaded) {
event.reply('music-download-error', {
filename,
error: '该歌曲已下载'
});
return;
}
// 添加到下载队列
downloadQueue.push({ url, filename, songInfo, type });
event.reply('music-download-queued', {
filename,
songInfo
});
// 尝试开始下载
processDownloadQueue(event);
}
/**
* 处理下载队列
*/
async function processDownloadQueue(event: Electron.IpcMainEvent) {
if (activeDownloads >= MAX_CONCURRENT_DOWNLOADS || downloadQueue.length === 0) {
return;
}
const { url, filename, songInfo, type } = downloadQueue.shift()!;
activeDownloads++;
try {
await downloadMusic(event, { url, filename, songInfo, type });
} finally {
activeDownloads--;
processDownloadQueue(event);
}
}
/**
@@ -31,17 +253,26 @@ export function initializeFileManager() {
*/
async function downloadMusic(
event: Electron.IpcMainEvent,
{ url, filename }: { url: string; filename: string }
{
url,
filename,
songInfo,
type = 'mp3'
}: { url: string; filename: string; songInfo: any; type?: string }
) {
let finalFilePath = '';
let writer: fs.WriteStream | null = null;
try {
const store = new Store();
const downloadPath = (store.get('set.downloadPath') as string) || app.getPath('downloads');
// 直接使用配置的下载路径
const filePath = path.join(downloadPath, `${filename}.mp3`);
// 从URL中获取文件扩展名如果没有则使用传入的type或默认mp3
const urlExt = type ? `.${type}` : '.mp3';
const filePath = path.join(downloadPath, `${filename}${urlExt}`);
// 检查文件是否已存在,如果存在则添加序号
let finalFilePath = filePath;
finalFilePath = filePath;
let counter = 1;
while (fs.existsSync(finalFilePath)) {
const ext = path.extname(filePath);
@@ -50,23 +281,115 @@ async function downloadMusic(
counter++;
}
// 先获取文件大小
const headResponse = await axios.head(url);
const totalSize = parseInt(headResponse.headers['content-length'] || '0', 10);
// 开始下载
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
responseType: 'stream',
timeout: 30000 // 30秒超时
});
const writer = fs.createWriteStream(finalFilePath);
response.data.pipe(writer);
writer = fs.createWriteStream(finalFilePath);
let downloadedSize = 0;
writer.on('finish', () => {
event.reply('music-download-complete', { success: true, path: finalFilePath });
// 使用 data 事件来跟踪下载进度
response.data.on('data', (chunk: Buffer) => {
downloadedSize += chunk.length;
const progress = Math.round((downloadedSize / totalSize) * 100);
event.reply('music-download-progress', {
filename,
progress,
loaded: downloadedSize,
total: totalSize,
path: finalFilePath,
status: progress === 100 ? 'completed' : 'downloading',
songInfo: songInfo || {
name: filename,
ar: [{ name: '本地音乐' }],
picUrl: '/images/default_cover.png'
}
});
});
writer.on('error', (err) => {
event.reply('music-download-complete', { success: false, error: err.message });
// 等待下载完成
await new Promise((resolve, reject) => {
writer!.on('finish', resolve);
writer!.on('error', reject);
response.data.pipe(writer!);
});
// 验证文件是否完整下载
const stats = fs.statSync(finalFilePath);
if (stats.size !== totalSize) {
throw new Error('文件下载不完整');
}
// 保存下载信息
try {
const songInfos = store.get('downloadedSongs', {}) as Record<string, any>;
const defaultInfo = {
name: filename,
ar: [{ name: '本地音乐' }],
picUrl: '/images/default_cover.png'
};
const newSongInfo = {
id: songInfo?.id || 0,
name: songInfo?.name || filename,
filename,
picUrl: songInfo?.picUrl || defaultInfo.picUrl,
ar: songInfo?.ar || defaultInfo.ar,
size: totalSize,
path: finalFilePath,
downloadTime: Date.now(),
al: songInfo?.al || { picUrl: songInfo?.picUrl || defaultInfo.picUrl },
type: type || 'mp3'
};
// 保存到下载记录
songInfos[finalFilePath] = newSongInfo;
store.set('downloadedSongs', songInfos);
// 添加到下载历史
const history = downloadStore.get('history', []) as any[];
history.unshift(newSongInfo);
downloadStore.set('history', history);
// 发送下载完成事件
event.reply('music-download-complete', {
success: true,
path: finalFilePath,
filename,
size: totalSize,
songInfo: newSongInfo
});
} catch (error) {
console.error('Error saving download info:', error);
throw new Error('保存下载信息失败');
}
} catch (error: any) {
event.reply('music-download-complete', { success: false, error: error.message });
console.error('Download error:', error);
// 清理未完成的下载
if (writer) {
writer.end();
}
if (finalFilePath && fs.existsSync(finalFilePath)) {
try {
fs.unlinkSync(finalFilePath);
} catch (e) {
console.error('Failed to delete incomplete download:', e);
}
}
event.reply('music-download-complete', {
success: false,
error: error.message || '下载失败',
filename
});
}
}

View File

@@ -19,7 +19,7 @@ export const getMusicUrl = async (id: number) => {
});
if (res.data.data.url) {
return { data: { data: [{ url: res.data.data.url }] } };
return { data: { data: [{ ...res.data.data }] } };
}
return await request.get('/song/url/v1', {

View File

@@ -8,12 +8,16 @@ export {}
declare module 'vue' {
export interface GlobalComponents {
NAvatar: typeof import('naive-ui')['NAvatar']
NBadge: typeof import('naive-ui')['NBadge']
NButton: typeof import('naive-ui')['NButton']
NButtonGroup: typeof import('naive-ui')['NButtonGroup']
NCard: typeof import('naive-ui')['NCard']
NCheckbox: typeof import('naive-ui')['NCheckbox']
NCheckboxGroup: typeof import('naive-ui')['NCheckboxGroup']
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
NDialogProvider: typeof import('naive-ui')['NDialogProvider']
NDrawer: typeof import('naive-ui')['NDrawer']
NDrawerContent: typeof import('naive-ui')['NDrawerContent']
NDropdown: typeof import('naive-ui')['NDropdown']
NEllipsis: typeof import('naive-ui')['NEllipsis']
NEmpty: typeof import('naive-ui')['NEmpty']
@@ -26,13 +30,16 @@ declare module 'vue' {
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
NModal: typeof import('naive-ui')['NModal']
NPopover: typeof import('naive-ui')['NPopover']
NProgress: typeof import('naive-ui')['NProgress']
NScrollbar: typeof import('naive-ui')['NScrollbar']
NSelect: typeof import('naive-ui')['NSelect']
NSlider: typeof import('naive-ui')['NSlider']
NSpace: typeof import('naive-ui')['NSpace']
NSpin: typeof import('naive-ui')['NSpin']
NSwitch: typeof import('naive-ui')['NSwitch']
NTabPane: typeof import('naive-ui')['NTabPane']
NTabs: typeof import('naive-ui')['NTabs']
NTag: typeof import('naive-ui')['NTag']
NText: typeof import('naive-ui')['NText']
NTooltip: typeof import('naive-ui')['NTooltip']
NVirtualList: typeof import('naive-ui')['NVirtualList']
RouterLink: typeof import('vue-router')['RouterLink']

View File

@@ -315,7 +315,6 @@ onUnmounted(() => {
if (cursorTimer) {
clearTimeout(cursorTimer);
}
unlockScreenOrientation();
});
// 监听 currentMv 的变化
@@ -416,27 +415,6 @@ const checkFullscreenAPI = () => {
};
};
// 添加横屏锁定功能
const lockScreenOrientation = async () => {
try {
if ('orientation' in screen) {
await (screen as any).orientation.lock('landscape');
}
} catch (error) {
console.warn('无法锁定屏幕方向:', error);
}
};
const unlockScreenOrientation = () => {
try {
if ('orientation' in screen) {
(screen as any).orientation.unlock();
}
} catch (error) {
console.warn('无法解锁屏幕方向:', error);
}
};
// 修改切换全屏状态的方法
const toggleFullscreen = async () => {
const api = checkFullscreenAPI();
@@ -450,17 +428,9 @@ const toggleFullscreen = async () => {
if (!api.fullscreenElement) {
await videoContainerRef.value?.requestFullscreen();
isFullscreen.value = true;
// 在移动端进入全屏时锁定横屏
if (window.innerWidth <= 768) {
await lockScreenOrientation();
}
} else {
await document.exitFullscreen();
isFullscreen.value = false;
// 退出全屏时解锁屏幕方向
if (window.innerWidth <= 768) {
unlockScreenOrientation();
}
}
} catch (error) {
console.error('切换全屏失败:', error);

View File

@@ -1,8 +1,16 @@
<template>
<div class="donation-container">
<div class="donation-grid">
<div class="refresh-container">
<n-button secondary round size="small" :loading="isLoading" @click="fetchDonors">
<template #icon>
<i class="ri-refresh-line"></i>
</template>
刷新列表
</n-button>
</div>
<div class="donation-grid" :class="{ 'grid-expanded': isExpanded }">
<div
v-for="(donor, index) in sortedDonors"
v-for="(donor, index) in displayDonors"
:key="donor.id"
class="donation-card animate__animated"
:class="getAnimationClass(index)"
@@ -37,17 +45,37 @@
</n-tag>
<span class="donation-date">{{ donor.date }}</span>
</div>
<div v-if="donor.message" class="donation-message">
</div>
</div>
<div v-if="donor.message" class="donation-message">
<n-popover trigger="hover" placement="bottom">
<template #trigger>
<div class="message-content">
<i class="ri-double-quotes-l quote-icon"></i>
<div class="message-text">{{ donor.message }}</div>
<i class="ri-double-quotes-r quote-icon"></i>
</div>
</template>
<div class="message-popup">
<i class="ri-double-quotes-l quote-icon"></i>
{{ donor.message }}
<i class="ri-double-quotes-r quote-icon"></i>
</div>
</div>
</n-popover>
</div>
<div class="card-sparkles"></div>
</div>
</div>
<div v-if="sortedDonors.length > 8" class="expand-button">
<n-button text @click="toggleExpand">
<template #icon>
<i :class="isExpanded ? 'ri-arrow-up-s-line' : 'ri-arrow-down-s-line'"></i>
</template>
{{ isExpanded ? '收起' : '展开更多' }}
</n-button>
</div>
<div class="p-6 rounded-lg shadow-lg bg-light dark:bg-gray-800">
<div class="flex justify-between">
<div class="flex flex-col items-center gap-2">
@@ -77,7 +105,7 @@
import 'animate.css';
import axios from 'axios';
import { computed, ref } from 'vue';
import { computed, onActivated, onMounted, ref } from 'vue';
import alipay from '@/assets/alipay.png';
import wechat from '@/assets/wechat.png';
@@ -97,58 +125,12 @@ interface Donor {
badgeColor: string;
}
const donors = ref<Donor[]>([
{
id: 6,
name: '*桤',
amount: 5,
date: '2025-01-01',
badge: '开源赞助',
badgeColor: '#FF69B4'
},
{
id: 5,
name: '*木',
amount: 1,
date: '2024-12-26',
badge: '开源赞助',
badgeColor: '#FF69B4'
},
{
id: 4,
name: '**兴',
amount: 5,
date: '2024-12-25',
badge: '开源赞助',
badgeColor: '#FF69B4'
},
{
id: 3,
name: 's*r',
amount: 1.68,
date: '2024-12-25',
badge: '开源赞助',
badgeColor: '#FF69B4'
},
{
id: 2,
name: 'G*Y',
amount: 1.99,
date: '2024-12-18',
badge: '开源赞助',
badgeColor: '#FF69B4'
},
{
id: 1,
name: '*辉',
amount: 1,
date: '2024-12-15',
badge: '开源赞助',
badgeColor: '#FF69B4'
}
]);
const donors = ref<Donor[]>([]);
onMounted(async () => {
const isLoading = ref(false);
const fetchDonors = async () => {
isLoading.value = true;
try {
const response = await axios.get(
'https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/data/main/donors.json'
@@ -159,7 +141,17 @@ onMounted(async () => {
}));
} catch (error) {
console.error('Failed to fetch donors:', error);
} finally {
isLoading.value = false;
}
};
onMounted(() => {
fetchDonors();
});
onActivated(() => {
fetchDonors();
});
// 动画类名列表
@@ -192,8 +184,8 @@ const getBadgeClass = (badge: string): string => {
// 鼠标悬停效果
const handleMouseEnter = (event: MouseEvent) => {
const card = event.currentTarget as HTMLElement;
card.style.transform = 'translateY(-5px) scale(1.02)';
card.style.boxShadow = '0 8px 30px rgba(0, 0, 0, 0.12)';
card.style.transform = 'translateY(-2px)';
card.style.boxShadow = '0 8px 20px rgba(0, 0, 0, 0.12)';
// 添加金额标签动画
const amountTag = card.querySelector('.donation-amount');
@@ -204,8 +196,8 @@ const handleMouseEnter = (event: MouseEvent) => {
const handleMouseLeave = (event: MouseEvent) => {
const card = event.currentTarget as HTMLElement;
card.style.transform = 'translateY(0) scale(1)';
card.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)';
card.style.transform = 'translateY(0)';
card.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.08)';
// 移除金额标签动画
const amountTag = card.querySelector('.donation-amount');
@@ -214,10 +206,14 @@ const handleMouseLeave = (event: MouseEvent) => {
}
};
// 按金额排序的捐赠列表
// 按金额和留言排序的捐赠列表
const sortedDonors = computed(() => {
return [...donors.value].sort((a, b) => {
// 首先按金额从大到小排序
// 如果一个有留言一个没有,有留言的排在前面
if (a.message && !b.message) return -1;
if (!a.message && b.message) return 1;
// 都有留言或都没有留言时,按金额从大到小排序
const amountDiff = b.amount - a.amount;
if (amountDiff !== 0) return amountDiff;
@@ -225,6 +221,19 @@ const sortedDonors = computed(() => {
return new Date(b.date).getTime() - new Date(a.date).getTime();
});
});
const isExpanded = ref(false);
const displayDonors = computed(() => {
if (isExpanded.value) {
return sortedDonors.value;
}
return sortedDonors.value.slice(0, 8);
});
const toggleExpand = () => {
isExpanded.value = !isExpanded.value;
};
</script>
<style lang="scss" scoped>
@@ -233,122 +242,145 @@ const sortedDonors = computed(() => {
}
.donation-grid {
@apply grid gap-3 px-2 py-3;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
@apply grid gap-3 px-2 py-3 transition-all duration-300 overflow-hidden;
grid-template-columns: repeat(2, 1fr);
max-height: 280px;
@media (min-width: 768px) {
grid-template-columns: repeat(3, 1fr);
}
@media (min-width: 1024px) {
grid-template-columns: repeat(4, 1fr);
}
&.grid-expanded {
@apply max-h-none;
}
}
.donation-card {
@apply relative overflow-hidden rounded-lg p-3;
background: linear-gradient(145deg, rgba(255, 255, 255, 0.03), rgba(255, 255, 255, 0.08));
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.08);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
animation-duration: 0.8s;
@apply relative rounded-lg p-3 min-w-0 w-full transition-all duration-500 shadow-md backdrop-blur-md;
@apply bg-gradient-to-br from-white/[0.03] to-white/[0.08] border border-white/[0.08];
@apply hover:shadow-lg;
.card-content {
@apply relative z-10 flex items-start gap-3;
}
.donor-avatar {
@apply relative flex-shrink-0 w-10 h-9 transition-transform duration-300;
.avatar-img {
@apply border border-white/20 dark:border-gray-800/50 shadow-sm;
@apply w-10 h-9;
}
}
.donor-badge {
@apply absolute -bottom-2 -right-1 px-1.5 py-0.5 text-xs font-medium text-white/90 rounded-full whitespace-nowrap;
@apply bg-gradient-to-r from-pink-400 to-pink-500 shadow-sm opacity-90 scale-90;
@apply transition-all duration-300;
}
.donor-info {
@apply flex-1 min-w-0;
.donor-name {
@apply text-sm font-medium mb-0.5 truncate;
}
.donation-meta {
@apply flex items-center gap-2 mb-1;
.donation-date {
@apply text-xs text-gray-400/80 dark:text-gray-500/80;
}
}
}
.donation-message {
@apply text-sm text-gray-600 dark:text-gray-300 leading-relaxed mt-3 w-full;
.message-content {
@apply relative p-2 rounded-lg transition-all duration-300 cursor-pointer;
@apply bg-white/[0.02] hover:bg-[var(--n-color)];
.message-text {
@apply px-6 italic line-clamp-2;
}
.quote-icon {
@apply absolute text-gray-400/60 dark:text-gray-500/60 text-sm;
&:first-child {
@apply left-0.5 top-2;
}
&:last-child {
@apply right-0.5 bottom-2;
}
}
}
}
&:hover {
.card-sparkles {
opacity: 0.4;
}
.donor-avatar {
transform: scale(1.05);
}
}
}
.card-content {
@apply relative z-10 flex items-start gap-3;
}
.donor-avatar {
@apply relative flex-shrink-0;
transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
.avatar-img {
@apply border border-white/20 dark:border-gray-800/50;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
width: 40px !important;
height: 36px !important;
}
}
.donor-badge {
@apply absolute -bottom-0.5 -right-0.5 px-1 py-0.5 text-xs font-medium text-white/90 rounded-full;
font-size: 0.5rem;
transform: scale(0.8);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
line-height: 1;
background: linear-gradient(45deg, #ff69b4, #ff1493);
opacity: 0.85;
}
.donor-info {
@apply flex-1 min-w-0;
}
.donor-name {
@apply text-sm font-medium mb-0.5 truncate;
color: var(--color-text);
}
.donation-meta {
@apply flex items-center gap-2 mb-1;
}
.donation-amount {
@apply text-xs font-medium;
}
.donation-date {
@apply text-xs text-gray-400/80 dark:text-gray-500/80;
}
.donation-message {
@apply text-sm text-gray-600 dark:text-gray-300 leading-relaxed;
@apply relative pl-4 pr-4;
font-style: italic;
.quote-icon {
@apply text-gray-400 dark:text-gray-500 absolute;
font-size: 0.8rem;
&:first-child {
left: 0;
top: 0;
@apply scale-105 rotate-3;
}
&:last-child {
right: 0;
bottom: 0;
.donor-badge {
@apply scale-95 -translate-y-0.5;
}
.card-sparkles {
@apply opacity-60 scale-110;
}
}
}
.card-sparkles {
@apply absolute inset-0 pointer-events-none opacity-0;
background-image: radial-gradient(
1.5px 1.5px at 20px 30px,
rgba(255, 255, 255, 0.95),
rgba(0, 0, 0, 0)
),
radial-gradient(1.5px 1.5px at 40px 70px, rgba(255, 255, 255, 0.95), rgba(0, 0, 0, 0)),
radial-gradient(2px 2px at 50px 160px, rgba(255, 255, 255, 0.95), rgba(0, 0, 0, 0)),
radial-gradient(1.5px 1.5px at 90px 40px, rgba(255, 255, 255, 0.95), rgba(0, 0, 0, 0)),
radial-gradient(2px 2px at 130px 80px, rgba(255, 255, 255, 0.95), rgba(0, 0, 0, 0));
@apply absolute inset-0 pointer-events-none opacity-0 transition-all duration-500;
background-image: radial-gradient(2px 2px at 20px 30px, rgba(255, 255, 255, 0.95), transparent),
radial-gradient(2px 2px at 40px 70px, rgba(255, 255, 255, 0.95), transparent),
radial-gradient(2.5px 2.5px at 50px 160px, rgba(255, 255, 255, 0.95), transparent),
radial-gradient(2px 2px at 90px 40px, rgba(255, 255, 255, 0.95), transparent),
radial-gradient(2.5px 2.5px at 130px 80px, rgba(255, 255, 255, 0.95), transparent);
background-size: 200% 200%;
animation: sparkle 5s ease infinite;
transition: opacity 0.5s ease;
animation: sparkle 8s ease infinite;
}
@keyframes sparkle {
0%,
100% {
background-position: 0% 0%;
opacity: 0.4;
@apply bg-[0%_0%] opacity-40 scale-100;
}
50% {
background-position: 100% 100%;
opacity: 0.8;
@apply bg-[100%_100%] opacity-80 scale-110;
}
}
.refresh-container {
@apply flex justify-end px-2 py-2;
}
.expand-button {
@apply flex justify-center items-center py-2;
:deep(.n-button) {
@apply transition-all duration-300 hover:-translate-y-0.5;
}
}
.message-popup {
@apply relative px-4 py-2 text-sm;
max-width: 300px;
line-height: 1.6;
font-style: italic;
.quote-icon {
@apply text-gray-400/60 dark:text-gray-500/60;
font-size: 0.9rem;
}
}
</style>

View File

@@ -0,0 +1,590 @@
<template>
<div class="download-drawer-trigger">
<n-badge :value="downloadingCount" :max="99" :show="downloadingCount > 0">
<n-button circle @click="showDrawer = true">
<template #icon>
<i class="iconfont ri-download-cloud-2-line"></i>
</template>
</n-button>
</n-badge>
</div>
<n-drawer v-model:show="showDrawer" :height="'80%'" placement="bottom">
<n-drawer-content title="下载管理" closable :native-scrollbar="false">
<div class="drawer-container">
<n-tabs type="line" animated class="h-full">
<!-- 下载列表 -->
<n-tab-pane name="downloading" tab="下载中" class="h-full">
<div class="download-list">
<div v-if="downloadList.length === 0" class="empty-tip">
<n-empty description="暂无下载任务" />
</div>
<template v-else>
<div class="total-progress">
<div class="total-progress-text">总进度: {{ totalProgress.toFixed(1) }}%</div>
<n-progress
type="line"
:percentage="Number(totalProgress.toFixed(1))"
:height="12"
:border-radius="6"
:indicator-placement="'inside'"
/>
</div>
<div class="download-content">
<div class="download-items">
<div v-for="item in downloadList" :key="item.path" class="download-item">
<div class="download-item-content">
<div class="download-item-cover">
<n-image
:src="getImgUrl(item.songInfo?.picUrl, '200y200')"
preview-disabled
:object-fit="'cover'"
class="cover-image"
/>
</div>
<div class="download-item-info">
<div class="download-item-name" :title="item.filename">
{{ item.filename }}
</div>
<div class="download-item-artist">
{{ item.songInfo?.ar?.map((a) => a.name).join(', ') || '未知歌手' }}
</div>
<div class="download-item-progress">
<n-progress
type="line"
:percentage="item.progress"
:processing="item.status === 'downloading'"
:status="getProgressStatus(item)"
:height="8"
/>
</div>
<div class="download-item-size">
<span
>{{ formatSize(item.loaded) }} / {{ formatSize(item.total) }}</span
>
</div>
</div>
<div class="download-item-status">
<n-tag :type="getStatusType(item)" size="small">
{{ getStatusText(item) }}
</n-tag>
</div>
</div>
</div>
</div>
</div>
</template>
</div>
</n-tab-pane>
<!-- 已下载列表 -->
<n-tab-pane name="downloaded" tab="已下载" class="h-full">
<div class="downloaded-list">
<div v-if="downloadedList.length === 0" class="empty-tip">
<n-empty description="暂无已下载歌曲" />
</div>
<div v-else class="downloaded-content">
<div class="downloaded-items">
<div v-for="item in downloadedList" :key="item.path" class="downloaded-item">
<div class="downloaded-item-content">
<div class="downloaded-item-cover">
<n-image
:src="getImgUrl(item.picUrl, '200y200')"
preview-disabled
:object-fit="'cover'"
class="cover-image"
/>
</div>
<div class="downloaded-item-info">
<div class="downloaded-item-name" :title="item.filename">
{{ item.filename }}
</div>
<div class="downloaded-item-artist">
{{ item.ar?.map((a) => a.name).join(', ') }}
</div>
<div class="downloaded-item-size">{{ formatSize(item.size) }}</div>
</div>
<div class="downloaded-item-actions">
<n-button text type="primary" size="large" @click="handlePlayMusic(item)">
<template #icon>
<i class="iconfont ri-play-circle-line text-xl"></i>
</template>
</n-button>
<n-button
text
type="primary"
size="large"
@click="openDirectory(item.path)"
>
<template #icon>
<i class="iconfont ri-folder-open-line text-xl"></i>
</template>
</n-button>
<n-button text type="error" size="large" @click="handleDelete(item)">
<template #icon>
<i class="iconfont ri-delete-bin-line text-xl"></i>
</template>
</n-button>
</div>
</div>
</div>
</div>
</div>
</div>
</n-tab-pane>
</n-tabs>
</div>
</n-drawer-content>
</n-drawer>
<!-- 删除确认对话框 -->
<n-modal v-model:show="showDeleteConfirm" preset="dialog" type="warning" title="删除确认">
<template #header>
<div class="flex items-center">
<i class="iconfont ri-error-warning-line mr-2 text-xl"></i>
<span>删除确认</span>
</div>
</template>
<div class="delete-confirm-content">
确定要删除歌曲 "{{ itemToDelete?.filename }}" 此操作不可恢复
</div>
<template #action>
<n-button size="small" @click="showDeleteConfirm = false">取消</n-button>
<n-button size="small" type="warning" @click="confirmDelete">确定删除</n-button>
</template>
</n-modal>
</template>
<script setup lang="ts">
import type { ProgressStatus } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { computed, onMounted, ref } from 'vue';
import { useStore } from 'vuex';
import { getMusicDetail } from '@/api/music';
import { audioService } from '@/services/audioService';
import { getImgUrl } from '@/utils';
interface DownloadItem {
filename: string;
progress: number;
loaded: number;
total: number;
path: string;
status: 'downloading' | 'completed' | 'error';
error?: string;
songInfo?: any;
}
interface DownloadedItem {
filename: string;
path: string;
size: number;
id: number;
picUrl: string;
ar: { name: string }[];
}
const store = useStore();
const message = useMessage();
const showDrawer = ref(false);
const downloadList = ref<DownloadItem[]>([]);
const downloadedList = ref<DownloadedItem[]>([]);
// 获取播放状态
const play = computed(() => store.state.play as boolean);
const currentMusic = computed(() => store.state.playMusic);
// 计算下载中的任务数量
const downloadingCount = computed(() => {
return downloadList.value.filter((item) => item.status === 'downloading').length;
});
// 计算总进度
const totalProgress = computed(() => {
if (downloadList.value.length === 0) return 0;
const total = downloadList.value.reduce((sum, item) => sum + item.progress, 0);
return total / downloadList.value.length;
});
watch(totalProgress, (newVal) => {
if (newVal === 100) {
refreshDownloadedList();
}
});
// 获取状态类型
const getStatusType = (item: DownloadItem) => {
switch (item.status) {
case 'downloading':
return 'info';
case 'completed':
return 'success';
case 'error':
return 'error';
default:
return 'default';
}
};
// 获取状态文本
const getStatusText = (item: DownloadItem) => {
switch (item.status) {
case 'downloading':
return '下载中';
case 'completed':
return '已完成';
case 'error':
return '失败';
default:
return '未知';
}
};
// 获取进度条状态
const getProgressStatus = (item: DownloadItem): ProgressStatus => {
switch (item.status) {
case 'completed':
return 'success';
case 'error':
return 'error';
default:
return 'info';
}
};
// 格式化文件大小
const formatSize = (bytes: number) => {
if (!bytes) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / k ** i).toFixed(1)} ${sizes[i]}`;
};
// 打开目录
const openDirectory = (path: string) => {
const directory = path.substring(0, path.lastIndexOf('/'));
window.electron.ipcRenderer.send('open-directory', directory);
};
// 删除相关
const showDeleteConfirm = ref(false);
const itemToDelete = ref<DownloadedItem | null>(null);
// 处理删除点击
const handleDelete = (item: DownloadedItem) => {
itemToDelete.value = item;
showDeleteConfirm.value = true;
};
// 确认删除
const confirmDelete = async () => {
if (!itemToDelete.value) return;
try {
const success = await window.electron.ipcRenderer.invoke(
'delete-downloaded-music',
itemToDelete.value.path
);
if (success) {
await refreshDownloadedList();
message.success('删除成功');
} else {
message.error('删除失败');
}
} catch (error) {
console.error('Failed to delete music:', error);
message.error('删除失败');
} finally {
showDeleteConfirm.value = false;
itemToDelete.value = null;
}
};
// 播放音乐
const handlePlayMusic = async (item: DownloadedItem) => {
// 确保路径正确编码
const encodedPath = encodeURIComponent(item.path);
const localUrl = `local://${encodedPath}`;
const musicInfo = {
name: item.filename,
id: item.id,
url: localUrl,
playMusicUrl: localUrl,
picUrl: item.picUrl,
ar: item.ar || [{ name: '本地音乐' }],
song: {
artists: item.ar || [{ name: '本地音乐' }]
},
al: {
picUrl: item.picUrl || '/images/default_cover.png'
}
};
// 如果是当前播放的音乐,则切换播放状态
if (currentMusic.value?.id === item.id) {
if (play.value) {
audioService.getCurrentSound()?.pause();
store.commit('setPlayMusic', false);
} else {
audioService.getCurrentSound()?.play();
store.commit('setPlayMusic', true);
}
return;
}
// 播放新的音乐
store.commit('setPlay', musicInfo);
store.commit('setPlayMusic', true);
store.commit('setIsPlay', true);
store.commit(
'setPlayList',
downloadedList.value.map((item) => ({
...item,
playMusicUrl: `local://${encodeURIComponent(item.path)}`
}))
);
};
// 获取已下载音乐列表
const refreshDownloadedList = async () => {
try {
const list = await window.electron.ipcRenderer.invoke('get-downloaded-music');
if (!Array.isArray(list) || list.length === 0) {
downloadedList.value = [];
return;
}
const songIds = list.filter((item) => item.id).map((item) => item.id);
// 如果有歌曲ID获取详细信息
if (songIds.length > 0) {
try {
const detailRes = await getMusicDetail(songIds);
const songDetails = detailRes.data.songs.reduce((acc, song) => {
acc[song.id] = song;
return acc;
}, {});
downloadedList.value = list.map((item) => {
const songDetail = songDetails[item.id];
return {
...item,
picUrl: songDetail?.al?.picUrl || item.picUrl || '/images/default_cover.png',
ar: songDetail?.ar || item.ar || [{ name: '本地音乐' }]
};
});
} catch (detailError) {
console.error('Failed to get music details:', detailError);
downloadedList.value = list;
}
} else {
downloadedList.value = list;
}
} catch (error) {
console.error('Failed to get downloaded music list:', error);
downloadedList.value = [];
}
};
// 监听抽屉显示状态
watch(
() => showDrawer.value,
(newVal) => {
if (newVal) {
refreshDownloadedList();
}
}
);
// 监听下载进度
onMounted(() => {
refreshDownloadedList();
// 监听下载进度
window.electron.ipcRenderer.on('music-download-progress', (_, data) => {
const existingItem = downloadList.value.find((item) => item.filename === data.filename);
if (existingItem) {
Object.assign(existingItem, {
...data,
songInfo: data.songInfo || existingItem.songInfo
});
// 如果下载完成,从列表中移除
if (data.status === 'completed') {
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
}
} else {
downloadList.value.push({
...data,
songInfo: data.songInfo
});
}
});
// 监听下载完成
window.electron.ipcRenderer.on('music-download-complete', (_, data) => {
if (data.success) {
// 从下载列表中移除
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
// 刷新已下载列表
refreshDownloadedList();
message.success(`${data.filename} 下载完成`);
} else {
const existingItem = downloadList.value.find((item) => item.filename === data.filename);
if (existingItem) {
Object.assign(existingItem, {
status: 'error',
error: data.error,
progress: 0
});
setTimeout(() => {
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
}, 3000);
}
message.error(`${data.filename} 下载失败: ${data.error}`);
}
});
// 监听下载队列
window.electron.ipcRenderer.on('music-download-queued', (_, data) => {
const existingItem = downloadList.value.find((item) => item.filename === data.filename);
if (!existingItem) {
downloadList.value.push({
filename: data.filename,
progress: 0,
loaded: 0,
total: 0,
path: '',
status: 'downloading',
songInfo: data.songInfo
});
}
});
});
</script>
<style lang="scss" scoped>
.download-drawer-trigger {
@apply fixed left-6 bottom-24 z-[999];
.n-button {
@apply bg-white/80 dark:bg-gray-800/80 shadow-lg backdrop-blur-sm;
@apply hover:bg-light dark:hover:bg-dark-200;
@apply text-gray-600 dark:text-gray-300;
@apply transition-all duration-300;
@apply w-10 h-10;
.iconfont {
@apply text-xl;
}
}
}
.drawer-container {
@apply h-full;
}
.download-list,
.downloaded-list {
@apply flex flex-col h-full;
.empty-tip {
@apply flex-1 flex items-center justify-center;
@apply text-gray-400 dark:text-gray-600;
}
}
.download-content,
.downloaded-content {
@apply flex-1 overflow-hidden pb-40;
}
.download-items,
.downloaded-items {
@apply space-y-3;
}
.total-progress {
@apply px-4 py-3 bg-light-100 dark:bg-dark-200 backdrop-blur-sm;
@apply border-b border-gray-100 dark:border-gray-800;
@apply sticky top-0 z-10;
&-text {
@apply mb-2 text-sm font-medium text-gray-600 dark:text-gray-400;
}
}
.download-item,
.downloaded-item {
@apply p-3 rounded-lg;
@apply bg-light-100 dark:bg-dark-200 backdrop-blur-sm;
@apply border border-gray-100 dark:border-gray-700;
@apply transition-all duration-300;
@apply hover:bg-light-300 dark:hover:bg-dark-300;
@apply hover:shadow-md;
&-content {
@apply flex items-center gap-3;
}
&-cover {
@apply w-10 h-10 flex-shrink-0 rounded-lg overflow-hidden;
@apply shadow-md;
.cover-image {
@apply w-full h-full object-cover;
}
}
&-info {
@apply flex-1 min-w-0;
}
&-name {
@apply text-sm font-medium truncate;
@apply text-gray-900 dark:text-gray-100;
}
&-artist {
@apply text-xs text-gray-500 dark:text-gray-400 truncate;
}
&-progress {
@apply mt-1;
}
&-size {
@apply text-xs text-gray-500 dark:text-gray-400 mt-1;
}
&-status {
@apply flex-shrink-0;
}
}
.downloaded-item {
&-actions {
@apply flex items-center gap-1;
.n-button {
@apply p-2;
@apply hover:bg-gray-200/80 dark:hover:bg-gray-600/80;
@apply rounded-lg;
@apply transition-colors duration-300;
.iconfont {
@apply text-xl;
}
}
}
}
.delete-confirm-content {
@apply py-6 px-4;
@apply text-base text-gray-600 dark:text-gray-400;
}
</style>

View File

@@ -158,43 +158,61 @@ const downloadMusic = async () => {
try {
isDownloading.value = true;
const loadingMessage = message.loading('正在下载中...', { duration: 0 });
const url = await getSongUrl(props.item.id, cloneDeep(props.item));
if (!url) {
loadingMessage.destroy();
message.error('获取音乐下载地址失败');
isDownloading.value = false;
return;
const data = (await getSongUrl(props.item.id, cloneDeep(props.item), true)) as any;
if (!data || !data.url) {
throw new Error('获取音乐下载地址失败');
}
// 先移除可能存在的旧监听器
window.electron.ipcRenderer.removeAllListeners('music-download-complete');
// 构建文件名
const artistNames = (props.item.ar || props.item.song?.artists)?.map((a) => a.name).join(',');
const filename = `${props.item.name} - ${artistNames}`;
// 发送下载请求
window.electron.ipcRenderer.send('download-music', {
url,
filename: `${props.item.name} - ${(props.item.ar || props.item.song?.artists)?.map((a) => a.name).join(',')}`
});
// 添加新的一次性监听器
window.electron.ipcRenderer.once('music-download-complete', (_, result) => {
isDownloading.value = false;
loadingMessage.destroy();
if (result.success) {
message.success('下载成功');
} else if (result.canceled) {
// 用户取消了保存
message.info('已取消下载');
} else {
message.error(`下载失败: ${result.error}`);
url: data.url,
type: data.type,
filename,
songInfo: {
...cloneDeep(props.item),
downloadTime: Date.now()
}
});
} catch (error) {
message.success('已加入下载队列');
// 监听下载完成事件
const handleDownloadComplete = (_, result) => {
if (result.filename === filename) {
isDownloading.value = false;
removeListeners();
}
};
// 监听下载错误事件
const handleDownloadError = (_, result) => {
if (result.filename === filename) {
isDownloading.value = false;
removeListeners();
}
};
// 移除监听器函数
const removeListeners = () => {
window.electron.ipcRenderer.removeListener('music-download-complete', handleDownloadComplete);
window.electron.ipcRenderer.removeListener('music-download-error', handleDownloadError);
};
// 添加事件监听器
window.electron.ipcRenderer.once('music-download-complete', handleDownloadComplete);
window.electron.ipcRenderer.once('music-download-error', handleDownloadError);
// 30秒后自动清理监听器以防下载过程中出现未知错误
setTimeout(removeListeners, 30000);
} catch (error: any) {
console.error('Download error:', error);
isDownloading.value = false;
message.destroyAll();
message.error('下载失败');
message.error(error.message || '下载失败');
}
};

View File

@@ -11,24 +11,34 @@ import { getImageLinearBackground } from '@/utils/linearColor';
const musicHistory = useMusicHistory();
// 获取歌曲url
export const getSongUrl = async (id: number, songData: any) => {
export const getSongUrl = async (id: number, songData: any, isDownloaded: boolean = false) => {
const { data } = await getMusicUrl(id);
console.log('data', data);
let url = '';
let songDetail = null;
try {
if (data.data[0].freeTrialInfo || !data.data[0].url) {
const res = await getParsingMusicUrl(id, songData);
console.log('res', res);
url = res.data.data.url;
songDetail = res.data.data;
} else {
songDetail = data.data[0] as any;
}
} catch (error) {
console.error('error', error);
}
if (isDownloaded) {
return songDetail;
}
url = url || data.data[0].url;
return url;
};
const getSongDetail = async (playMusic: SongResult) => {
playMusic.playLoading = true;
const playMusicUrl = await getSongUrl(playMusic.id, cloneDeep(playMusic));
const playMusicUrl =
playMusic.playMusicUrl || (await getSongUrl(playMusic.id, cloneDeep(playMusic)));
const { backgroundColor, primaryColor } =
playMusic.backgroundColor && playMusic.primaryColor
? playMusic
@@ -42,6 +52,7 @@ const getSongDetail = async (playMusic: SongResult) => {
export const useMusicListHook = () => {
const handlePlayMusic = async (state: any, playMusic: SongResult) => {
const updatedPlayMusic = await getSongDetail(playMusic);
console.log('updatedPlayMusic', updatedPlayMusic);
state.playMusic = updatedPlayMusic;
state.playMusicUrl = updatedPlayMusic.playMusicUrl;
state.play = true;

View File

@@ -26,6 +26,8 @@
</div>
<!-- 底部音乐播放 -->
<play-bar v-if="isPlay" :style="isMobile && store.state.musicFull ? 'bottom: 0;' : ''" />
<!-- 下载管理抽屉 -->
<download-drawer v-if="isElectron" />
</div>
<install-app-modal v-if="!isElectron"></install-app-modal>
<update-modal v-if="isElectron" />
@@ -37,6 +39,7 @@ import { computed, defineAsyncComponent, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
import DownloadDrawer from '@/components/common/DownloadDrawer.vue';
import InstallAppModal from '@/components/common/InstallAppModal.vue';
import PlayBottom from '@/components/common/PlayBottom.vue';
import UpdateModal from '@/components/common/UpdateModal.vue';

View File

@@ -5,7 +5,7 @@
<h2>我的收藏</h2>
<div class="favorite-count"> {{ favoriteList.length }} </div>
</div>
<div v-if="!isComponent" class="favorite-header-right">
<div v-if="!isComponent && isElectron" class="favorite-header-right">
<n-button
v-if="!isSelecting"
secondary
@@ -81,6 +81,7 @@
</template>
<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { useMessage } from 'naive-ui';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
@@ -90,7 +91,7 @@ import { getMusicDetail } from '@/api/music';
import SongItem from '@/components/common/SongItem.vue';
import { getSongUrl } from '@/hooks/MusicListHook';
import type { SongResult } from '@/type/music';
import { setAnimationClass, setAnimationDelay } from '@/utils';
import { isElectron, setAnimationClass, setAnimationDelay } from '@/utils';
const store = useStore();
const message = useMessage();
@@ -140,47 +141,64 @@ const handleBatchDownload = async () => {
try {
isDownloading.value = true;
const loadingMessage = message.loading('正在下载...', { duration: 0 });
let successCount = 0;
let failCount = 0;
message.success('开始下载...');
// 移除旧的监听器
window.electron.ipcRenderer.removeAllListeners('music-download-complete');
let successCount = 0;
let failCount = 0;
// 添加新的监听器
window.electron.ipcRenderer.on('music-download-complete', (_, result) => {
if (result.success) {
successCount++;
} else if (!result.canceled) {
} else {
failCount++;
}
// 当所有下载完成时
if (successCount + failCount === selectedSongs.value.length) {
isDownloading.value = false;
loadingMessage.destroy();
message.success(`下载完成:成功 ${successCount} 首,失败 ${failCount}`);
message.success(`下载完成`);
cancelSelect();
}
});
// 开始下载选中歌曲
for (const songId of selectedSongs.value) {
const song = favoriteSongs.value.find((s) => s.id === songId);
if (!song) continue;
// 获取选中歌曲的信息
const selectedSongsList = selectedSongs.value
.map((songId) => favoriteSongs.value.find((s) => s.id === songId))
.filter((song) => song) as SongResult[];
const url = await getSongUrl(song.id, song);
// 并行获取所有歌曲的下载链接
const downloadUrls = await Promise.all(
selectedSongsList.map(async (song) => {
try {
const data = (await getSongUrl(song.id, song, true)) as any;
return { song, ...data };
} catch (error) {
console.error(`获取歌曲 ${song.name} 下载链接失败:`, error);
return { song, url: null };
}
})
);
// 开始下载有效的链接
downloadUrls.forEach(({ song, url, type }) => {
if (!url) {
failCount++;
continue;
return;
}
window.electron.ipcRenderer.send('download-music', {
url,
filename: `${song.name} - ${(song.ar || song.song?.artists)?.map((a) => a.name).join(',')}`
filename: `${song.name} - ${(song.ar || song.song?.artists)?.map((a) => a.name).join(',')}`,
songInfo: cloneDeep(song),
type
});
}
});
} catch (error) {
console.error('下载失败:', error);
isDownloading.value = false;
message.destroyAll();
message.error('下载失败');

View File

@@ -14,7 +14,7 @@ defineOptions({
const message = useMessage();
const store = useStore();
const router = useRouter();
const isQr = ref(false);
const isQr = ref(true);
const qrUrl = ref<string>();
onMounted(() => {

View File

@@ -156,7 +156,22 @@
<div class="set-item-title">重启</div>
<div class="set-item-content">重启应用</div>
</div>
<n-button type="primary" @click="restartApp">重启</n-button>
<n-button type="primary" size="small" @click="restartApp">重启</n-button>
</div>
<!-- 缓存管理 -->
<!-- <n-card class="set-card" title="缓存管理">
<n-space vertical>
<n-button type="primary" @click="showClearCacheModal = true"> 清除缓存 </n-button>
</n-space>
</n-card> -->
<div v-if="isElectron" class="set-item">
<div>
<div class="set-item-title">缓存管理</div>
<div class="set-item-content">清除缓存</div>
</div>
<n-button type="primary" size="small" @click="showClearCacheModal = true">
清除缓存
</n-button>
</div>
<div v-if="isElectron" class="set-item">
<div>
@@ -196,12 +211,56 @@
<div
class="p-4 bg-light dark:bg-dark rounded-lg mb-4 border border-gray-200 dark:border-gray-700 rounded-lg"
>
<div>
<div class="set-item-title">捐赠支持</div>
<div class="set-item-content">感谢您的支持让我有动力能够持续改进</div>
<div class="flex justify-between items-center">
<div>
<div class="set-item-title">捐赠支持</div>
<div class="set-item-content">感谢您的支持让我有动力能够持续改进</div>
</div>
<n-button text @click="toggleDonationList">
<template #icon>
<i :class="isDonationListVisible ? 'ri-eye-line' : 'ri-eye-off-line'" />
</template>
{{ isDonationListVisible ? '隐藏列表' : '显示列表' }}
</n-button>
</div>
<donation-list />
<donation-list v-if="isDonationListVisible" />
</div>
<!-- 清除缓存弹窗 -->
<n-modal
v-model:show="showClearCacheModal"
preset="dialog"
title="清除缓存"
positive-text="确认"
negative-text="取消"
@positive-click="clearCache"
@negative-click="
() => {
selectedCacheTypes = [];
}
"
>
<n-space vertical>
<p>请选择要清除的缓存类型:</p>
<n-checkbox-group v-model:value="selectedCacheTypes">
<n-space vertical>
<n-checkbox
v-for="option in clearCacheOptions"
:key="option.key"
:value="option.key"
:label="option.label"
>
<template #default>
<div>
<div>{{ option.label }}</div>
<div class="text-gray-400 text-sm">{{ option.description }}</div>
</div>
</template>
</n-checkbox>
</n-space>
</n-checkbox-group>
</n-space>
</n-modal>
</div>
<play-bottom />
<n-modal
@@ -254,6 +313,7 @@ import { useMessage } from 'naive-ui';
import { computed, onMounted, ref, watch } from 'vue';
import { useStore } from 'vuex';
import localData from '@/../main/set.json';
import Coffee from '@/components/Coffee.vue';
import DonationList from '@/components/common/DonationList.vue';
import PlayBottom from '@/components/common/PlayBottom.vue';
@@ -476,6 +536,89 @@ watch(
}
}
);
const isDonationListVisible = ref(localStorage.getItem('donationListVisible') !== 'false');
const toggleDonationList = () => {
isDonationListVisible.value = !isDonationListVisible.value;
localStorage.setItem('donationListVisible', isDonationListVisible.value.toString());
};
// 清除缓存相关
const showClearCacheModal = ref(false);
const clearCacheOptions = ref([
{ label: '播放历史', key: 'history', description: '清除播放过的歌曲记录' },
{ label: '收藏记录', key: 'favorite', description: '清除本地收藏的歌曲记录(不会影响云端收藏)' },
{ label: '用户数据', key: 'user', description: '清除登录信息和用户相关数据' },
{ label: '应用设置', key: 'settings', description: '清除应用的所有自定义设置' },
{ label: '下载记录', key: 'downloads', description: '清除下载历史记录(不会删除已下载的文件)' },
{ label: '音乐资源', key: 'resources', description: '清除已加载的音乐文件、歌词等资源缓存' }
]);
const selectedCacheTypes = ref<string[]>([]);
const clearCache = async () => {
const clearTasks = selectedCacheTypes.value.map(async (type) => {
switch (type) {
case 'history':
localStorage.removeItem('musicHistory');
break;
case 'favorite':
localStorage.removeItem('favoriteList');
break;
case 'user':
localStorage.removeItem('user');
localStorage.removeItem('token');
store.commit('logout');
break;
case 'settings':
if (window.electron) {
window.electron.ipcRenderer.send('set-store-value', 'set', localData);
}
localStorage.removeItem('appSettings');
localStorage.removeItem('theme');
localStorage.removeItem('lyricData');
localStorage.removeItem('lyricFontSize');
localStorage.removeItem('playMode');
break;
case 'downloads':
if (window.electron) {
window.electron.ipcRenderer.send('clear-downloads-history');
}
break;
case 'resources':
// 清除音频资源缓存
if (window.electron) {
window.electron.ipcRenderer.send('clear-audio-cache');
}
// 清除歌词缓存
localStorage.removeItem('lyricCache');
// 清除音乐URL缓存
localStorage.removeItem('musicUrlCache');
// 清除图片缓存
if (window.caches) {
try {
const cache = await window.caches.open('music-images');
await cache.keys().then((keys) => {
keys.forEach((key) => {
cache.delete(key);
});
});
} catch (error) {
console.error('清除图片缓存失败:', error);
}
}
break;
default:
break;
}
});
await Promise.all(clearTasks);
message.success('清除成功,部分设置在重启后生效');
showClearCacheModal.value = false;
selectedCacheTypes.value = [];
};
</script>
<style lang="scss" scoped>

View File

@@ -123,8 +123,29 @@ onBeforeUnmount(() => {
mounted.value = false;
});
// 检查登录状态
const checkLoginStatus = () => {
const token = localStorage.getItem('token');
const userData = localStorage.getItem('user');
if (!token || !userData) {
router.push('/login');
return false;
}
// 如果store中没有用户数据但localStorage中有则恢复用户数据
if (!store.state.user && userData) {
store.state.user = JSON.parse(userData);
}
return true;
};
const loadPage = async () => {
if (!mounted.value || !user.value) return;
if (!mounted.value) return;
// 检查登录状态
if (!checkLoginStatus()) return;
try {
infoLoading.value = true;
@@ -144,8 +165,13 @@ const loadPage = async () => {
...item.song,
picUrl: item.song.al.picUrl
}));
} catch (error) {
} catch (error: any) {
console.error('加载用户页面失败:', error);
// 如果获取用户数据失败可能是token过期
if (error.response?.status === 401) {
store.commit('logout');
router.push('/login');
}
} finally {
if (mounted.value) {
infoLoading.value = false;
@@ -153,6 +179,16 @@ const loadPage = async () => {
}
};
// 监听路由变化
watch(
() => router.currentRoute.value.path,
(newPath) => {
if (newPath === '/user') {
checkLoginStatus();
}
}
);
// 监听用户状态变化
watch(
() => store.state.user,
@@ -168,6 +204,12 @@ watch(
{ immediate: true }
);
// 页面挂载时检查登录状态
onMounted(() => {
checkLoginStatus();
loadPage();
});
// 展示歌单
const showPlaylist = async (id: number, name: string) => {
isShowList.value = true;