mirror of
https://github.com/algerkong/AlgerMusicPlayer.git
synced 2026-04-03 14:20:50 +08:00
Compare commits
47 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
599b0251af | ||
|
|
25c2180247 | ||
|
|
a6ff0e7f5c | ||
|
|
2e06711600 | ||
|
|
80770d6c75 | ||
|
|
1e068df2ad | ||
|
|
4172ff9fc6 | ||
|
|
83a7df9fe8 | ||
|
|
ba95dc11fe | ||
|
|
93829acdab | ||
|
|
1f0f35dd51 | ||
|
|
be94d6ff8e | ||
|
|
1bdb8fcb4a | ||
|
|
914e043502 | ||
|
|
dfa175b8b2 | ||
|
|
a94e0efba5 | ||
|
|
fb0831f2eb | ||
|
|
573023600a | ||
|
|
041aad31b4 | ||
|
|
f652932d71 | ||
|
|
7efeb9492b | ||
|
|
055536eb5c | ||
|
|
14852fc8d3 | ||
|
|
9866e772df | ||
|
|
87ca0836b1 | ||
|
|
fa07c5a40c | ||
|
|
5dbfea240b | ||
|
|
c1344393c3 | ||
|
|
426888f77c | ||
|
|
45cbc15c0f | ||
|
|
072025a543 | ||
|
|
c6427aa3e1 | ||
|
|
632cdb1239 | ||
|
|
8ffe472605 | ||
|
|
8e86d378d0 | ||
|
|
744fd53fb1 | ||
|
|
3c64473dbb | ||
|
|
e70fed37da | ||
|
|
b749854c5e | ||
|
|
d9210cc50a | ||
|
|
f186d34885 | ||
|
|
ba992b7c33 | ||
|
|
24d7c839c7 | ||
|
|
a4f3df80c9 | ||
|
|
866fec6ee3 | ||
|
|
8f7d6fbb8d | ||
|
|
62e26cae7d |
4
.eslintignore
Normal file
4
.eslintignore
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
out
|
||||
.gitignore
|
||||
137
.eslintrc.cjs
Normal file
137
.eslintrc.cjs
Normal file
@@ -0,0 +1,137 @@
|
||||
/* eslint-env node */
|
||||
require('@rushstack/eslint-patch/modern-module-resolution');
|
||||
|
||||
module.exports = {
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'eslint-config-airbnb-base',
|
||||
'@vue/typescript/recommended',
|
||||
'plugin:vue/vue3-recommended',
|
||||
'plugin:vue-scoped-css/base',
|
||||
'@electron-toolkit',
|
||||
'@electron-toolkit/eslint-config-ts/eslint-recommended',
|
||||
'plugin:prettier/recommended'
|
||||
],
|
||||
env: {
|
||||
browser: true,
|
||||
node: true,
|
||||
jest: true,
|
||||
es6: true
|
||||
},
|
||||
globals: {
|
||||
defineProps: 'readonly',
|
||||
defineEmits: 'readonly'
|
||||
},
|
||||
plugins: ['vue', '@typescript-eslint', 'simple-import-sort'],
|
||||
parserOptions: {
|
||||
parser: '@typescript-eslint/parser',
|
||||
sourceType: 'module',
|
||||
allowImportExportEverywhere: true,
|
||||
ecmaFeatures: {
|
||||
jsx: true
|
||||
}
|
||||
},
|
||||
settings: {
|
||||
'import/extensions': ['.js', '.jsx', '.ts', '.tsx']
|
||||
},
|
||||
rules: {
|
||||
'vue/require-default-prop': 'off',
|
||||
'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',
|
||||
'no-unused-expressions': 'off',
|
||||
'no-return-await': 'off',
|
||||
'no-plusplus': 'off',
|
||||
'no-param-reassign': 'off',
|
||||
'no-shadow': 'off',
|
||||
'guard-for-in': 'off',
|
||||
'import/extensions': 'off',
|
||||
'import/no-unresolved': 'off',
|
||||
'import/no-extraneous-dependencies': 'off',
|
||||
'import/prefer-default-export': 'off',
|
||||
'import/first': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'vue/first-attribute-linebreak': 0,
|
||||
'@typescript-eslint/no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_'
|
||||
}
|
||||
],
|
||||
'no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_'
|
||||
}
|
||||
],
|
||||
'no-use-before-define': 'off',
|
||||
'@typescript-eslint/no-use-before-define': 'off',
|
||||
'@typescript-eslint/ban-ts-comment': 'off',
|
||||
'@typescript-eslint/ban-types': 'off',
|
||||
'class-methods-use-this': 'off',
|
||||
'simple-import-sort/imports': 'error',
|
||||
'simple-import-sort/exports': 'error'
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
files: ['*.vue'],
|
||||
rules: {
|
||||
'vue/component-name-in-template-casing': [2, 'kebab-case'],
|
||||
'vue/require-default-prop': 0,
|
||||
'vue/multi-word-component-names': 0,
|
||||
'vue/no-reserved-props': 0,
|
||||
'vue/no-v-html': 0,
|
||||
'vue-scoped-css/enforce-style-type': [
|
||||
'error',
|
||||
{
|
||||
allows: ['scoped']
|
||||
}
|
||||
],
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
// 需要行尾分号
|
||||
'prettier/prettier': ['error', { endOfLine: 'auto' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
files: ['*.ts', '*.tsx'],
|
||||
rules: {
|
||||
'max-classes-per-file': 'off',
|
||||
'no-await-in-loop': 'off',
|
||||
'dot-notation': 'off',
|
||||
'constructor-super': 'off',
|
||||
'getter-return': 'off',
|
||||
'no-const-assign': 'off',
|
||||
'no-dupe-args': 'off',
|
||||
'no-dupe-class-members': 'off',
|
||||
'no-dupe-keys': 'off',
|
||||
'no-func-assign': 'off',
|
||||
'no-import-assign': 'off',
|
||||
'no-new-symbol': 'off',
|
||||
'no-obj-calls': 'off',
|
||||
'no-redeclare': 'off',
|
||||
'no-setter-return': 'off',
|
||||
'no-this-before-super': 'off',
|
||||
'no-undef': 'off',
|
||||
'no-unreachable': 'off',
|
||||
'no-unsafe-negation': 'off',
|
||||
'no-var': 'error',
|
||||
'prefer-const': 'error',
|
||||
'prefer-rest-params': 'error',
|
||||
'prefer-spread': 'error',
|
||||
'valid-typeof': 'off',
|
||||
'consistent-return': 'off',
|
||||
'no-promise-executor-return': 'off',
|
||||
'prefer-promise-reject-errors': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off'
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -19,4 +19,6 @@ bun.lockb
|
||||
|
||||
.env.*.local
|
||||
|
||||
out
|
||||
out
|
||||
|
||||
.cursorrules
|
||||
6
.prettierignore
Normal file
6
.prettierignore
Normal file
@@ -0,0 +1,6 @@
|
||||
out
|
||||
dist
|
||||
pnpm-lock.yaml
|
||||
LICENSE.md
|
||||
tsconfig.json
|
||||
tsconfig.*.json
|
||||
5
.prettierrc.yaml
Normal file
5
.prettierrc.yaml
Normal file
@@ -0,0 +1,5 @@
|
||||
singleQuote: true
|
||||
semi: true
|
||||
printWidth: 100
|
||||
trailingComma: none
|
||||
endOfLine: auto
|
||||
26
CHANGELOG.md
26
CHANGELOG.md
@@ -1,11 +1,21 @@
|
||||
# 更新日志
|
||||
|
||||
## [v3.3.0] - 2024-01-04
|
||||
|
||||
## v3.9.0
|
||||
### ✨ 新功能
|
||||
- 添加音质选择功能,优化灰色歌曲解析 (020aca7)
|
||||
- 收藏功能改为接口对接 与 网易云同步 (43c64b1)
|
||||
- 添加退出登录 (fcc47dc)
|
||||
- 优化登录失效处理 (9eb17fd)
|
||||
- 修复未登录状态下的收藏问题 (17ce268)
|
||||
- 优化更新检查和下载功能 (11ced6b)
|
||||
- 添加歌曲右键菜单功能,支持添加到歌单、创建歌单、取消收藏等操作
|
||||
- 添加下一首播放功能(右键歌曲)
|
||||
- 添加自动播放和自动保存正在播放列表功能(设置->播放设置->自动播放)
|
||||
- 优化歌词滚动体验
|
||||
|
||||
### ⚡ 优化
|
||||
- 升级 Electron 版本和相关依赖包
|
||||
- 优化播放体验和代码结构
|
||||
|
||||
### 🐞 修复
|
||||
- 修复我的收藏查看更多跳转空白页的问题
|
||||
|
||||
|
||||
## 咖啡☕️
|
||||
| 微信 | | 支付宝 |
|
||||
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: |
|
||||
| <img src="https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/src/renderer/assets/wechat.png" alt="WeChat QRcode" width=200>| | <img src="https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/src/renderer/assets/alipay.png" alt="Wechat QRcode" width=200> |
|
||||
76
README.md
76
README.md
@@ -1,15 +1,24 @@
|
||||
# Alger Music Player
|
||||
主要功能如下
|
||||
|
||||
- 音乐推荐
|
||||
- 网易云登录
|
||||
- 播放历史
|
||||
- 桌面歌词
|
||||
- 歌单 mv 搜索 专辑等功能
|
||||
- 识别无法播放歌曲 并解析播放
|
||||
- 主题切换 更新检测
|
||||
- 本地服务 不依赖线上服务
|
||||
- 可听周杰伦(搜索专辑)
|
||||
- 🎵 音乐推荐
|
||||
- 🔐 网易云账号登录与同步
|
||||
- 📝 功能
|
||||
- 播放历史记录
|
||||
- 歌曲收藏管理
|
||||
- 自定义快捷键配置
|
||||
- 🎨 界面与交互
|
||||
- 沉浸式歌词显示(点击左下角封面进入)
|
||||
- 独立桌面歌词窗口
|
||||
- 明暗主题切换
|
||||
- 🎼 音乐功能
|
||||
- 支持歌单、MV、专辑等完整音乐服务
|
||||
- 灰色音乐资源解析(基于 @unblockneteasemusic/server)
|
||||
- 高品质音乐试听(需网易云VIP)
|
||||
- 音乐文件下载(支持右键下载和批量下载)
|
||||
- 🚀 技术特性
|
||||
- 本地化服务,无需依赖在线API (基于 netease-cloud-music-api)
|
||||
- 自动更新检测
|
||||
- 全平台适配(Desktop & Web & Mobile Web)
|
||||
|
||||
## 项目简介
|
||||
一个基于 electron typescript vue3 的桌面音乐播放器 适配 web端 桌面端 web移动端
|
||||
@@ -24,6 +33,7 @@ QQ群:789288579
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## 技术栈
|
||||
|
||||
@@ -36,53 +46,13 @@ QQ群:789288579
|
||||
|
||||
|
||||
## 咖啡☕️
|
||||
|
||||
[<img src="https://api.gitsponsors.com/api/badge/img?id=710867462" height="90">](https://api.gitsponsors.com/api/badge/link?p=GTUHmTNQ9W5XzPhaLd8cPBm26uhtP/QOon9hexaWh9gnfaDT3ivj1ID0uKScVHL61jTFrK1fRWyigScIYvcLh/no+3zgtdW3TK0+vN0TVs84Mt3RibhEqAgBHSd8KhNLxaMd4vMIY37P5gOA2/QYcw==)
|
||||
|
||||
| 微信 | 支付宝 |
|
||||
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: |
|
||||
| <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
|
||||
[](https://starchart.cc/algerkong/AlgerMusicPlayer)
|
||||
|
||||
BIN
docs/image4.png
Normal file
BIN
docs/image4.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
49
package.json
49
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "AlgerMusicPlayer",
|
||||
"version": "3.3.0",
|
||||
"version": "3.9.0",
|
||||
"description": "Alger Music Player",
|
||||
"author": "Alger <algerkc@qq.com>",
|
||||
"main": "./out/main/index.js",
|
||||
@@ -26,10 +26,10 @@
|
||||
"@unblockneteasemusic/server": "^0.27.8-patch.1",
|
||||
"electron-store": "^8.1.0",
|
||||
"electron-updater": "^6.1.7",
|
||||
"font-list": "^1.5.1",
|
||||
"netease-cloud-music-api-alger": "^4.25.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"marked": "^15.0.4",
|
||||
"devDependencies": {
|
||||
"@electron-toolkit/eslint-config": "^1.0.2",
|
||||
"@electron-toolkit/eslint-config-ts": "^2.0.0",
|
||||
"@electron-toolkit/tsconfig": "^1.0.1",
|
||||
@@ -37,6 +37,7 @@
|
||||
"@tailwindcss/postcss7-compat": "^2.2.4",
|
||||
"@types/howler": "^2.2.12",
|
||||
"@types/node": "^20.14.8",
|
||||
"@types/tinycolor2": "^1.4.6",
|
||||
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
||||
"@typescript-eslint/parser": "^7.0.0",
|
||||
"@vitejs/plugin-vue": "^5.0.5",
|
||||
@@ -46,11 +47,12 @@
|
||||
"@vue/runtime-core": "^3.5.0",
|
||||
"@vueuse/core": "^11.0.3",
|
||||
"@vueuse/electron": "^11.0.3",
|
||||
"animate.css": "^4.1.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"axios": "^1.7.7",
|
||||
"cross-env": "^7.0.3",
|
||||
"electron": "^31.0.2",
|
||||
"electron-builder": "^24.13.3",
|
||||
"electron": "^34.0.0",
|
||||
"electron-builder": "^25.1.8",
|
||||
"electron-vite": "^2.3.0",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
@@ -62,12 +64,14 @@
|
||||
"eslint-plugin-vue-scoped-css": "^2.7.2",
|
||||
"howler": "^2.2.4",
|
||||
"lodash": "^4.17.21",
|
||||
"naive-ui": "^2.39.0",
|
||||
"marked": "^15.0.4",
|
||||
"naive-ui": "^2.41.0",
|
||||
"postcss": "^8.4.49",
|
||||
"prettier": "^3.3.2",
|
||||
"remixicon": "^4.2.0",
|
||||
"sass": "^1.82.0",
|
||||
"tailwindcss": "^3.4.15",
|
||||
"sass": "^1.83.4",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"tinycolor2": "^1.6.0",
|
||||
"typescript": "^5.5.2",
|
||||
"unplugin-auto-import": "^0.18.2",
|
||||
"unplugin-vue-components": "^0.27.4",
|
||||
@@ -75,19 +79,21 @@
|
||||
"vite": "^5.3.1",
|
||||
"vite-plugin-compression": "^0.5.1",
|
||||
"vite-plugin-vue-devtools": "7.4.0",
|
||||
"vue": "^3.4.30",
|
||||
"vue-router": "^4.4.3",
|
||||
"vue": "^3.5.13",
|
||||
"vue-router": "^4.5.0",
|
||||
"vue-tsc": "^2.0.22",
|
||||
"vuex": "^4.1.0"
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.alger.music",
|
||||
"productName": "AlgerMusicPlayer",
|
||||
"publish": [{
|
||||
"provider": "github",
|
||||
"owner": "algerkong",
|
||||
"repo": "AlgerMusicPlayer"
|
||||
}],
|
||||
"publish": [
|
||||
{
|
||||
"provider": "github",
|
||||
"owner": "algerkong",
|
||||
"repo": "AlgerMusicPlayer"
|
||||
}
|
||||
],
|
||||
"mac": {
|
||||
"icon": "resources/icon.icns",
|
||||
"target": [
|
||||
@@ -116,7 +122,10 @@
|
||||
"target": [
|
||||
{
|
||||
"target": "nsis",
|
||||
"arch": ["x64", "ia32"]
|
||||
"arch": [
|
||||
"x64",
|
||||
"ia32"
|
||||
]
|
||||
}
|
||||
],
|
||||
"artifactName": "${productName}-${version}-win-${arch}.${ext}",
|
||||
@@ -127,11 +136,15 @@
|
||||
"target": [
|
||||
{
|
||||
"target": "AppImage",
|
||||
"arch": ["x64"]
|
||||
"arch": [
|
||||
"x64"
|
||||
]
|
||||
},
|
||||
{
|
||||
"target": "deb",
|
||||
"arch": ["x64"]
|
||||
"arch": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
],
|
||||
"artifactName": "${productName}-${version}-linux-${arch}.${ext}",
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { electronApp, optimizer } from '@electron-toolkit/utils';
|
||||
import { app, globalShortcut, ipcMain, nativeImage } from 'electron';
|
||||
import { app, ipcMain, nativeImage } from 'electron';
|
||||
import { join } from 'path';
|
||||
|
||||
import { loadLyricWindow } from './lyric';
|
||||
import { startMusicApi } from './server';
|
||||
import { initializeFileManager } from './modules/fileManager';
|
||||
import { initializeTray } from './modules/tray';
|
||||
import { createMainWindow, initializeWindowManager } from './modules/window';
|
||||
import { initializeConfig } from './modules/config';
|
||||
import { initializeFileManager } from './modules/fileManager';
|
||||
import { initializeFonts } from './modules/fonts';
|
||||
import { initializeShortcuts, registerShortcuts } from './modules/shortcuts';
|
||||
import { initializeTray } from './modules/tray';
|
||||
import { setupUpdateHandlers } from './modules/update';
|
||||
import { createMainWindow, initializeWindowManager } from './modules/window';
|
||||
import { startMusicApi } from './server';
|
||||
|
||||
// 导入所有图标
|
||||
const iconPath = join(__dirname, '../../resources');
|
||||
@@ -15,78 +18,98 @@ const icon = nativeImage.createFromPath(
|
||||
process.platform === 'darwin'
|
||||
? join(iconPath, 'icon.icns')
|
||||
: process.platform === 'win32'
|
||||
? join(iconPath, 'favicon.ico')
|
||||
: join(iconPath, 'icon.png')
|
||||
? join(iconPath, 'favicon.ico')
|
||||
: join(iconPath, 'icon.png')
|
||||
);
|
||||
|
||||
let mainWindow: Electron.BrowserWindow;
|
||||
|
||||
// 初始化应用
|
||||
function initialize() {
|
||||
// 初始化各个模块
|
||||
// 初始化配置管理
|
||||
initializeConfig();
|
||||
// 初始化文件管理
|
||||
initializeFileManager();
|
||||
|
||||
// 创建主窗口
|
||||
mainWindow = createMainWindow(icon);
|
||||
|
||||
// 初始化窗口管理
|
||||
initializeWindowManager();
|
||||
|
||||
// 初始化字体管理
|
||||
initializeFonts();
|
||||
|
||||
// 创建主窗口
|
||||
mainWindow = createMainWindow(icon);
|
||||
|
||||
// 初始化托盘
|
||||
initializeTray(iconPath, mainWindow);
|
||||
|
||||
|
||||
// 启动音乐API
|
||||
startMusicApi();
|
||||
|
||||
|
||||
// 加载歌词窗口
|
||||
loadLyricWindow(ipcMain, mainWindow);
|
||||
|
||||
// 初始化快捷键
|
||||
initializeShortcuts(mainWindow);
|
||||
|
||||
// 初始化更新处理程序
|
||||
setupUpdateHandlers(mainWindow);
|
||||
}
|
||||
|
||||
// 应用程序准备就绪时的处理
|
||||
app.whenReady().then(() => {
|
||||
// 设置应用ID
|
||||
electronApp.setAppUserModelId('com.alger.music');
|
||||
// 检查是否为第一个实例
|
||||
const isSingleInstance = app.requestSingleInstanceLock();
|
||||
|
||||
// 监听窗口创建事件
|
||||
app.on('browser-window-created', (_, window) => {
|
||||
optimizer.watchWindowShortcuts(window);
|
||||
});
|
||||
|
||||
// 初始化应用
|
||||
initialize();
|
||||
|
||||
// macOS 激活应用时的处理
|
||||
app.on('activate', function () {
|
||||
if (mainWindow === null) initialize();
|
||||
});
|
||||
});
|
||||
|
||||
// 应用程序准备就绪后的快捷键设置
|
||||
app.on('ready', () => {
|
||||
globalShortcut.register('CommandOrControl+Alt+Shift+M', () => {
|
||||
if (mainWindow.isVisible()) {
|
||||
mainWindow.hide();
|
||||
} else {
|
||||
if (!isSingleInstance) {
|
||||
app.quit();
|
||||
} else {
|
||||
// 当第二个实例启动时,将焦点转移到第一个实例的窗口
|
||||
app.on('second-instance', () => {
|
||||
if (mainWindow) {
|
||||
if (mainWindow.isMinimized()) {
|
||||
mainWindow.restore();
|
||||
}
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 所有窗口关闭时的处理
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
// 应用程序准备就绪时的处理
|
||||
app.whenReady().then(() => {
|
||||
// 设置应用ID
|
||||
electronApp.setAppUserModelId('com.alger.music');
|
||||
|
||||
// 重启应用
|
||||
ipcMain.on('restart', () => {
|
||||
app.relaunch();
|
||||
app.exit(0);
|
||||
});
|
||||
// 监听窗口创建事件
|
||||
app.on('browser-window-created', (_, window) => {
|
||||
optimizer.watchWindowShortcuts(window);
|
||||
});
|
||||
|
||||
// 获取系统架构信息
|
||||
ipcMain.on('get-arch', (event) => {
|
||||
event.returnValue = process.arch;
|
||||
});
|
||||
// 初始化应用
|
||||
initialize();
|
||||
|
||||
// macOS 激活应用时的处理
|
||||
app.on('activate', () => {
|
||||
if (mainWindow === null) initialize();
|
||||
});
|
||||
});
|
||||
|
||||
// 监听快捷键更新
|
||||
ipcMain.on('update-shortcuts', () => {
|
||||
registerShortcuts(mainWindow);
|
||||
});
|
||||
|
||||
// 所有窗口关闭时的处理
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// 重启应用
|
||||
ipcMain.on('restart', () => {
|
||||
app.relaunch();
|
||||
app.exit(0);
|
||||
});
|
||||
|
||||
// 获取系统架构信息
|
||||
ipcMain.on('get-arch', (event) => {
|
||||
event.returnValue = process.arch;
|
||||
});
|
||||
}
|
||||
|
||||
89
src/main/modules/cache.ts
Normal file
89
src/main/modules/cache.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
|
||||
interface LyricData {
|
||||
id: number;
|
||||
data: any;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface StoreSchema {
|
||||
lyrics: Record<number, LyricData>;
|
||||
}
|
||||
|
||||
class CacheManager {
|
||||
private store: Store<StoreSchema>;
|
||||
|
||||
constructor() {
|
||||
this.store = new Store<StoreSchema>({
|
||||
name: 'lyrics',
|
||||
defaults: {
|
||||
lyrics: {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async cacheLyric(id: number, data: any) {
|
||||
try {
|
||||
const lyrics = this.store.get('lyrics');
|
||||
lyrics[id] = {
|
||||
id,
|
||||
data,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
this.store.set('lyrics', lyrics);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error caching lyric:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async getCachedLyric(id: number) {
|
||||
try {
|
||||
const lyrics = this.store.get('lyrics');
|
||||
const result = lyrics[id];
|
||||
|
||||
if (!result) return undefined;
|
||||
|
||||
// 检查缓存是否过期(24小时)
|
||||
if (Date.now() - result.timestamp > 24 * 60 * 60 * 1000) {
|
||||
delete lyrics[id];
|
||||
this.store.set('lyrics', lyrics);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return result.data;
|
||||
} catch (error) {
|
||||
console.error('Error getting cached lyric:', error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async clearLyricCache() {
|
||||
try {
|
||||
this.store.set('lyrics', {});
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error clearing lyric cache:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const cacheManager = new CacheManager();
|
||||
|
||||
export function initializeCacheManager() {
|
||||
// 添加歌词缓存相关的 IPC 处理
|
||||
ipcMain.handle('cache-lyric', async (_, id: number, lyricData: any) => {
|
||||
return await cacheManager.cacheLyric(id, lyricData);
|
||||
});
|
||||
|
||||
ipcMain.handle('get-cached-lyric', async (_, id: number) => {
|
||||
return await cacheManager.getCachedLyric(id);
|
||||
});
|
||||
|
||||
ipcMain.handle('clear-lyric-cache', async () => {
|
||||
return await cacheManager.clearLyricCache();
|
||||
});
|
||||
}
|
||||
@@ -1,16 +1,32 @@
|
||||
import { app, ipcMain } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
import set from '../set.json';
|
||||
|
||||
interface StoreType {
|
||||
set: {
|
||||
isProxy: boolean;
|
||||
noAnimate: boolean;
|
||||
animationSpeed: number;
|
||||
author: string;
|
||||
authorUrl: string;
|
||||
musicApiPort: number;
|
||||
import set from '../set.json';
|
||||
import { defaultShortcuts } from './shortcuts';
|
||||
|
||||
type SetConfig = {
|
||||
isProxy: boolean;
|
||||
proxyConfig: {
|
||||
enable: boolean;
|
||||
protocol: string;
|
||||
host: string;
|
||||
port: number;
|
||||
};
|
||||
enableRealIP: boolean;
|
||||
realIP: string;
|
||||
noAnimate: boolean;
|
||||
animationSpeed: number;
|
||||
author: string;
|
||||
authorUrl: string;
|
||||
musicApiPort: number;
|
||||
closeAction: 'ask' | 'minimize' | 'close';
|
||||
musicQuality: string;
|
||||
fontFamily: string;
|
||||
fontScope: 'global' | 'lyric';
|
||||
};
|
||||
interface StoreType {
|
||||
set: SetConfig;
|
||||
shortcuts: typeof defaultShortcuts;
|
||||
}
|
||||
|
||||
let store: Store<StoreType>;
|
||||
@@ -22,7 +38,8 @@ export function initializeConfig() {
|
||||
store = new Store<StoreType>({
|
||||
name: 'config',
|
||||
defaults: {
|
||||
set: set
|
||||
set: set as SetConfig,
|
||||
shortcuts: defaultShortcuts
|
||||
}
|
||||
});
|
||||
|
||||
@@ -39,4 +56,8 @@ export function initializeConfig() {
|
||||
});
|
||||
|
||||
return store;
|
||||
}
|
||||
}
|
||||
|
||||
export function getStore() {
|
||||
return store;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,53 @@
|
||||
import { app, dialog, shell, ipcMain } from 'electron';
|
||||
import axios from 'axios';
|
||||
import { app, dialog, ipcMain, protocol, shell } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import axios from 'axios';
|
||||
|
||||
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,27 +58,221 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载音乐功能
|
||||
*/
|
||||
async function downloadMusic(event: Electron.IpcMainEvent, { url, filename }: { url: string; filename: string }) {
|
||||
async function downloadMusic(
|
||||
event: Electron.IpcMainEvent,
|
||||
{
|
||||
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`);
|
||||
const downloadPath = (store.get('set.downloadPath') as string) || app.getPath('downloads');
|
||||
|
||||
// 从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);
|
||||
@@ -47,23 +281,115 @@ async function downloadMusic(event: Electron.IpcMainEvent, { url, filename }: {
|
||||
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(undefined));
|
||||
writer!.on('error', (error) => reject(error));
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
42
src/main/modules/fonts.ts
Normal file
42
src/main/modules/fonts.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import { getFonts } from 'font-list';
|
||||
|
||||
/**
|
||||
* 清理字体名称
|
||||
* @param fontName 原始字体名称
|
||||
* @returns 清理后的字体名称
|
||||
*/
|
||||
function cleanFontName(fontName: string): string {
|
||||
return fontName
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '') // 移除首尾的引号
|
||||
.replace(/\s+/g, ' '); // 将多个空格替换为单个空格
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取系统字体列表
|
||||
*/
|
||||
async function getSystemFonts(): Promise<string[]> {
|
||||
try {
|
||||
// 使用 font-list 获取系统字体
|
||||
const fonts = await getFonts();
|
||||
// 清理字体名称并去重
|
||||
const cleanedFonts = [...new Set(fonts.map(cleanFontName))];
|
||||
// 添加系统默认字体并排序
|
||||
return ['system-ui', ...cleanedFonts].sort();
|
||||
} catch (error) {
|
||||
console.error('获取系统字体失败:', error);
|
||||
// 如果获取失败,至少返回系统默认字体
|
||||
return ['system-ui'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化字体管理模块
|
||||
*/
|
||||
export function initializeFonts() {
|
||||
// 添加获取系统字体的 IPC 处理
|
||||
ipcMain.handle('get-system-fonts', async () => {
|
||||
return await getSystemFonts();
|
||||
});
|
||||
}
|
||||
88
src/main/modules/shortcuts.ts
Normal file
88
src/main/modules/shortcuts.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import { globalShortcut, ipcMain } from 'electron';
|
||||
|
||||
import { getStore } from './config';
|
||||
|
||||
// 添加获取平台信息的 IPC 处理程序
|
||||
ipcMain.on('get-platform', (event) => {
|
||||
event.returnValue = process.platform;
|
||||
});
|
||||
|
||||
// 定义默认快捷键
|
||||
export const defaultShortcuts = {
|
||||
togglePlay: 'CommandOrControl+Alt+P',
|
||||
prevPlay: 'CommandOrControl+Alt+Left',
|
||||
nextPlay: 'CommandOrControl+Alt+Right',
|
||||
volumeUp: 'CommandOrControl+Alt+Up',
|
||||
volumeDown: 'CommandOrControl+Alt+Down',
|
||||
toggleFavorite: 'CommandOrControl+Alt+L',
|
||||
toggleWindow: 'CommandOrControl+Alt+Shift+M'
|
||||
};
|
||||
|
||||
let mainWindowRef: Electron.BrowserWindow | null = null;
|
||||
|
||||
// 注册快捷键
|
||||
export function registerShortcuts(mainWindow: Electron.BrowserWindow) {
|
||||
mainWindowRef = mainWindow;
|
||||
const store = getStore();
|
||||
const shortcuts = store.get('shortcuts');
|
||||
|
||||
// 注销所有已注册的快捷键
|
||||
globalShortcut.unregisterAll();
|
||||
|
||||
// 显示/隐藏主窗口
|
||||
globalShortcut.register(shortcuts.toggleWindow, () => {
|
||||
if (mainWindow.isVisible()) {
|
||||
mainWindow.hide();
|
||||
} else {
|
||||
mainWindow.show();
|
||||
}
|
||||
});
|
||||
|
||||
// 播放/暂停
|
||||
globalShortcut.register(shortcuts.togglePlay, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'togglePlay');
|
||||
});
|
||||
|
||||
// 上一首
|
||||
globalShortcut.register(shortcuts.prevPlay, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'prevPlay');
|
||||
});
|
||||
|
||||
// 下一首
|
||||
globalShortcut.register(shortcuts.nextPlay, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'nextPlay');
|
||||
});
|
||||
|
||||
// 音量增加
|
||||
globalShortcut.register(shortcuts.volumeUp, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'volumeUp');
|
||||
});
|
||||
|
||||
// 音量减少
|
||||
globalShortcut.register(shortcuts.volumeDown, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'volumeDown');
|
||||
});
|
||||
|
||||
// 收藏当前歌曲
|
||||
globalShortcut.register(shortcuts.toggleFavorite, () => {
|
||||
mainWindow.webContents.send('global-shortcut', 'toggleFavorite');
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化快捷键
|
||||
export function initializeShortcuts(mainWindow: Electron.BrowserWindow) {
|
||||
mainWindowRef = mainWindow;
|
||||
registerShortcuts(mainWindow);
|
||||
|
||||
// 监听禁用快捷键事件
|
||||
ipcMain.on('disable-shortcuts', () => {
|
||||
globalShortcut.unregisterAll();
|
||||
});
|
||||
|
||||
// 监听启用快捷键事件
|
||||
ipcMain.on('enable-shortcuts', () => {
|
||||
if (mainWindowRef) {
|
||||
registerShortcuts(mainWindowRef);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { app, Menu, nativeImage, Tray, BrowserWindow } from 'electron';
|
||||
import { app, BrowserWindow, Menu, nativeImage, Tray } from 'electron';
|
||||
import { join } from 'path';
|
||||
|
||||
let tray: Tray | null = null;
|
||||
@@ -7,7 +7,9 @@ let tray: Tray | null = null;
|
||||
* 初始化系统托盘
|
||||
*/
|
||||
export function initializeTray(iconPath: string, mainWindow: BrowserWindow) {
|
||||
const trayIcon = nativeImage.createFromPath(join(iconPath, 'icon_16x16.png')).resize({ width: 16, height: 16 });
|
||||
const trayIcon = nativeImage
|
||||
.createFromPath(join(iconPath, 'icon_16x16.png'))
|
||||
.resize({ width: 16, height: 16 });
|
||||
tray = new Tray(trayIcon);
|
||||
|
||||
// 创建一个上下文菜单
|
||||
@@ -16,15 +18,15 @@ export function initializeTray(iconPath: string, mainWindow: BrowserWindow) {
|
||||
label: '显示',
|
||||
click: () => {
|
||||
mainWindow.show();
|
||||
},
|
||||
}
|
||||
},
|
||||
{
|
||||
label: '退出',
|
||||
click: () => {
|
||||
mainWindow.destroy();
|
||||
app.quit();
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
// 设置系统托盘图标的上下文菜单
|
||||
@@ -40,4 +42,4 @@ export function initializeTray(iconPath: string, mainWindow: BrowserWindow) {
|
||||
});
|
||||
|
||||
return tray;
|
||||
}
|
||||
}
|
||||
|
||||
90
src/main/modules/update.ts
Normal file
90
src/main/modules/update.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import axios from 'axios';
|
||||
import { exec } from 'child_process';
|
||||
import { app, BrowserWindow, ipcMain } from 'electron';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
export function setupUpdateHandlers(_mainWindow: BrowserWindow) {
|
||||
ipcMain.on('start-download', async (event, url: string) => {
|
||||
try {
|
||||
const response = await axios({
|
||||
url,
|
||||
method: 'GET',
|
||||
responseType: 'stream',
|
||||
onDownloadProgress: (progressEvent: { loaded: number; total?: number }) => {
|
||||
if (!progressEvent.total) return;
|
||||
const percent = Math.round((progressEvent.loaded / progressEvent.total) * 100);
|
||||
const downloaded = (progressEvent.loaded / 1024 / 1024).toFixed(2);
|
||||
const total = (progressEvent.total / 1024 / 1024).toFixed(2);
|
||||
event.sender.send('download-progress', percent, `已下载 ${downloaded}MB / ${total}MB`);
|
||||
}
|
||||
});
|
||||
|
||||
const fileName = url.split('/').pop() || 'update.exe';
|
||||
const downloadPath = path.join(app.getPath('downloads'), fileName);
|
||||
|
||||
// 创建写入流
|
||||
const writer = fs.createWriteStream(downloadPath);
|
||||
|
||||
// 将响应流写入文件
|
||||
response.data.pipe(writer);
|
||||
|
||||
// 处理写入完成
|
||||
writer.on('finish', () => {
|
||||
event.sender.send('download-complete', true, downloadPath);
|
||||
});
|
||||
|
||||
// 处理写入错误
|
||||
writer.on('error', (error) => {
|
||||
console.error('Write file error:', error);
|
||||
event.sender.send('download-complete', false, '');
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Download failed:', error);
|
||||
event.sender.send('download-complete', false, '');
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.on('install-update', (_event, filePath: string) => {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
console.error('Installation file not found:', filePath);
|
||||
return;
|
||||
}
|
||||
|
||||
const { platform } = process;
|
||||
|
||||
// 关闭当前应用
|
||||
app.quit();
|
||||
|
||||
// 根据不同平台执行安装
|
||||
if (platform === 'win32') {
|
||||
exec(`"${filePath}"`, (error) => {
|
||||
if (error) {
|
||||
console.error('Error starting installer:', error);
|
||||
}
|
||||
});
|
||||
} else if (platform === 'darwin') {
|
||||
// 挂载 DMG 文件
|
||||
exec(`open "${filePath}"`, (error) => {
|
||||
if (error) {
|
||||
console.error('Error opening DMG:', error);
|
||||
}
|
||||
});
|
||||
} else if (platform === 'linux') {
|
||||
const ext = path.extname(filePath);
|
||||
if (ext === '.AppImage') {
|
||||
exec(`chmod +x "${filePath}" && "${filePath}"`, (error) => {
|
||||
if (error) {
|
||||
console.error('Error running AppImage:', error);
|
||||
}
|
||||
});
|
||||
} else if (ext === '.deb') {
|
||||
exec(`pkexec dpkg -i "${filePath}"`, (error) => {
|
||||
if (error) {
|
||||
console.error('Error installing deb package:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BrowserWindow, shell, ipcMain, app, session } from 'electron';
|
||||
import { is } from '@electron-toolkit/utils';
|
||||
import { join } from 'path';
|
||||
import { app, BrowserWindow, ipcMain, session, shell } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
import { join } from 'path';
|
||||
|
||||
const store = new Store();
|
||||
|
||||
@@ -116,4 +116,4 @@ export function createMainWindow(icon: Electron.NativeImage): BrowserWindow {
|
||||
}
|
||||
|
||||
return mainWindow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ipcMain } from 'electron';
|
||||
import Store from 'electron-store';
|
||||
import fs from 'fs';
|
||||
import server from 'netease-cloud-music-api-alger/server';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
|
||||
@@ -16,9 +17,6 @@ ipcMain.handle('unblock-music', async (_, id, data) => {
|
||||
return unblockMusic(id, data);
|
||||
});
|
||||
|
||||
import server from 'netease-cloud-music-api-alger/server';
|
||||
|
||||
|
||||
async function startMusicApi(): Promise<void> {
|
||||
console.log('MUSIC API STARTED');
|
||||
|
||||
|
||||
@@ -14,5 +14,9 @@
|
||||
"authorUrl": "https://github.com/algerkong",
|
||||
"musicApiPort": 30488,
|
||||
"closeAction": "ask",
|
||||
"musicQuality": "higher"
|
||||
"musicQuality": "higher",
|
||||
"fontFamily": "system-ui",
|
||||
"fontScope": "global",
|
||||
"autoPlay": false,
|
||||
"downloadPath": ""
|
||||
}
|
||||
|
||||
@@ -1,23 +1,75 @@
|
||||
import match from '@unblockneteasemusic/server';
|
||||
|
||||
const unblockMusic = async (id: any, songData: any): Promise<any> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
match(parseInt(id, 10), ['qq', 'migu', 'kugou', 'joox'], songData)
|
||||
.then((data) => {
|
||||
resolve({
|
||||
data: {
|
||||
data,
|
||||
params: {
|
||||
id,
|
||||
type: 'song'
|
||||
}
|
||||
type Platform = 'qq' | 'migu' | 'kugou' | 'pyncmd' | 'joox' | 'kuwo' | 'bilibili' | 'youtube';
|
||||
|
||||
interface SongData {
|
||||
name: string;
|
||||
artists: Array<{ name: string }>;
|
||||
album?: { name: string };
|
||||
}
|
||||
|
||||
interface ResponseData {
|
||||
url: string;
|
||||
br: number;
|
||||
size: number;
|
||||
md5?: string;
|
||||
platform?: Platform;
|
||||
gain?: number;
|
||||
}
|
||||
|
||||
interface UnblockResult {
|
||||
data: {
|
||||
data: ResponseData;
|
||||
params: {
|
||||
id: number;
|
||||
type: 'song';
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 音乐解析函数
|
||||
* @param id 歌曲ID
|
||||
* @param songData 歌曲信息
|
||||
* @param retryCount 重试次数
|
||||
* @returns Promise<UnblockResult>
|
||||
*/
|
||||
const unblockMusic = async (
|
||||
id: number | string,
|
||||
songData: SongData,
|
||||
retryCount = 3
|
||||
): Promise<UnblockResult> => {
|
||||
// 所有可用平台
|
||||
const platforms: Platform[] = ['migu', 'kugou', 'pyncmd', 'joox', 'kuwo', 'bilibili', 'youtube'];
|
||||
|
||||
const retry = async (attempt: number): Promise<UnblockResult> => {
|
||||
try {
|
||||
const data = await match(parseInt(String(id), 10), platforms, songData);
|
||||
const result: UnblockResult = {
|
||||
data: {
|
||||
data,
|
||||
params: {
|
||||
id: parseInt(String(id), 10),
|
||||
type: 'song'
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
return result;
|
||||
} catch (err) {
|
||||
if (attempt < retryCount) {
|
||||
// 延迟重试,每次重试增加延迟时间
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
|
||||
return retry(attempt + 1);
|
||||
}
|
||||
|
||||
// 所有重试都失败后,抛出详细错误
|
||||
throw new Error(
|
||||
`音乐解析失败 (ID: ${id}): ${err instanceof Error ? err.message : '未知错误'}`
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return retry(1);
|
||||
};
|
||||
|
||||
export { unblockMusic };
|
||||
export { type Platform, type ResponseData, type SongData, unblockMusic, type UnblockResult };
|
||||
|
||||
7
src/preload/index.d.ts
vendored
7
src/preload/index.d.ts
vendored
@@ -13,7 +13,12 @@ declare global {
|
||||
miniTray: () => void;
|
||||
restart: () => void;
|
||||
unblockMusic: (id: number, data: any) => Promise<any>;
|
||||
startDownload: (url: string) => void;
|
||||
onDownloadProgress: (callback: (progress: number, status: string) => void) => void;
|
||||
onDownloadComplete: (callback: (success: boolean, filePath: string) => void) => void;
|
||||
removeDownloadListeners: () => void;
|
||||
invoke: (channel: string, ...args: any[]) => Promise<any>;
|
||||
};
|
||||
$message:any
|
||||
$message: any;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,34 @@ const api = {
|
||||
restart: () => ipcRenderer.send('restart'),
|
||||
openLyric: () => ipcRenderer.send('open-lyric'),
|
||||
sendLyric: (data) => ipcRenderer.send('send-lyric', data),
|
||||
unblockMusic: (id) => ipcRenderer.invoke('unblock-music', id)
|
||||
unblockMusic: (id) => ipcRenderer.invoke('unblock-music', id),
|
||||
// 更新相关
|
||||
startDownload: (url: string) => ipcRenderer.send('start-download', url),
|
||||
onDownloadProgress: (callback: (progress: number, status: string) => void) => {
|
||||
ipcRenderer.on('download-progress', (_event, progress, status) => callback(progress, status));
|
||||
},
|
||||
onDownloadComplete: (callback: (success: boolean, filePath: string) => void) => {
|
||||
ipcRenderer.on('download-complete', (_event, success, filePath) => callback(success, filePath));
|
||||
},
|
||||
removeDownloadListeners: () => {
|
||||
ipcRenderer.removeAllListeners('download-progress');
|
||||
ipcRenderer.removeAllListeners('download-complete');
|
||||
},
|
||||
// 歌词缓存相关
|
||||
invoke: (channel: string, ...args: any[]) => {
|
||||
const validChannels = [
|
||||
'get-lyrics',
|
||||
'clear-lyrics-cache',
|
||||
'get-system-fonts',
|
||||
'get-cached-lyric',
|
||||
'cache-lyric',
|
||||
'clear-lyric-cache'
|
||||
];
|
||||
if (validChannels.includes(channel)) {
|
||||
return ipcRenderer.invoke(channel, ...args);
|
||||
}
|
||||
return Promise.reject(new Error(`未授权的 IPC 通道: ${channel}`));
|
||||
}
|
||||
};
|
||||
|
||||
// Use `contextBridge` APIs to expose Electron APIs to
|
||||
|
||||
@@ -12,11 +12,11 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { darkTheme, lightTheme } from 'naive-ui';
|
||||
import { onMounted } from 'vue';
|
||||
import { isElectron } from '@/utils';
|
||||
import { computed, onMounted, watch } from 'vue';
|
||||
|
||||
import homeRouter from '@/router/home';
|
||||
import store from '@/store';
|
||||
import { isElectron } from '@/utils';
|
||||
|
||||
import { isMobile } from './utils';
|
||||
|
||||
@@ -24,9 +24,46 @@ const theme = computed(() => {
|
||||
return store.state.theme;
|
||||
});
|
||||
|
||||
// 监听字体变化并应用
|
||||
watch(
|
||||
() => [store.state.setData.fontFamily, store.state.setData.fontScope],
|
||||
([newFont, fontScope]) => {
|
||||
const appElement = document.body;
|
||||
if (!appElement) return;
|
||||
|
||||
const defaultFonts =
|
||||
'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
|
||||
|
||||
// 只有在全局模式下才应用字体
|
||||
if (fontScope !== 'global') {
|
||||
appElement.style.fontFamily = defaultFonts;
|
||||
return;
|
||||
}
|
||||
|
||||
if (newFont === 'system-ui') {
|
||||
appElement.style.fontFamily = defaultFonts;
|
||||
} else {
|
||||
// 处理多个字体,确保每个字体名都被正确引用
|
||||
const fontList = newFont.split(',').map((font) => {
|
||||
const trimmedFont = font.trim();
|
||||
// 如果字体名包含空格或特殊字符,添加引号(如果还没有引号的话)
|
||||
return /[\s'"()]/.test(trimmedFont) && !/^['"].*['"]$/.test(trimmedFont)
|
||||
? `"${trimmedFont}"`
|
||||
: trimmedFont;
|
||||
});
|
||||
|
||||
// 将选择的字体和默认字体组合
|
||||
appElement.style.fontFamily = `${fontList.join(', ')}, ${defaultFonts}`;
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
onMounted(() => {
|
||||
store.dispatch('initializeSettings');
|
||||
store.dispatch('initializeTheme');
|
||||
store.dispatch('initializeSystemFonts');
|
||||
store.dispatch('initializePlayState');
|
||||
if (isMobile.value) {
|
||||
store.commit(
|
||||
'setMenus',
|
||||
|
||||
21
src/renderer/api/artist.ts
Normal file
21
src/renderer/api/artist.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import request from '@/utils/request';
|
||||
|
||||
// 获取歌手详情
|
||||
export const getArtistDetail = (id) => {
|
||||
return request.get('/artist/detail', { params: { id } });
|
||||
};
|
||||
|
||||
// 获取歌手热门歌曲
|
||||
export const getArtistTopSongs = (params) => {
|
||||
return request.get('/artist/songs', {
|
||||
params: {
|
||||
...params,
|
||||
order: 'hot'
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 获取歌手专辑
|
||||
export const getArtistAlbums = (params) => {
|
||||
return request.get('/artist/album', { params });
|
||||
};
|
||||
@@ -1,8 +1,11 @@
|
||||
import { ILyric } from '@/type/lyric';
|
||||
import { musicDB } from '@/hooks/MusicHook';
|
||||
import store from '@/store';
|
||||
import type { ILyric } from '@/type/lyric';
|
||||
import { isElectron } from '@/utils';
|
||||
import request from '@/utils/request';
|
||||
import requestMusic from '@/utils/request_music';
|
||||
import store from '@/store';
|
||||
|
||||
const { addData, getData, deleteData } = musicDB;
|
||||
|
||||
// 获取音乐音质详情
|
||||
export const getMusicQualityDetail = (id: number) => {
|
||||
@@ -11,22 +14,22 @@ export const getMusicQualityDetail = (id: number) => {
|
||||
|
||||
// 根据音乐Id获取音乐播放URl
|
||||
export const getMusicUrl = async (id: number) => {
|
||||
const res = await request.get('/song/download/url/v1', {
|
||||
params: {
|
||||
id,
|
||||
const res = await request.get('/song/download/url/v1', {
|
||||
params: {
|
||||
id,
|
||||
level: store.state.setData.musicQuality || 'higher'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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', {
|
||||
params: {
|
||||
id,
|
||||
return await request.get('/song/url/v1', {
|
||||
params: {
|
||||
id,
|
||||
level: store.state.setData.musicQuality || 'higher'
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -36,8 +39,32 @@ export const getMusicDetail = (ids: Array<number>) => {
|
||||
};
|
||||
|
||||
// 根据音乐Id获取音乐歌词
|
||||
export const getMusicLrc = (id: number) => {
|
||||
return request.get<ILyric>('/lyric', { params: { id } });
|
||||
export const getMusicLrc = async (id: number) => {
|
||||
const TEN_DAYS_MS = 10 * 24 * 60 * 60 * 1000; // 10天的毫秒数
|
||||
|
||||
try {
|
||||
// 尝试获取缓存的歌词
|
||||
const cachedLyric = await getData('music_lyric', id);
|
||||
if (cachedLyric?.createTime && Date.now() - cachedLyric.createTime < TEN_DAYS_MS) {
|
||||
return { ...cachedLyric };
|
||||
}
|
||||
|
||||
// 获取新的歌词数据
|
||||
const res = await request.get<ILyric>('/lyric', { params: { id } });
|
||||
|
||||
// 只有在成功获取新数据后才删除旧缓存并添加新缓存
|
||||
if (res?.data) {
|
||||
if (cachedLyric) {
|
||||
await deleteData('music_lyric', id);
|
||||
}
|
||||
addData('music_lyric', { id, data: res.data, createTime: Date.now() });
|
||||
}
|
||||
|
||||
return res;
|
||||
} catch (error) {
|
||||
console.error('获取歌词失败:', error);
|
||||
throw error; // 向上抛出错误,让调用者处理
|
||||
}
|
||||
};
|
||||
|
||||
export const getParsingMusicUrl = (id: number, data: any) => {
|
||||
@@ -56,3 +83,17 @@ export const likeSong = (id: number, like: boolean = true) => {
|
||||
export const getLikedList = () => {
|
||||
return request.get('/likelist');
|
||||
};
|
||||
|
||||
// 创建歌单
|
||||
export const createPlaylist = (params: { name: string; privacy: number }) => {
|
||||
return request.post('/playlist/create', params);
|
||||
};
|
||||
|
||||
// 添加或删除歌单歌曲
|
||||
export const updatePlaylistTracks = (params: {
|
||||
op: 'add' | 'del';
|
||||
pid: number;
|
||||
tracks: string;
|
||||
}) => {
|
||||
return request.get('/playlist/tracks', { params });
|
||||
};
|
||||
|
||||
@@ -3,6 +3,8 @@ import request from '@/utils/request';
|
||||
interface IParams {
|
||||
keywords: string;
|
||||
type: number;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
// 搜索内容
|
||||
export const getSearch = (params: IParams) => {
|
||||
|
||||
3687
src/renderer/assets/css/animate.css
vendored
3687
src/renderer/assets/css/animate.css
vendored
File diff suppressed because it is too large
Load Diff
@@ -5,3 +5,11 @@ body {
|
||||
.n-popover:has(.music-play) {
|
||||
border-radius: 1.5rem !important;
|
||||
}
|
||||
.n-popover {
|
||||
border-radius: 0.5rem !important;
|
||||
overflow: hidden !important;
|
||||
}
|
||||
.n-popover:has(.transparent-popover ) {
|
||||
background-color: transparent !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
14
src/renderer/components.d.ts
vendored
14
src/renderer/components.d.ts
vendored
@@ -8,31 +8,45 @@ 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']
|
||||
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']
|
||||
NForm: typeof import('naive-ui')['NForm']
|
||||
NFormItem: typeof import('naive-ui')['NFormItem']
|
||||
NIcon: typeof import('naive-ui')['NIcon']
|
||||
NImage: typeof import('naive-ui')['NImage']
|
||||
NInput: typeof import('naive-ui')['NInput']
|
||||
NInputNumber: typeof import('naive-ui')['NInputNumber']
|
||||
NLayout: typeof import('naive-ui')['NLayout']
|
||||
NList: typeof import('naive-ui')['NList']
|
||||
NListItem: typeof import('naive-ui')['NListItem']
|
||||
NMessageProvider: typeof import('naive-ui')['NMessageProvider']
|
||||
NModal: typeof import('naive-ui')['NModal']
|
||||
NPopover: typeof import('naive-ui')['NPopover']
|
||||
NProgress: typeof import('naive-ui')['NProgress']
|
||||
NRadio: typeof import('naive-ui')['NRadio']
|
||||
NRadioButton: typeof import('naive-ui')['NRadioButton']
|
||||
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
|
||||
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']
|
||||
NTooltip: typeof import('naive-ui')['NTooltip']
|
||||
NTransfer: typeof import('naive-ui')['NTransfer']
|
||||
NVirtualList: typeof import('naive-ui')['NVirtualList']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
|
||||
@@ -49,8 +49,10 @@
|
||||
|
||||
<script setup>
|
||||
import { NButton, NImage, NPopover } from 'naive-ui';
|
||||
|
||||
import alipay from '@/assets/alipay.png';
|
||||
import wechat from '@/assets/wechat.png';
|
||||
|
||||
const message = useMessage();
|
||||
const copyQQ = () => {
|
||||
navigator.clipboard.writeText('789288579');
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
mask-closable
|
||||
:style="{ backgroundColor: 'transparent' }"
|
||||
:to="`#layout-main`"
|
||||
:z-index="zIndex"
|
||||
@mask-click="close"
|
||||
>
|
||||
<div class="music-page">
|
||||
@@ -17,7 +18,7 @@
|
||||
</div>
|
||||
</n-ellipsis>
|
||||
<div class="music-close">
|
||||
<i class="icon iconfont icon-icon_error" @click="close"></i>
|
||||
<i class="icon iconfont ri-close-line" @click="close"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="music-content">
|
||||
@@ -58,7 +59,12 @@
|
||||
:class="setAnimationClass('animate__bounceInUp')"
|
||||
:style="getItemAnimationDelay(index)"
|
||||
>
|
||||
<song-item :item="formatDetail(item)" @play="handlePlay" />
|
||||
<song-item
|
||||
:item="formatDetail(item)"
|
||||
:can-remove="canRemove"
|
||||
@play="handlePlay"
|
||||
@remove-song="(id) => emit('remove-song', id)"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="isLoadingMore" class="loading-more">加载更多...</div>
|
||||
<play-bottom />
|
||||
@@ -88,6 +94,7 @@ const props = withDefaults(
|
||||
defineProps<{
|
||||
show: boolean;
|
||||
name: string;
|
||||
zIndex?: number;
|
||||
songList: any[];
|
||||
loading?: boolean;
|
||||
listInfo?: {
|
||||
@@ -95,14 +102,17 @@ const props = withDefaults(
|
||||
[key: string]: any;
|
||||
};
|
||||
cover?: boolean;
|
||||
canRemove?: boolean;
|
||||
}>(),
|
||||
{
|
||||
loading: false,
|
||||
cover: true
|
||||
cover: true,
|
||||
zIndex: 9996,
|
||||
canRemove: false
|
||||
}
|
||||
);
|
||||
|
||||
const emit = defineEmits(['update:show', 'update:loading']);
|
||||
const emit = defineEmits(['update:show', 'update:loading', 'remove-song']);
|
||||
|
||||
const page = ref(0);
|
||||
const pageSize = 20;
|
||||
@@ -234,7 +244,7 @@ watch(
|
||||
}
|
||||
|
||||
&-close {
|
||||
@apply cursor-pointer text-gray-900 dark:text-white flex gap-2 items-center;
|
||||
@apply cursor-pointer text-gray-500 dark:text-white hover:text-gray-900 dark:hover:text-gray-300 flex gap-2 items-center transition;
|
||||
.icon {
|
||||
@apply text-3xl;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<MusicList
|
||||
<music-list
|
||||
v-model:show="showMusic"
|
||||
:name="albumName"
|
||||
:song-list="songList"
|
||||
@@ -36,9 +36,9 @@ import { onMounted, ref } from 'vue';
|
||||
|
||||
import { getNewAlbum } from '@/api/home';
|
||||
import { getAlbum } from '@/api/list';
|
||||
import MusicList from '@/components/MusicList.vue';
|
||||
import type { IAlbumNew } from '@/type/album';
|
||||
import { getImgUrl, setAnimationClass, setAnimationDelay } from '@/utils';
|
||||
import MusicList from '@/components/MusicList.vue';
|
||||
|
||||
const albumData = ref<IAlbumNew>();
|
||||
const loadAlbumList = async () => {
|
||||
|
||||
@@ -74,11 +74,11 @@ import { onMounted, ref } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { getDayRecommend, getHotSinger } from '@/api/home';
|
||||
import MusicList from '@/components/MusicList.vue';
|
||||
import router from '@/router';
|
||||
import { IDayRecommend } from '@/type/day_recommend';
|
||||
import type { IHotSinger } from '@/type/singer';
|
||||
import { getImgUrl, setAnimationClass, setAnimationDelay, setBackgroundImg } from '@/utils';
|
||||
import MusicList from '@/components/MusicList.vue';
|
||||
|
||||
const store = useStore();
|
||||
|
||||
|
||||
91
src/renderer/components/ShortcutToast.vue
Normal file
91
src/renderer/components/ShortcutToast.vue
Normal file
@@ -0,0 +1,91 @@
|
||||
<template>
|
||||
<transition name="shortcut-toast">
|
||||
<div v-if="visible" class="shortcut-toast">
|
||||
<div class="shortcut-toast-content">
|
||||
<div class="shortcut-toast-icon">
|
||||
<i :class="icon"></i>
|
||||
</div>
|
||||
<div class="shortcut-toast-text">{{ text }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { onBeforeUnmount, ref } from 'vue';
|
||||
|
||||
const visible = ref(false);
|
||||
const text = ref('');
|
||||
const icon = ref('');
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
|
||||
const show = (message: string, iconName: string) => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
text.value = message;
|
||||
icon.value = iconName;
|
||||
visible.value = true;
|
||||
|
||||
timer = setTimeout(() => {
|
||||
visible.value = false;
|
||||
// 在动画结束后触发销毁事件
|
||||
setTimeout(() => {
|
||||
emit('destroy');
|
||||
}, 300);
|
||||
}, 1500);
|
||||
};
|
||||
|
||||
// 清理定时器
|
||||
onBeforeUnmount(() => {
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['destroy']);
|
||||
|
||||
// 暴露方法给父组件
|
||||
defineExpose({
|
||||
show
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.shortcut-toast {
|
||||
@apply fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 z-[9999];
|
||||
@apply flex items-center justify-center;
|
||||
|
||||
&-content {
|
||||
@apply flex flex-col items-center gap-2 p-4 rounded-lg;
|
||||
@apply bg-light-200 bg-opacity-70 dark:bg-dark-200 dark:bg-opacity-90;
|
||||
@apply text-dark-100 dark:text-light-100;
|
||||
@apply shadow-lg backdrop-blur-sm;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
&-icon {
|
||||
@apply text-3xl;
|
||||
}
|
||||
|
||||
&-text {
|
||||
@apply text-sm font-medium text-center;
|
||||
}
|
||||
}
|
||||
|
||||
.shortcut-toast-enter-active,
|
||||
.shortcut-toast-leave-active {
|
||||
@apply transition-all duration-300;
|
||||
}
|
||||
|
||||
.shortcut-toast-enter-from,
|
||||
.shortcut-toast-leave-to {
|
||||
@apply opacity-0 scale-90;
|
||||
}
|
||||
|
||||
.shortcut-toast-enter-to,
|
||||
.shortcut-toast-leave-from {
|
||||
@apply opacity-100 scale-100;
|
||||
}
|
||||
</style>
|
||||
317
src/renderer/components/common/ArtistDrawer.vue
Normal file
317
src/renderer/components/common/ArtistDrawer.vue
Normal file
@@ -0,0 +1,317 @@
|
||||
<template>
|
||||
<n-drawer
|
||||
v-model:show="modelValue"
|
||||
:width="800"
|
||||
placement="right"
|
||||
:mask-closable="true"
|
||||
:z-index="9997"
|
||||
>
|
||||
<div v-loading="loading" class="artist-drawer">
|
||||
<div class="close-btn">
|
||||
<i class="ri-close-line" @click="modelValue = false"></i>
|
||||
</div>
|
||||
|
||||
<!-- 歌手信息头部 -->
|
||||
<div class="artist-header">
|
||||
<div class="artist-cover">
|
||||
<n-image
|
||||
:src="getImgUrl(artistInfo?.avatar, '300y300')"
|
||||
class="w-48 h-48 rounded-2xl object-cover"
|
||||
preview-disabled
|
||||
/>
|
||||
</div>
|
||||
<div class="artist-info">
|
||||
<h1 class="artist-name">{{ artistInfo?.name }}</h1>
|
||||
<div v-if="artistInfo?.alias?.length" class="artist-alias">
|
||||
{{ artistInfo.alias.join(' / ') }}
|
||||
</div>
|
||||
<div v-if="artistInfo?.briefDesc" class="artist-desc">
|
||||
{{ artistInfo.briefDesc }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 标签页切换 -->
|
||||
<n-tabs v-model:value="activeTab" class="flex-1" type="line" animated>
|
||||
<n-tab-pane name="songs" tab="热门歌曲">
|
||||
<div ref="songListRef" class="songs-list">
|
||||
<n-scrollbar style="max-height: 61vh" :size="5" @scroll="handleSongScroll">
|
||||
<div class="song-list-content">
|
||||
<song-item
|
||||
v-for="song in songs"
|
||||
:key="song.id"
|
||||
:item="song"
|
||||
:list="true"
|
||||
@play="handlePlay"
|
||||
/>
|
||||
<div v-if="songLoading" class="loading-more">加载中...</div>
|
||||
</div>
|
||||
<play-bottom />
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
|
||||
<n-tab-pane name="albums" tab="专辑">
|
||||
<div ref="albumListRef" class="albums-list">
|
||||
<n-scrollbar style="max-height: 61vh" :size="5" @scroll="handleAlbumScroll">
|
||||
<div class="albums-grid">
|
||||
<search-item
|
||||
v-for="album in albums"
|
||||
:key="album.id"
|
||||
shape="square"
|
||||
:z-index="9998"
|
||||
:item="{
|
||||
id: album.id,
|
||||
picUrl: album.picUrl,
|
||||
name: album.name,
|
||||
desc: formatPublishTime(album.publishTime),
|
||||
size: album.size,
|
||||
type: '专辑'
|
||||
}"
|
||||
/>
|
||||
<div v-if="albumLoading" class="loading-more">加载中...</div>
|
||||
</div>
|
||||
<play-bottom />
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
|
||||
<n-tab-pane name="about" tab="艺人介绍">
|
||||
<div class="artist-description">
|
||||
<n-scrollbar style="max-height: 60vh">
|
||||
<div class="description-content" v-html="artistInfo?.briefDesc"></div>
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
</n-tabs>
|
||||
</div>
|
||||
</n-drawer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDateFormat } from '@vueuse/core';
|
||||
import { ref, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { getArtistAlbums, getArtistDetail, getArtistTopSongs } from '@/api/artist';
|
||||
import { getMusicDetail } from '@/api/music';
|
||||
import SearchItem from '@/components/common/SearchItem.vue';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
import { IArtist } from '@/type/artist';
|
||||
import { getImgUrl } from '@/utils';
|
||||
|
||||
import PlayBottom from './PlayBottom.vue';
|
||||
|
||||
const modelValue = defineModel<boolean>('show', { required: true });
|
||||
|
||||
const store = useStore();
|
||||
const activeTab = ref('songs');
|
||||
const currentArtistId = ref<number>();
|
||||
|
||||
// 歌手信息
|
||||
const artistInfo = ref<IArtist>();
|
||||
const songs = ref<any[]>([]);
|
||||
const albums = ref<any[]>([]);
|
||||
|
||||
// 加载状态
|
||||
const songLoading = ref(false);
|
||||
const albumLoading = ref(false);
|
||||
|
||||
// 分页参数
|
||||
const songPage = ref({
|
||||
page: 1,
|
||||
pageSize: 30,
|
||||
hasMore: true
|
||||
});
|
||||
|
||||
const albumPage = ref({
|
||||
page: 1,
|
||||
pageSize: 30,
|
||||
hasMore: true
|
||||
});
|
||||
|
||||
watch(modelValue, (newVal) => {
|
||||
store.commit('setShowArtistDrawer', newVal);
|
||||
});
|
||||
const loading = ref(false);
|
||||
// 加载歌手信息
|
||||
const loadArtistInfo = async (id: number) => {
|
||||
if (currentArtistId.value === id) return;
|
||||
activeTab.value = 'songs';
|
||||
loading.value = true;
|
||||
currentArtistId.value = id;
|
||||
try {
|
||||
const info = await getArtistDetail(id);
|
||||
if (info.data?.data?.artist) {
|
||||
artistInfo.value = info.data.data.artist;
|
||||
}
|
||||
// 重置分页并加载初始数据
|
||||
resetPagination();
|
||||
await Promise.all([loadSongs(), loadAlbums()]);
|
||||
} catch (error) {
|
||||
console.error('加载歌手信息失败:', error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 重置分页
|
||||
const resetPagination = () => {
|
||||
songPage.value = {
|
||||
page: 1,
|
||||
pageSize: 30,
|
||||
hasMore: true
|
||||
};
|
||||
albumPage.value = {
|
||||
page: 1,
|
||||
pageSize: 30,
|
||||
hasMore: true
|
||||
};
|
||||
songs.value = [];
|
||||
albums.value = [];
|
||||
};
|
||||
|
||||
// 加载歌曲
|
||||
const loadSongs = async () => {
|
||||
if (!currentArtistId.value || !songPage.value.hasMore || songLoading.value) return;
|
||||
|
||||
try {
|
||||
songLoading.value = true;
|
||||
const { page, pageSize } = songPage.value;
|
||||
const res = await getArtistTopSongs({
|
||||
id: currentArtistId.value,
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize
|
||||
});
|
||||
|
||||
const ids = res.data.songs.map((item) => item.id);
|
||||
const songsDetail = await getMusicDetail(ids);
|
||||
|
||||
if (songsDetail.data?.songs) {
|
||||
const newSongs = songsDetail.data.songs.map((item) => {
|
||||
return {
|
||||
...item,
|
||||
picUrl: item.al.picUrl,
|
||||
song: {
|
||||
artists: item.ar,
|
||||
name: item.name,
|
||||
id: item.id
|
||||
}
|
||||
};
|
||||
});
|
||||
songs.value = page === 1 ? newSongs : [...songs.value, ...newSongs];
|
||||
songPage.value.hasMore = newSongs.length === pageSize;
|
||||
songPage.value.page++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载歌曲失败:', error);
|
||||
} finally {
|
||||
songLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 加载专辑
|
||||
const loadAlbums = async () => {
|
||||
if (!currentArtistId.value || !albumPage.value.hasMore || albumLoading.value) return;
|
||||
|
||||
try {
|
||||
albumLoading.value = true;
|
||||
const { page, pageSize } = albumPage.value;
|
||||
const res = await getArtistAlbums({
|
||||
id: currentArtistId.value,
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize
|
||||
});
|
||||
|
||||
if (res.data?.hotAlbums) {
|
||||
const newAlbums = res.data.hotAlbums;
|
||||
albums.value = page === 1 ? newAlbums : [...albums.value, ...newAlbums];
|
||||
albumPage.value.hasMore = newAlbums.length === pageSize;
|
||||
albumPage.value.page++;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载专辑失败:', error);
|
||||
} finally {
|
||||
albumLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 处理滚动加载
|
||||
const handleSongScroll = (e: { target: any }) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = e.target;
|
||||
if (scrollHeight - scrollTop - clientHeight < 50) {
|
||||
loadSongs();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAlbumScroll = (e: { target: any }) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = e.target;
|
||||
if (scrollHeight - scrollTop - clientHeight < 50) {
|
||||
loadAlbums();
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化发布时间
|
||||
const formatPublishTime = (time: number) => {
|
||||
return useDateFormat(time, 'YYYY-MM-DD').value;
|
||||
};
|
||||
|
||||
const handlePlay = () => {
|
||||
store.commit(
|
||||
'setPlayList',
|
||||
songs.value.map((item) => ({
|
||||
...item,
|
||||
picUrl: item.al.picUrl
|
||||
}))
|
||||
);
|
||||
};
|
||||
|
||||
// 暴露方法给父组件
|
||||
defineExpose({
|
||||
loadArtistInfo
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.artist-drawer {
|
||||
@apply h-full bg-light dark:bg-dark px-6 overflow-hidden flex flex-col;
|
||||
|
||||
.close-btn {
|
||||
@apply absolute top-4 right-4 text-gray-500 dark:text-gray-400 hover:text-green-500 text-2xl cursor-pointer p-2;
|
||||
}
|
||||
|
||||
.artist-header {
|
||||
@apply flex gap-6 pt-6;
|
||||
|
||||
.artist-info {
|
||||
@apply flex-1;
|
||||
|
||||
.artist-name {
|
||||
@apply text-4xl font-bold mb-2;
|
||||
}
|
||||
|
||||
.artist-alias {
|
||||
@apply text-gray-500 dark:text-gray-400 mb-2;
|
||||
}
|
||||
|
||||
.artist-desc {
|
||||
@apply text-sm text-gray-600 dark:text-gray-300 line-clamp-3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.albums-grid {
|
||||
@apply grid gap-4 grid-cols-5;
|
||||
}
|
||||
|
||||
.loading-more {
|
||||
@apply text-center py-4 text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
|
||||
.artist-description {
|
||||
.description-content {
|
||||
@apply text-sm leading-relaxed whitespace-pre-wrap;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
388
src/renderer/components/common/DonationList.vue
Normal file
388
src/renderer/components/common/DonationList.vue
Normal file
@@ -0,0 +1,388 @@
|
||||
<template>
|
||||
<div class="donation-container">
|
||||
<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 displayDonors"
|
||||
:key="donor.id"
|
||||
class="donation-card animate__animated"
|
||||
:class="getAnimationClass(index)"
|
||||
:style="{ animationDelay: `${index * 0.1}s` }"
|
||||
@mouseenter="handleMouseEnter"
|
||||
@mouseleave="handleMouseLeave"
|
||||
>
|
||||
<div class="card-content">
|
||||
<div class="donor-avatar">
|
||||
<n-avatar
|
||||
:src="donor.avatar"
|
||||
:fallback-src="defaultAvatar"
|
||||
round
|
||||
size="large"
|
||||
class="animate__animated animate__pulse animate__infinite avatar-img"
|
||||
/>
|
||||
<div class="donor-badge" :class="getBadgeClass(donor.badge)">
|
||||
{{ donor.badge }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="donor-info">
|
||||
<div class="donor-name">{{ donor.name }}</div>
|
||||
<div class="donation-meta">
|
||||
<n-tag
|
||||
:type="getAmountTagType(donor.amount)"
|
||||
size="small"
|
||||
class="donation-amount animate__animated"
|
||||
round
|
||||
bordered
|
||||
>
|
||||
¥{{ donor.amount }}
|
||||
</n-tag>
|
||||
<span class="donation-date">{{ donor.date }}</span>
|
||||
</div>
|
||||
</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>
|
||||
</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="description text-center text-sm text-gray-700 dark:text-gray-200">
|
||||
<p>您的捐赠将用于支持开发和维护工作,包括但不限于服务器维护、域名续费等。</p>
|
||||
<p>留言时可留下您的邮箱或 github名称。</p>
|
||||
</div>
|
||||
<div class="flex justify-between">
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<n-image
|
||||
:src="alipay"
|
||||
alt="支付宝收款码"
|
||||
class="w-60 h-60 rounded-lg cursor-none"
|
||||
preview-disabled
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-200">支付宝</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-center gap-2">
|
||||
<n-image
|
||||
:src="wechat"
|
||||
alt="微信收款码"
|
||||
class="w-60 h-60 rounded-lg cursor-none"
|
||||
preview-disabled
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-200">微信支付</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import axios from 'axios';
|
||||
import { computed, onActivated, onMounted, ref } from 'vue';
|
||||
|
||||
import alipay from '@/assets/alipay.png';
|
||||
import wechat from '@/assets/wechat.png';
|
||||
|
||||
// 默认头像
|
||||
const defaultAvatar = 'https://avatars.githubusercontent.com/u/0?v=4';
|
||||
|
||||
// 捐赠者数据
|
||||
interface Donor {
|
||||
id: number;
|
||||
name: string;
|
||||
amount: number;
|
||||
date: string;
|
||||
message?: string;
|
||||
avatar?: string;
|
||||
badge: string;
|
||||
badgeColor: string;
|
||||
}
|
||||
|
||||
const donors = ref<Donor[]>([]);
|
||||
|
||||
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'
|
||||
);
|
||||
donors.value = response.data.map((donor: Donor, index: number) => ({
|
||||
...donor,
|
||||
avatar: `https://api.dicebear.com/7.x/micah/svg?seed=${index}`
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch donors:', error);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchDonors();
|
||||
});
|
||||
|
||||
onActivated(() => {
|
||||
fetchDonors();
|
||||
});
|
||||
|
||||
// 动画类名列表
|
||||
const animationClasses = [
|
||||
'animate__fadeInUp',
|
||||
'animate__fadeInLeft',
|
||||
'animate__fadeInRight',
|
||||
'animate__zoomIn'
|
||||
];
|
||||
|
||||
// 获取随机动画类名
|
||||
const getAnimationClass = (index: number) => {
|
||||
return animationClasses[index % animationClasses.length];
|
||||
};
|
||||
|
||||
// 根据金额获取标签类型
|
||||
const getAmountTagType = (amount: number): 'success' | 'warning' | 'error' | 'info' => {
|
||||
if (amount >= 5) return 'warning';
|
||||
if (amount >= 2) return 'success';
|
||||
return 'info';
|
||||
};
|
||||
|
||||
// 获取徽章样式类名
|
||||
const getBadgeClass = (badge: string): string => {
|
||||
if (badge.includes('金牌')) return 'badge-gold';
|
||||
if (badge.includes('银牌')) return 'badge-silver';
|
||||
return 'badge-bronze';
|
||||
};
|
||||
|
||||
// 鼠标悬停效果
|
||||
const handleMouseEnter = (event: MouseEvent) => {
|
||||
const card = event.currentTarget as HTMLElement;
|
||||
card.style.transform = 'translateY(-2px)';
|
||||
card.style.boxShadow = '0 8px 20px rgba(0, 0, 0, 0.12)';
|
||||
|
||||
// 添加金额标签动画
|
||||
const amountTag = card.querySelector('.donation-amount');
|
||||
if (amountTag) {
|
||||
amountTag.classList.add('animate__tada');
|
||||
}
|
||||
};
|
||||
|
||||
const handleMouseLeave = (event: MouseEvent) => {
|
||||
const card = event.currentTarget as HTMLElement;
|
||||
card.style.transform = 'translateY(0)';
|
||||
card.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.08)';
|
||||
|
||||
// 移除金额标签动画
|
||||
const amountTag = card.querySelector('.donation-amount');
|
||||
if (amountTag) {
|
||||
amountTag.classList.remove('animate__tada');
|
||||
}
|
||||
};
|
||||
|
||||
// 按金额和留言排序的捐赠列表
|
||||
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;
|
||||
|
||||
// 金额相同时,按日期从新到旧排序
|
||||
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>
|
||||
.donation-container {
|
||||
@apply w-full overflow-hidden;
|
||||
}
|
||||
|
||||
.donation-grid {
|
||||
@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 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 {
|
||||
.donor-avatar {
|
||||
@apply scale-105 rotate-3;
|
||||
}
|
||||
|
||||
.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 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 8s ease infinite;
|
||||
}
|
||||
|
||||
@keyframes sparkle {
|
||||
0%,
|
||||
100% {
|
||||
@apply bg-[0%_0%] opacity-40 scale-100;
|
||||
}
|
||||
50% {
|
||||
@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>
|
||||
590
src/renderer/components/common/DownloadDrawer.vue
Normal file
590
src/renderer/components/common/DownloadDrawer.vue
Normal 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>
|
||||
@@ -39,10 +39,12 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
|
||||
import { isElectron, isMobile } from '@/utils';
|
||||
import config from '../../../../package.json';
|
||||
import { getLatestReleaseInfo } from '@/utils/update';
|
||||
|
||||
import config from '../../../../package.json';
|
||||
|
||||
const showModal = ref(false);
|
||||
const noPrompt = ref(false);
|
||||
const releaseInfo = ref<any>(null);
|
||||
@@ -77,36 +79,33 @@ const handleInstall = async (): Promise<void> => {
|
||||
const isMac = userAgent.toLowerCase().includes('mac');
|
||||
const isWindows = userAgent.toLowerCase().includes('win');
|
||||
const isLinux = userAgent.toLowerCase().includes('linux');
|
||||
const isX64 = userAgent.includes('x86_64') ||
|
||||
userAgent.includes('Win64') ||
|
||||
userAgent.includes('WOW64');
|
||||
const isX64 =
|
||||
userAgent.includes('x86_64') || userAgent.includes('Win64') || userAgent.includes('WOW64');
|
||||
|
||||
let downloadUrl = '';
|
||||
|
||||
// 根据平台和架构选择对应的安装包
|
||||
if (isMac) {
|
||||
// macOS
|
||||
const macAsset = assets.find(asset =>
|
||||
asset.name.includes('mac')
|
||||
);
|
||||
const macAsset = assets.find((asset) => asset.name.includes('mac'));
|
||||
downloadUrl = macAsset?.browser_download_url || '';
|
||||
} else if (isWindows) {
|
||||
// Windows
|
||||
let winAsset = assets.find(asset =>
|
||||
asset.name.includes('win') &&
|
||||
(isX64 ? asset.name.includes('x64') : asset.name.includes('ia32'))
|
||||
let winAsset = assets.find(
|
||||
(asset) =>
|
||||
asset.name.includes('win') &&
|
||||
(isX64 ? asset.name.includes('x64') : asset.name.includes('ia32'))
|
||||
);
|
||||
if(!winAsset){
|
||||
winAsset = assets.find(asset =>
|
||||
asset.name.includes('win.exe')
|
||||
);
|
||||
if (!winAsset) {
|
||||
winAsset = assets.find((asset) => asset.name.includes('win.exe'));
|
||||
}
|
||||
downloadUrl = winAsset?.browser_download_url || '';
|
||||
} else if (isLinux) {
|
||||
// Linux
|
||||
const linuxAsset = assets.find(asset =>
|
||||
(asset.name.endsWith('.AppImage') || asset.name.endsWith('.deb')) &&
|
||||
asset.name.includes('x64')
|
||||
const linuxAsset = assets.find(
|
||||
(asset) =>
|
||||
(asset.name.endsWith('.AppImage') || asset.name.endsWith('.deb')) &&
|
||||
asset.name.includes('x64')
|
||||
);
|
||||
downloadUrl = linuxAsset?.browser_download_url || '';
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import { setAnimationClass } from '@/utils';
|
||||
|
||||
const props = defineProps({
|
||||
showPop: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
showClose: {
|
||||
type: Boolean,
|
||||
default: true
|
||||
}
|
||||
});
|
||||
|
||||
const musicFullClass = computed(() => {
|
||||
if (props.showPop) {
|
||||
return setAnimationClass('animate__fadeInUp');
|
||||
}
|
||||
return setAnimationClass('animate__fadeOutDown');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-show="props.showPop" class="pop-page" :class="musicFullClass">
|
||||
<i v-if="props.showClose" class="iconfont icon-icon_error close"></i>
|
||||
<img src="http://code.myalger.top/2000*2000.jpg,f054f0,0f2255" />
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.pop-page {
|
||||
height: 800px;
|
||||
@apply absolute top-4 left-0 w-full;
|
||||
background-color: #000000f0;
|
||||
.close {
|
||||
@apply absolute top-4 right-4 cursor-pointer text-white text-3xl;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
355
src/renderer/components/common/PlaylistDrawer.vue
Normal file
355
src/renderer/components/common/PlaylistDrawer.vue
Normal file
@@ -0,0 +1,355 @@
|
||||
<template>
|
||||
<n-drawer
|
||||
:show="modelValue"
|
||||
:width="400"
|
||||
placement="right"
|
||||
@update:show="$emit('update:modelValue', $event)"
|
||||
>
|
||||
<n-drawer-content title="添加到歌单" class="mac-style-drawer">
|
||||
<n-scrollbar class="h-full">
|
||||
<div class="playlist-drawer">
|
||||
<!-- 创建新歌单按钮和表单 -->
|
||||
<div class="create-playlist-section">
|
||||
<div
|
||||
class="create-playlist-button"
|
||||
:class="{ 'is-expanded': isCreating }"
|
||||
@click="toggleCreateForm"
|
||||
>
|
||||
<div class="create-playlist-icon">
|
||||
<i class="iconfont" :class="isCreating ? 'ri-close-line' : 'ri-add-line'"></i>
|
||||
</div>
|
||||
<div class="create-playlist-text">{{ isCreating ? '取消创建' : '创建新歌单' }}</div>
|
||||
</div>
|
||||
|
||||
<!-- 创建歌单表单 -->
|
||||
<div class="create-playlist-form" :class="{ 'is-visible': isCreating }">
|
||||
<n-input
|
||||
v-model:value="formValue.name"
|
||||
placeholder="歌单名称"
|
||||
maxlength="40"
|
||||
class="mac-style-input"
|
||||
:status="inputError ? 'error' : undefined"
|
||||
>
|
||||
<template #prefix>
|
||||
<i class="iconfont ri-music-2-line"></i>
|
||||
</template>
|
||||
</n-input>
|
||||
<div class="privacy-switch">
|
||||
<div class="privacy-label">
|
||||
<i
|
||||
class="iconfont"
|
||||
:class="formValue.privacy ? 'ri-lock-line' : 'ri-earth-line'"
|
||||
></i>
|
||||
<span>{{ formValue.privacy ? '私密歌单' : '公开歌单' }}</span>
|
||||
</div>
|
||||
<n-switch v-model:value="formValue.privacy" class="mac-style-switch">
|
||||
<template #checked>私密</template>
|
||||
<template #unchecked>公开</template>
|
||||
</n-switch>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<n-button
|
||||
type="primary"
|
||||
quaternary
|
||||
class="mac-style-button"
|
||||
:loading="creating"
|
||||
:disabled="!formValue.name"
|
||||
@click="handleCreatePlaylist"
|
||||
>
|
||||
创建歌单
|
||||
</n-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 歌单列表 -->
|
||||
<div class="playlist-list">
|
||||
<div
|
||||
v-for="playlist in playlists"
|
||||
:key="playlist.id"
|
||||
class="playlist-item"
|
||||
@click="handleAddToPlaylist(playlist)"
|
||||
>
|
||||
<n-image
|
||||
:src="getImgUrl(playlist.coverImgUrl || playlist.picUrl, '100y100')"
|
||||
class="playlist-item-img"
|
||||
preview-disabled
|
||||
:img-props="{
|
||||
crossorigin: 'anonymous'
|
||||
}"
|
||||
/>
|
||||
<div class="playlist-item-info">
|
||||
<div class="playlist-item-name">{{ playlist.name }}</div>
|
||||
<div class="playlist-item-count">{{ playlist.trackCount }}首歌曲</div>
|
||||
</div>
|
||||
<div class="playlist-item-action">
|
||||
<i class="iconfont ri-add-line"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-scrollbar>
|
||||
</n-drawer-content>
|
||||
</n-drawer>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { createPlaylist, updatePlaylistTracks } from '@/api/music';
|
||||
import { getUserPlaylist } from '@/api/user';
|
||||
import { getImgUrl } from '@/utils';
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
songId?: number;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits(['update:modelValue']);
|
||||
|
||||
const message = useMessage();
|
||||
const playlists = ref<any[]>([]);
|
||||
const creating = ref(false);
|
||||
const store = useStore();
|
||||
const isCreating = ref(false);
|
||||
|
||||
const formValue = ref({
|
||||
name: '',
|
||||
privacy: false
|
||||
});
|
||||
|
||||
const inputError = computed(() => {
|
||||
return isCreating.value && !formValue.value.name;
|
||||
});
|
||||
|
||||
const toggleCreateForm = () => {
|
||||
if (creating.value) return;
|
||||
isCreating.value = !isCreating.value;
|
||||
if (!isCreating.value) {
|
||||
formValue.value.name = '';
|
||||
formValue.value.privacy = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 获取用户歌单
|
||||
const fetchUserPlaylists = async () => {
|
||||
try {
|
||||
const { user } = store.state;
|
||||
if (!user?.userId) {
|
||||
message.error('请先登录');
|
||||
emit('update:modelValue', false);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await getUserPlaylist(user.userId);
|
||||
if (res.data?.playlist) {
|
||||
playlists.value = res.data.playlist;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取歌单失败:', error);
|
||||
message.error('获取歌单失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 添加到歌单
|
||||
const handleAddToPlaylist = async (playlist: any) => {
|
||||
if (!props.songId) return;
|
||||
try {
|
||||
const res = await updatePlaylistTracks({
|
||||
op: 'add',
|
||||
pid: playlist.id,
|
||||
tracks: props.songId.toString()
|
||||
});
|
||||
console.log('res.data', res.data);
|
||||
|
||||
if (res.status === 200) {
|
||||
message.success('添加成功');
|
||||
emit('update:modelValue', false);
|
||||
} else {
|
||||
throw new Error(res.data?.msg || '添加失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('添加到歌单失败:', error);
|
||||
message.error(error.message || '添加到歌单失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 创建歌单
|
||||
const handleCreatePlaylist = async () => {
|
||||
if (!formValue.value.name) {
|
||||
message.error('请输入歌单名称');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
creating.value = true;
|
||||
|
||||
const res = await createPlaylist({
|
||||
name: formValue.value.name,
|
||||
privacy: formValue.value.privacy ? 10 : 0
|
||||
});
|
||||
|
||||
if (res.data?.id) {
|
||||
message.success('创建成功');
|
||||
isCreating.value = false;
|
||||
formValue.value.name = '';
|
||||
formValue.value.privacy = false;
|
||||
await fetchUserPlaylists();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('创建歌单失败:', error);
|
||||
message.error('创建歌单失败');
|
||||
} finally {
|
||||
creating.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 监听显示状态变化
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(newVal) => {
|
||||
if (newVal) {
|
||||
fetchUserPlaylists();
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.mac-style-drawer {
|
||||
@apply h-full;
|
||||
|
||||
:deep(.n-drawer-header__main) {
|
||||
@apply text-base font-medium;
|
||||
}
|
||||
|
||||
:deep(.n-drawer-content) {
|
||||
@apply h-full;
|
||||
}
|
||||
|
||||
:deep(.n-drawer-content-wrapper) {
|
||||
@apply h-full;
|
||||
}
|
||||
|
||||
:deep(.n-scrollbar-rail) {
|
||||
@apply right-0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.playlist-drawer {
|
||||
@apply flex flex-col gap-6;
|
||||
}
|
||||
|
||||
.create-playlist-section {
|
||||
@apply flex flex-col;
|
||||
}
|
||||
|
||||
.create-playlist-button {
|
||||
@apply flex items-center gap-4 p-3 rounded-xl cursor-pointer transition-all duration-200
|
||||
bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700;
|
||||
|
||||
&.is-expanded {
|
||||
@apply bg-gray-100 dark:bg-gray-700;
|
||||
|
||||
.create-playlist-icon {
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
}
|
||||
|
||||
&-icon {
|
||||
@apply w-10 h-10 rounded-xl bg-green-500 flex items-center justify-center text-white
|
||||
transition-all duration-300;
|
||||
|
||||
.iconfont {
|
||||
@apply text-xl transition-transform duration-300;
|
||||
}
|
||||
}
|
||||
|
||||
&-text {
|
||||
@apply text-sm font-medium transition-colors duration-300;
|
||||
}
|
||||
}
|
||||
|
||||
.create-playlist-form {
|
||||
@apply max-h-0 overflow-hidden transition-all duration-300 ease-in-out opacity-0;
|
||||
|
||||
&.is-visible {
|
||||
@apply max-h-[200px] mt-4 opacity-100;
|
||||
}
|
||||
|
||||
.mac-style-input {
|
||||
@apply rounded-lg;
|
||||
:deep(.n-input-wrapper) {
|
||||
@apply bg-gray-50 dark:bg-gray-800 border-0;
|
||||
}
|
||||
:deep(.n-input__input) {
|
||||
@apply text-sm;
|
||||
}
|
||||
:deep(.n-input__prefix) {
|
||||
@apply text-gray-400;
|
||||
}
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
@apply mt-4;
|
||||
.mac-style-button {
|
||||
@apply w-full rounded-lg text-sm py-2 bg-green-500 hover:bg-green-600 text-white;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.privacy-switch {
|
||||
@apply flex items-center justify-between mt-4 px-2;
|
||||
|
||||
.privacy-label {
|
||||
@apply flex items-center gap-2;
|
||||
|
||||
.iconfont {
|
||||
@apply text-base text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
span {
|
||||
@apply text-sm;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.n-switch) {
|
||||
@apply h-5 min-w-[40px];
|
||||
}
|
||||
}
|
||||
|
||||
.playlist-list {
|
||||
@apply flex flex-col gap-2;
|
||||
}
|
||||
|
||||
.playlist-item {
|
||||
@apply flex items-center gap-3 p-2 rounded-xl cursor-pointer transition-all duration-200
|
||||
hover:bg-gray-50 dark:hover:bg-gray-800;
|
||||
|
||||
&-img {
|
||||
@apply w-10 h-10 rounded-xl;
|
||||
}
|
||||
|
||||
&-info {
|
||||
@apply flex-1 min-w-0;
|
||||
}
|
||||
|
||||
&-name {
|
||||
@apply text-sm font-medium truncate;
|
||||
}
|
||||
|
||||
&-count {
|
||||
@apply text-xs text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
|
||||
&-action {
|
||||
@apply w-8 h-8 rounded-lg flex items-center justify-center
|
||||
text-gray-400 hover:text-green-500 transition-colors duration-200;
|
||||
|
||||
.iconfont {
|
||||
@apply text-xl;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,8 +1,9 @@
|
||||
<template>
|
||||
<div class="search-item" :class="item.type" @click="handleClick">
|
||||
<div class="search-item" :class="[item.type, shape]" @click="handleClick">
|
||||
<div class="search-item-img">
|
||||
<n-image
|
||||
:src="getImgUrl(item.picUrl, item.type === 'mv' ? '320y180' : '100y100')"
|
||||
class="w-full h-full"
|
||||
:src="getImgUrl(item.picUrl, item.type === 'mv' ? '320y180' : '200y200')"
|
||||
lazy
|
||||
preview-disabled
|
||||
/>
|
||||
@@ -15,13 +16,19 @@
|
||||
<p class="search-item-artist">{{ item.desc }}</p>
|
||||
</div>
|
||||
|
||||
<MusicList
|
||||
<div v-if="item.type === '专辑'" class="search-item-size">
|
||||
<i class="ri-music-2-line"></i>
|
||||
<span>{{ item.size }}</span>
|
||||
</div>
|
||||
|
||||
<music-list
|
||||
v-if="['专辑', 'playlist'].includes(item.type)"
|
||||
v-model:show="showPop"
|
||||
:name="item.name"
|
||||
:song-list="songList"
|
||||
:list-info="listInfo"
|
||||
:cover="false"
|
||||
:z-index="zIndex"
|
||||
/>
|
||||
<mv-player
|
||||
v-if="item.type === 'mv'"
|
||||
@@ -40,17 +47,25 @@ import MvPlayer from '@/components/MvPlayer.vue';
|
||||
import { audioService } from '@/services/audioService';
|
||||
import { IMvItem } from '@/type/mv';
|
||||
import { getImgUrl } from '@/utils';
|
||||
|
||||
import MusicList from '../MusicList.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
item: {
|
||||
picUrl: string;
|
||||
name: string;
|
||||
desc: string;
|
||||
type: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
}>();
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
shape?: 'square' | 'rectangle';
|
||||
zIndex?: number;
|
||||
item: {
|
||||
picUrl: string;
|
||||
name: string;
|
||||
desc: string;
|
||||
type: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
}>(),
|
||||
{
|
||||
shape: 'rectangle'
|
||||
}
|
||||
);
|
||||
|
||||
const songList = ref<any[]>([]);
|
||||
|
||||
@@ -103,11 +118,45 @@ const handleClick = async () => {
|
||||
|
||||
<style scoped lang="scss">
|
||||
.search-item {
|
||||
@apply rounded-3xl p-3 flex items-center hover:bg-light-200 dark:hover:bg-gray-800 transition cursor-pointer;
|
||||
margin: 0 10px;
|
||||
.search-item-img {
|
||||
@apply w-12 h-12 mr-4 rounded-2xl overflow-hidden;
|
||||
@apply rounded-lg p-0 flex items-center hover:bg-transparent transition cursor-pointer border-none;
|
||||
|
||||
&.square {
|
||||
@apply flex-col relative;
|
||||
|
||||
.search-item-img {
|
||||
@apply w-full aspect-square mb-2 mr-0 rounded-lg overflow-hidden hover:shadow-xl transition-all duration-300 shadow-sm shadow-black/20 dark:shadow-white/20;
|
||||
img {
|
||||
@apply object-cover w-full h-full transition-transform duration-500;
|
||||
}
|
||||
}
|
||||
|
||||
.search-item-info {
|
||||
@apply w-full text-left px-0;
|
||||
|
||||
.search-item-name {
|
||||
@apply truncate mb-1 font-medium text-base text-gray-800 dark:text-gray-200;
|
||||
}
|
||||
|
||||
.search-item-artist {
|
||||
@apply truncate text-sm text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
}
|
||||
|
||||
.search-item-size {
|
||||
@apply absolute top-2 right-2 text-xs text-white px-2 py-1 rounded-full bg-black/30 backdrop-blur-sm;
|
||||
i {
|
||||
@apply text-xs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.rectangle {
|
||||
@apply hover:bg-light-200 dark:hover:bg-dark-200 p-3;
|
||||
.search-item-img {
|
||||
@apply w-12 h-12 mr-4 rounded-lg overflow-hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.search-item-info {
|
||||
@apply flex-1 overflow-hidden;
|
||||
&-name {
|
||||
@@ -137,4 +186,8 @@ const handleClick = async () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.search-item-size {
|
||||
@apply flex items-center gap-2 text-gray-400;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
<template>
|
||||
<div class="song-item" :class="{ 'song-mini': mini, 'song-list': list }" @contextmenu.prevent="handleContextMenu">
|
||||
<div
|
||||
class="song-item"
|
||||
:class="{ 'song-mini': mini, 'song-list': list }"
|
||||
@contextmenu.prevent="handleContextMenu"
|
||||
>
|
||||
<div v-if="selectable" class="song-item-select" @click.stop="toggleSelect">
|
||||
<n-checkbox :checked="selected" />
|
||||
</div>
|
||||
<n-image
|
||||
v-if="item.picUrl"
|
||||
ref="songImg"
|
||||
@@ -18,10 +25,14 @@
|
||||
}}</n-ellipsis>
|
||||
<div class="song-item-content-divider">-</div>
|
||||
<n-ellipsis class="song-item-content-name text-ellipsis" line-clamp="1">
|
||||
<span v-for="(artists, artistsindex) in item.ar || item.song.artists" :key="artistsindex"
|
||||
>{{ artists.name
|
||||
}}{{ artistsindex < (item.ar || item.song.artists).length - 1 ? ' / ' : '' }}</span
|
||||
>
|
||||
<template v-for="(artist, index) in artists" :key="index">
|
||||
<span
|
||||
class="cursor-pointer hover:text-green-500"
|
||||
@click.stop="handleArtistClick(artist.id)"
|
||||
>{{ artist.name }}</span
|
||||
>
|
||||
<span v-if="index < artists.length - 1"> / </span>
|
||||
</template>
|
||||
</n-ellipsis>
|
||||
</div>
|
||||
<template v-else>
|
||||
@@ -30,12 +41,14 @@
|
||||
</div>
|
||||
<div class="song-item-content-name">
|
||||
<n-ellipsis class="text-ellipsis" line-clamp="1">
|
||||
<span
|
||||
v-for="(artists, artistsindex) in item.ar || item.song.artists"
|
||||
:key="artistsindex"
|
||||
>{{ artists.name
|
||||
}}{{ artistsindex < (item.ar || item.song.artists).length - 1 ? ' / ' : '' }}</span
|
||||
>
|
||||
<template v-for="(artist, index) in artists" :key="index">
|
||||
<span
|
||||
class="cursor-pointer hover:text-green-500"
|
||||
@click.stop="handleArtistClick(artist.id)"
|
||||
>{{ artist.name }}</span
|
||||
>
|
||||
<span v-if="index < artists.length - 1"> / </span>
|
||||
</template>
|
||||
</n-ellipsis>
|
||||
</div>
|
||||
</template>
|
||||
@@ -60,9 +73,10 @@
|
||||
<n-dropdown
|
||||
v-if="isElectron"
|
||||
:show="showDropdown"
|
||||
:options="dropdownOptions"
|
||||
:x="dropdownX"
|
||||
:y="dropdownY"
|
||||
:options="dropdownOptions"
|
||||
:z-index="99999"
|
||||
placement="bottom-start"
|
||||
@clickoutside="showDropdown = false"
|
||||
@select="handleSelect"
|
||||
@@ -71,17 +85,17 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, h, ref, useTemplateRef } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import type { MenuOption } from 'naive-ui';
|
||||
import { NImage, NText, useMessage } from 'naive-ui';
|
||||
import { computed, h, inject, ref, useTemplateRef } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { getSongUrl } from '@/hooks/MusicListHook';
|
||||
import { audioService } from '@/services/audioService';
|
||||
import type { SongResult } from '@/type/music';
|
||||
import { getImgUrl, isElectron } from '@/utils';
|
||||
import { getImageBackground } from '@/utils/linearColor';
|
||||
import { getSongUrl } from '@/hooks/MusicListHook';
|
||||
import { cloneDeep } from 'lodash';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -89,11 +103,17 @@ const props = withDefaults(
|
||||
mini?: boolean;
|
||||
list?: boolean;
|
||||
favorite?: boolean;
|
||||
selectable?: boolean;
|
||||
selected?: boolean;
|
||||
canRemove?: boolean;
|
||||
}>(),
|
||||
{
|
||||
mini: false,
|
||||
list: false,
|
||||
favorite: true
|
||||
favorite: true,
|
||||
selectable: false,
|
||||
selected: false,
|
||||
canRemove: false
|
||||
}
|
||||
);
|
||||
|
||||
@@ -115,14 +135,109 @@ const dropdownY = ref(0);
|
||||
|
||||
const isDownloading = ref(false);
|
||||
|
||||
const dropdownOptions = computed<MenuOption[]>(() => [
|
||||
{
|
||||
label: isDownloading.value ? '下载中...' : '下载 ' + props.item.name,
|
||||
key: 'download',
|
||||
icon: () => h('i', { class: 'iconfont ri-download-line' }),
|
||||
disabled: isDownloading.value
|
||||
const openPlaylistDrawer = inject<(songId: number) => void>('openPlaylistDrawer');
|
||||
|
||||
const renderSongPreview = () => {
|
||||
return h(
|
||||
'div',
|
||||
{
|
||||
class: 'flex items-center gap-3 px-2 py-1 dark:border-gray-800'
|
||||
},
|
||||
[
|
||||
h(NImage, {
|
||||
src: getImgUrl(props.item.picUrl || props.item.al?.picUrl, '100y100'),
|
||||
class: 'w-10 h-10 rounded-lg flex-shrink-0',
|
||||
previewDisabled: true,
|
||||
imgProps: {
|
||||
crossorigin: 'anonymous'
|
||||
}
|
||||
}),
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
class: 'flex-1 min-w-0 py-1'
|
||||
},
|
||||
[
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
class: 'mb-1'
|
||||
},
|
||||
[
|
||||
h(
|
||||
NText,
|
||||
{
|
||||
depth: 1,
|
||||
class: 'text-sm font-medium'
|
||||
},
|
||||
{
|
||||
default: () => props.item.name
|
||||
}
|
||||
)
|
||||
]
|
||||
)
|
||||
]
|
||||
)
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
const dropdownOptions = computed<MenuOption[]>(() => {
|
||||
const options: MenuOption[] = [
|
||||
{
|
||||
key: 'header',
|
||||
type: 'render',
|
||||
render: renderSongPreview
|
||||
},
|
||||
{
|
||||
key: 'divider1',
|
||||
type: 'divider'
|
||||
},
|
||||
{
|
||||
label: '播放',
|
||||
key: 'play',
|
||||
icon: () => h('i', { class: 'iconfont ri-play-circle-line' })
|
||||
},
|
||||
{
|
||||
label: '下一首播放',
|
||||
key: 'playNext',
|
||||
icon: () => h('i', { class: 'iconfont ri-play-list-2-line' })
|
||||
},
|
||||
{
|
||||
type: 'divider',
|
||||
key: 'd1'
|
||||
},
|
||||
{
|
||||
label: '添加到歌单',
|
||||
key: 'addToPlaylist',
|
||||
icon: () => h('i', { class: 'iconfont ri-folder-add-line' })
|
||||
},
|
||||
{
|
||||
label: isFavorite.value ? '取消喜欢' : '喜欢',
|
||||
key: 'favorite',
|
||||
icon: () =>
|
||||
h('i', {
|
||||
class: `iconfont ${isFavorite.value ? 'ri-heart-fill text-red-500' : 'ri-heart-line'}`
|
||||
})
|
||||
}
|
||||
];
|
||||
|
||||
if (props.canRemove) {
|
||||
options.push(
|
||||
{
|
||||
type: 'divider',
|
||||
key: 'd2'
|
||||
},
|
||||
{
|
||||
label: '从歌单中删除',
|
||||
key: 'remove',
|
||||
icon: () => h('i', { class: 'iconfont ri-delete-bin-line' })
|
||||
}
|
||||
);
|
||||
}
|
||||
]);
|
||||
|
||||
return options;
|
||||
});
|
||||
|
||||
const handleContextMenu = (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -135,6 +250,16 @@ const handleSelect = (key: string | number) => {
|
||||
showDropdown.value = false;
|
||||
if (key === 'download') {
|
||||
downloadMusic();
|
||||
} else if (key === 'playNext') {
|
||||
handlePlayNext();
|
||||
} else if (key === 'addToPlaylist') {
|
||||
openPlaylistDrawer?.(props.item.id);
|
||||
} else if (key === 'favorite') {
|
||||
toggleFavorite(new Event('click'));
|
||||
} else if (key === 'play') {
|
||||
playMusicEvent(props.item);
|
||||
} else if (key === 'remove') {
|
||||
emits('remove-song', props.item.id);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -147,47 +272,65 @@ 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 || '下载失败');
|
||||
}
|
||||
};
|
||||
|
||||
const emits = defineEmits(['play']);
|
||||
const emits = defineEmits(['play', 'select', 'remove-song']);
|
||||
const songImageRef = useTemplateRef('songImg');
|
||||
|
||||
const imageLoad = async () => {
|
||||
@@ -232,6 +375,26 @@ const toggleFavorite = async (e: Event) => {
|
||||
store.commit('addToFavorite', props.item.id);
|
||||
}
|
||||
};
|
||||
|
||||
// 切换选择状态
|
||||
const toggleSelect = () => {
|
||||
emits('select', props.item.id, !props.selected);
|
||||
};
|
||||
|
||||
const handleArtistClick = (id: number) => {
|
||||
store.commit('setCurrentArtistId', id);
|
||||
};
|
||||
|
||||
// 获取歌手列表(最多显示5个)
|
||||
const artists = computed(() => {
|
||||
return (props.item.ar || props.item.song?.artists)?.slice(0, 4) || [];
|
||||
});
|
||||
|
||||
// 添加到下一首播放
|
||||
const handlePlayNext = () => {
|
||||
store.commit('addToNextPlay', props.item);
|
||||
message.success('已添加到下一首播放');
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -279,11 +442,11 @@ const toggleFavorite = async (e: Event) => {
|
||||
}
|
||||
|
||||
&-like {
|
||||
@apply mr-2 cursor-pointer ml-4;
|
||||
@apply mr-2 cursor-pointer ml-4 transition-all;
|
||||
}
|
||||
|
||||
.like-active {
|
||||
@apply text-red-500;
|
||||
@apply text-red-500 dark:text-red-500;
|
||||
}
|
||||
|
||||
&-play {
|
||||
@@ -298,12 +461,16 @@ const toggleFavorite = async (e: Event) => {
|
||||
|
||||
&-download {
|
||||
@apply mr-2 cursor-pointer;
|
||||
|
||||
|
||||
.iconfont {
|
||||
@apply text-xl transition text-gray-500 dark:text-gray-400 hover:text-green-500;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&-select {
|
||||
@apply mr-3 cursor-pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.song-mini {
|
||||
@@ -397,4 +564,56 @@ const toggleFavorite = async (e: Event) => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.n-dropdown-menu) {
|
||||
@apply min-w-[240px] overflow-hidden rounded-lg border dark:border-gray-800;
|
||||
|
||||
.n-dropdown-option {
|
||||
@apply h-9 text-sm;
|
||||
|
||||
&:hover {
|
||||
@apply bg-gray-100 dark:bg-gray-800;
|
||||
}
|
||||
|
||||
.n-dropdown-option-body {
|
||||
@apply h-full;
|
||||
|
||||
.n-dropdown-option-body__prefix {
|
||||
@apply w-8 flex justify-center items-center;
|
||||
|
||||
.iconfont {
|
||||
@apply text-base;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.n-dropdown-divider {
|
||||
@apply my-1;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.song-preview) {
|
||||
@apply flex items-center gap-3 p-3 border-b dark:border-gray-800;
|
||||
|
||||
.n-image {
|
||||
@apply w-12 h-12 rounded-lg flex-shrink-0;
|
||||
}
|
||||
|
||||
.song-preview-info {
|
||||
@apply flex-1 min-w-0 py-1;
|
||||
|
||||
.song-preview-name {
|
||||
@apply text-sm font-medium truncate mb-1;
|
||||
}
|
||||
|
||||
.song-preview-artist {
|
||||
@apply text-xs text-gray-500 dark:text-gray-400 truncate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.n-dropdown-option-body--render) {
|
||||
@apply p-0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
v-model:show="showModal"
|
||||
preset="dialog"
|
||||
:show-icon="false"
|
||||
:mask-closable="true"
|
||||
:mask-closable="!downloading"
|
||||
:closable="!downloading"
|
||||
class="update-app-modal"
|
||||
style="width: 800px; max-width: 90vw"
|
||||
>
|
||||
@@ -15,7 +16,6 @@
|
||||
<div class="app-info">
|
||||
<h2 class="app-name">发现新版本 {{ updateInfo.latestVersion }}</h2>
|
||||
<p class="app-desc mb-2">当前版本 {{ updateInfo.currentVersion }}</p>
|
||||
<n-checkbox v-model:checked="noPrompt">不再提示</n-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
<div class="update-info">
|
||||
@@ -23,11 +23,35 @@
|
||||
<div class="update-body" v-html="parsedReleaseNotes"></div>
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<n-button class="cancel-btn" @click="closeModal">暂不更新</n-button>
|
||||
<n-button type="primary" class="update-btn" @click="handleUpdate">立即更新</n-button>
|
||||
<div v-if="downloading" class="download-status mt-6">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span class="text-sm text-gray-500">{{ downloadStatus }}</span>
|
||||
<span class="text-sm font-medium">{{ downloadProgress }}%</span>
|
||||
</div>
|
||||
<div class="progress-bar-wrapper">
|
||||
<div class="progress-bar" :style="{ width: `${downloadProgress}%` }"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-desc mt-4 text-center">
|
||||
<div class="modal-actions" :class="{ 'mt-6': !downloading }">
|
||||
<n-button
|
||||
class="cancel-btn"
|
||||
:disabled="downloading"
|
||||
:loading="downloading"
|
||||
@click="closeModal"
|
||||
>
|
||||
{{ '暂不更新' }}
|
||||
</n-button>
|
||||
<n-button
|
||||
type="primary"
|
||||
class="update-btn"
|
||||
:loading="downloading"
|
||||
:disabled="downloading"
|
||||
@click="handleUpdate"
|
||||
>
|
||||
{{ downloadBtnText }}
|
||||
</n-button>
|
||||
</div>
|
||||
<div v-if="!downloading" class="modal-desc mt-4 text-center">
|
||||
<p class="text-xs text-gray-400">
|
||||
下载遇到问题?去
|
||||
<a
|
||||
@@ -44,12 +68,14 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, computed, watch } from 'vue';
|
||||
import { marked } from 'marked';
|
||||
import { checkUpdate, UpdateResult } from '@/utils/update';
|
||||
import config from '../../../../package.json';
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { checkUpdate, UpdateResult } from '@/utils/update';
|
||||
|
||||
import config from '../../../../package.json';
|
||||
|
||||
// 配置 marked
|
||||
marked.setOptions({
|
||||
breaks: true, // 支持 GitHub 风格的换行
|
||||
@@ -57,7 +83,6 @@ marked.setOptions({
|
||||
});
|
||||
|
||||
const showModal = ref(false);
|
||||
const noPrompt = ref(false);
|
||||
const updateInfo = ref<UpdateResult>({
|
||||
hasUpdate: false,
|
||||
latestVersion: '',
|
||||
@@ -65,24 +90,27 @@ const updateInfo = ref<UpdateResult>({
|
||||
releaseInfo: null
|
||||
});
|
||||
|
||||
const store = useStore()
|
||||
const store = useStore();
|
||||
|
||||
// 添加计算属性
|
||||
const showUpdateModalState = computed({
|
||||
get: () => store.state.showUpdateModal,
|
||||
set: (val) => store.commit('setShowUpdateModal', val)
|
||||
})
|
||||
});
|
||||
|
||||
// 替换原来的 watch
|
||||
watch(showUpdateModalState, (newVal) => {
|
||||
if (newVal) {
|
||||
showModal.value = true
|
||||
showModal.value = true;
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
watch(() => showModal.value, (newVal) => {
|
||||
showUpdateModalState.value = newVal
|
||||
})
|
||||
watch(
|
||||
() => showModal.value,
|
||||
(newVal) => {
|
||||
showUpdateModalState.value = newVal;
|
||||
}
|
||||
);
|
||||
|
||||
// 解析 Markdown
|
||||
const parsedReleaseNotes = computed(() => {
|
||||
@@ -97,9 +125,6 @@ const parsedReleaseNotes = computed(() => {
|
||||
|
||||
const closeModal = () => {
|
||||
showModal.value = false;
|
||||
if (noPrompt.value) {
|
||||
localStorage.setItem('updatePromptDismissed', 'true');
|
||||
}
|
||||
};
|
||||
|
||||
const checkForUpdates = async () => {
|
||||
@@ -107,76 +132,111 @@ const checkForUpdates = async () => {
|
||||
const result = await checkUpdate(config.version);
|
||||
if (result) {
|
||||
updateInfo.value = result;
|
||||
if (localStorage.getItem('updatePromptDismissed') !== 'true') {
|
||||
showModal.value = true;
|
||||
}
|
||||
showModal.value = true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('检查更新失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const downloading = ref(false);
|
||||
const downloadProgress = ref(0);
|
||||
const downloadStatus = ref('准备下载...');
|
||||
const downloadBtnText = computed(() => {
|
||||
if (downloading.value) return '下载中...';
|
||||
return '立即更新';
|
||||
});
|
||||
|
||||
// 处理下载状态更新
|
||||
const handleDownloadProgress = (_event: any, progress: number, status: string) => {
|
||||
downloadProgress.value = progress;
|
||||
downloadStatus.value = status;
|
||||
};
|
||||
|
||||
// 处理下载完成
|
||||
const handleDownloadComplete = (_event: any, success: boolean, filePath: string) => {
|
||||
downloading.value = false;
|
||||
if (success) {
|
||||
window.electron.ipcRenderer.send('install-update', filePath);
|
||||
} else {
|
||||
window.$message.error('下载失败,请重试或手动下载');
|
||||
}
|
||||
};
|
||||
|
||||
// 监听下载事件
|
||||
onMounted(() => {
|
||||
checkForUpdates();
|
||||
window.electron.ipcRenderer.on('download-progress', handleDownloadProgress);
|
||||
window.electron.ipcRenderer.on('download-complete', handleDownloadComplete);
|
||||
});
|
||||
|
||||
// 清理事件监听
|
||||
onUnmounted(() => {
|
||||
window.electron.ipcRenderer.removeListener('download-progress', handleDownloadProgress);
|
||||
window.electron.ipcRenderer.removeListener('download-complete', handleDownloadComplete);
|
||||
});
|
||||
|
||||
const handleUpdate = async () => {
|
||||
|
||||
const assets = updateInfo.value.releaseInfo?.assets || [];
|
||||
const platform = window.electron.process.platform;
|
||||
const { platform } = window.electron.process;
|
||||
const arch = window.electron.ipcRenderer.sendSync('get-arch');
|
||||
console.log('arch',arch)
|
||||
console.log('platform',platform)
|
||||
const version = updateInfo.value.latestVersion
|
||||
const version = updateInfo.value.latestVersion;
|
||||
const downUrls = {
|
||||
win32: {
|
||||
all: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-win.exe`,
|
||||
x64: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-win-x64.exe`,
|
||||
ia32: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-win-ia32.exe`,
|
||||
ia32: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-win-ia32.exe`
|
||||
},
|
||||
darwin: {
|
||||
all: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}AlgerMusicPlayer-${version}-mac-universal.dmg`,
|
||||
all: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}AlgerMusicPlayer-${version}-mac-universal.dmg`
|
||||
},
|
||||
linux: {
|
||||
AppImage: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-linux-x64.AppImage`,
|
||||
deb: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-linux-x64.deb`,
|
||||
deb: `https://github.com/algerkong/AlgerMusicPlayer/releases/download/v${version}/AlgerMusicPlayer-${version}-linux-x64.deb`
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let downloadUrl = '';
|
||||
|
||||
// 根据平台和架构选择对应的安装包
|
||||
if (platform === 'darwin') {
|
||||
// macOS
|
||||
const macAsset = assets.find(asset =>
|
||||
asset.name.includes('mac')
|
||||
);
|
||||
const macAsset = assets.find((asset) => asset.name.includes('mac'));
|
||||
downloadUrl = macAsset?.browser_download_url || downUrls.darwin.all || '';
|
||||
} else if (platform === 'win32') {
|
||||
// Windows
|
||||
const winAsset = assets.find(asset =>
|
||||
asset.name.includes('win') &&
|
||||
(arch === 'x64' ? asset.name.includes('x64') : asset.name.includes('ia32'))
|
||||
const winAsset = assets.find(
|
||||
(asset) =>
|
||||
asset.name.includes('win') &&
|
||||
(arch === 'x64' ? asset.name.includes('x64') : asset.name.includes('ia32'))
|
||||
);
|
||||
downloadUrl = winAsset?.browser_download_url || downUrls.win32[arch] || downUrls.win32.all || '';
|
||||
downloadUrl =
|
||||
winAsset?.browser_download_url || downUrls.win32[arch] || downUrls.win32.all || '';
|
||||
} else if (platform === 'linux') {
|
||||
// Linux
|
||||
const linuxAsset = assets.find(asset =>
|
||||
(asset.name.endsWith('.AppImage') || asset.name.endsWith('.deb')) &&
|
||||
asset.name.includes('x64')
|
||||
const linuxAsset = assets.find(
|
||||
(asset) =>
|
||||
(asset.name.endsWith('.AppImage') || asset.name.endsWith('.deb')) &&
|
||||
asset.name.includes('x64')
|
||||
);
|
||||
downloadUrl = linuxAsset?.browser_download_url || downUrls.linux[arch] || '';
|
||||
}
|
||||
|
||||
if (downloadUrl) {
|
||||
window.open(`https://www.ghproxy.cn/${downloadUrl}`, '_blank');
|
||||
try {
|
||||
downloading.value = true;
|
||||
downloadStatus.value = '准备下载...';
|
||||
window.electron.ipcRenderer.send('start-download', downloadUrl);
|
||||
} catch (error) {
|
||||
downloading.value = false;
|
||||
window.$message.error('启动下载失败,请重试或手动下载');
|
||||
console.error('下载失败:', error);
|
||||
}
|
||||
} else {
|
||||
// 如果没有找到对应的安装包,跳转到 release 页面
|
||||
window.$message.error('未找到适合当前系统的安装包,请手动下载');
|
||||
window.open('https://github.com/algerkong/AlgerMusicPlayer/releases/latest', '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
checkForUpdates();
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -211,7 +271,7 @@ onMounted(() => {
|
||||
}
|
||||
.update-body {
|
||||
@apply p-4 pt-2 text-gray-600 dark:text-gray-300 rounded-lg overflow-hidden;
|
||||
|
||||
|
||||
:deep(h1) {
|
||||
@apply text-xl font-bold mb-3;
|
||||
}
|
||||
@@ -253,7 +313,8 @@ onMounted(() => {
|
||||
}
|
||||
:deep(table) {
|
||||
@apply w-full mb-3;
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
@apply px-3 py-2 border border-gray-200 dark:border-gray-600;
|
||||
}
|
||||
th {
|
||||
@@ -262,8 +323,18 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
}
|
||||
.download-status {
|
||||
@apply p-2;
|
||||
.progress-bar-wrapper {
|
||||
@apply w-full h-2 bg-gray-100 dark:bg-gray-700 rounded-full overflow-hidden;
|
||||
.progress-bar {
|
||||
@apply h-full bg-green-500 rounded-full transition-all duration-300 ease-out;
|
||||
box-shadow: 0 0 10px rgba(34, 197, 94, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
.modal-actions {
|
||||
@apply flex gap-4 mt-6;
|
||||
@apply flex gap-4;
|
||||
.n-button {
|
||||
@apply flex-1 text-base py-2;
|
||||
}
|
||||
@@ -272,14 +343,20 @@ onMounted(() => {
|
||||
&:hover {
|
||||
@apply bg-gray-700;
|
||||
}
|
||||
&:disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
}
|
||||
.update-btn {
|
||||
@apply bg-green-600 border-none;
|
||||
&:hover {
|
||||
@apply bg-green-500;
|
||||
}
|
||||
&:disabled {
|
||||
@apply opacity-50 cursor-not-allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
||||
192
src/renderer/components/lyric/LyricSettings.vue
Normal file
192
src/renderer/components/lyric/LyricSettings.vue
Normal file
@@ -0,0 +1,192 @@
|
||||
<template>
|
||||
<div class="settings-panel transparent-popover">
|
||||
<div class="settings-title">页面设置</div>
|
||||
<div class="settings-content">
|
||||
<div class="settings-item">
|
||||
<span>纯净模式</span>
|
||||
<n-switch v-model:value="config.pureModeEnabled" />
|
||||
</div>
|
||||
|
||||
<div class="settings-item">
|
||||
<span>隐藏封面</span>
|
||||
<n-switch v-model:value="config.hideCover" />
|
||||
</div>
|
||||
|
||||
<div class="settings-item">
|
||||
<span>居中显示</span>
|
||||
<n-switch v-model:value="config.centerLyrics" />
|
||||
</div>
|
||||
|
||||
<div class="settings-item">
|
||||
<span>显示翻译</span>
|
||||
<n-switch v-model:value="config.showTranslation" />
|
||||
</div>
|
||||
|
||||
<div class="settings-item">
|
||||
<span>隐藏播放栏</span>
|
||||
<n-switch v-model:value="config.hidePlayBar" />
|
||||
</div>
|
||||
|
||||
<div class="settings-slider">
|
||||
<span>字体大小</span>
|
||||
<n-slider
|
||||
v-model:value="config.fontSize"
|
||||
:step="1"
|
||||
:min="12"
|
||||
:max="32"
|
||||
:marks="{
|
||||
12: '小',
|
||||
22: '中',
|
||||
32: '大'
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="settings-slider">
|
||||
<span>文字间距</span>
|
||||
<n-slider
|
||||
v-model:value="config.letterSpacing"
|
||||
:step="0.2"
|
||||
:min="-2"
|
||||
:max="10"
|
||||
:marks="{
|
||||
'-2': '紧凑',
|
||||
0: '默认',
|
||||
10: '宽松'
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="settings-slider">
|
||||
<span>行高</span>
|
||||
<n-slider
|
||||
v-model:value="config.lineHeight"
|
||||
:step="0.1"
|
||||
:min="1"
|
||||
:max="3"
|
||||
:marks="{
|
||||
1: '紧凑',
|
||||
1.5: '默认',
|
||||
3: '宽松'
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="settings-item">
|
||||
<span>背景主题</span>
|
||||
<n-radio-group v-model:value="config.theme" name="theme">
|
||||
<n-radio value="default">默认</n-radio>
|
||||
<n-radio value="light">亮色</n-radio>
|
||||
<n-radio value="dark">暗色</n-radio>
|
||||
</n-radio-group>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
|
||||
interface LyricConfig {
|
||||
hideCover: boolean;
|
||||
centerLyrics: boolean;
|
||||
fontSize: number;
|
||||
letterSpacing: number;
|
||||
lineHeight: number;
|
||||
showTranslation: boolean;
|
||||
theme: 'default' | 'light' | 'dark';
|
||||
hidePlayBar: boolean;
|
||||
pureModeEnabled: boolean;
|
||||
}
|
||||
|
||||
const config = ref<LyricConfig>({
|
||||
hideCover: false,
|
||||
centerLyrics: false,
|
||||
fontSize: 22,
|
||||
letterSpacing: 0,
|
||||
lineHeight: 2,
|
||||
showTranslation: true,
|
||||
theme: 'default',
|
||||
hidePlayBar: false,
|
||||
pureModeEnabled: false
|
||||
});
|
||||
|
||||
const emit = defineEmits(['themeChange']);
|
||||
|
||||
// 监听配置变化并保存到本地存储
|
||||
watch(
|
||||
() => config.value,
|
||||
(newConfig) => {
|
||||
updateCSSVariables(newConfig);
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
// 监听主题变化
|
||||
watch(
|
||||
() => config.value.theme,
|
||||
(newTheme) => {
|
||||
emit('themeChange', newTheme);
|
||||
}
|
||||
);
|
||||
|
||||
// 更新 CSS 变量
|
||||
const updateCSSVariables = (config: LyricConfig) => {
|
||||
document.documentElement.style.setProperty('--lyric-font-size', `${config.fontSize}px`);
|
||||
document.documentElement.style.setProperty('--lyric-letter-spacing', `${config.letterSpacing}px`);
|
||||
document.documentElement.style.setProperty('--lyric-line-height', config.lineHeight.toString());
|
||||
};
|
||||
|
||||
// 加载保存的配置
|
||||
onMounted(() => {
|
||||
const savedConfig = localStorage.getItem('music-full-config');
|
||||
if (savedConfig) {
|
||||
config.value = { ...config.value, ...JSON.parse(savedConfig) };
|
||||
updateCSSVariables(config.value);
|
||||
}
|
||||
});
|
||||
|
||||
defineExpose({
|
||||
config
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.settings-panel {
|
||||
@apply p-4 w-72 rounded-lg relative overflow-hidden backdrop-blur-lg bg-black/10;
|
||||
.settings-title {
|
||||
@apply text-base font-bold mb-4;
|
||||
color: var(--text-color-active);
|
||||
}
|
||||
|
||||
.settings-content {
|
||||
@apply space-y-4;
|
||||
}
|
||||
|
||||
.settings-item {
|
||||
@apply flex items-center justify-between;
|
||||
span {
|
||||
@apply text-sm;
|
||||
color: var(--text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.settings-slider {
|
||||
@apply space-y-2;
|
||||
@apply mb-10 !important;
|
||||
span {
|
||||
@apply text-sm;
|
||||
color: var(--text-color-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 修改 slider 字体颜色
|
||||
:deep(.n-slider-mark) {
|
||||
color: var(--text-color-primary) !important;
|
||||
}
|
||||
// 修改 radio 字体颜色
|
||||
:deep(.n-radio__label) {
|
||||
color: var(--text-color-active) !important;
|
||||
}
|
||||
</style>
|
||||
380
src/renderer/components/settings/ShortcutSettings.vue
Normal file
380
src/renderer/components/settings/ShortcutSettings.vue
Normal file
@@ -0,0 +1,380 @@
|
||||
<template>
|
||||
<n-modal
|
||||
v-model:show="visible"
|
||||
preset="dialog"
|
||||
title="快捷键设置"
|
||||
:show-icon="false"
|
||||
style="width: 600px"
|
||||
@after-leave="handleAfterLeave"
|
||||
>
|
||||
<div class="shortcut-settings">
|
||||
<div class="shortcut-card">
|
||||
<div class="shortcut-content">
|
||||
<n-scrollbar>
|
||||
<n-space vertical>
|
||||
<div v-for="(shortcut, key) in tempShortcuts" :key="key" class="shortcut-item">
|
||||
<div class="shortcut-info">
|
||||
<span class="shortcut-label">{{ getShortcutLabel(key) }}</span>
|
||||
</div>
|
||||
<div class="shortcut-input">
|
||||
<n-input
|
||||
:value="formatShortcut(shortcut)"
|
||||
:status="duplicateKeys[key] ? 'error' : undefined"
|
||||
placeholder="点击输入快捷键"
|
||||
readonly
|
||||
@keydown="(e) => handleKeyDown(e, key)"
|
||||
@focus="() => startRecording(key)"
|
||||
@blur="stopRecording"
|
||||
/>
|
||||
<n-tooltip v-if="duplicateKeys[key]" trigger="hover">
|
||||
<template #trigger>
|
||||
<n-icon class="error-icon" size="18">
|
||||
<i class="ri-error-warning-line"></i>
|
||||
</n-icon>
|
||||
</template>
|
||||
快捷键冲突
|
||||
</n-tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</n-space>
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
|
||||
<div class="shortcut-footer">
|
||||
<n-space justify="end">
|
||||
<n-button size="small" @click="handleCancel">取消</n-button>
|
||||
<n-button size="small" @click="resetShortcuts">恢复默认</n-button>
|
||||
<n-button type="primary" size="small" :disabled="hasConflict" @click="handleSave">
|
||||
保存
|
||||
</n-button>
|
||||
</n-space>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-modal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { cloneDeep } from 'lodash';
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
|
||||
import { isElectron } from '@/utils';
|
||||
|
||||
interface Shortcuts {
|
||||
togglePlay: string;
|
||||
prevPlay: string;
|
||||
nextPlay: string;
|
||||
volumeUp: string;
|
||||
volumeDown: string;
|
||||
toggleFavorite: string;
|
||||
toggleWindow: string;
|
||||
}
|
||||
|
||||
const defaultShortcuts: Shortcuts = {
|
||||
togglePlay: 'CommandOrControl+Alt+P',
|
||||
prevPlay: 'Alt+Left',
|
||||
nextPlay: 'Alt+Right',
|
||||
volumeUp: 'Alt+Up',
|
||||
volumeDown: 'Alt+Down',
|
||||
toggleFavorite: 'CommandOrControl+Alt+L',
|
||||
toggleWindow: 'CommandOrControl+Alt+Shift+M'
|
||||
};
|
||||
|
||||
const shortcuts = ref<Shortcuts>(
|
||||
isElectron
|
||||
? window.electron.ipcRenderer.sendSync('get-store-value', 'shortcuts') || defaultShortcuts
|
||||
: { ...defaultShortcuts }
|
||||
);
|
||||
|
||||
// 临时存储编辑中的快捷键
|
||||
const tempShortcuts = ref<Shortcuts>({ ...shortcuts.value });
|
||||
|
||||
// 监听快捷键更新
|
||||
if (isElectron) {
|
||||
window.electron.ipcRenderer.on('shortcuts-updated', () => {
|
||||
const newShortcuts = window.electron.ipcRenderer.sendSync('get-store-value', 'shortcuts');
|
||||
if (newShortcuts) {
|
||||
shortcuts.value = newShortcuts;
|
||||
tempShortcuts.value = { ...newShortcuts };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 组件挂载时禁用快捷键
|
||||
onMounted(() => {
|
||||
if (isElectron) {
|
||||
// 禁用全局快捷键
|
||||
window.electron.ipcRenderer.send('disable-shortcuts');
|
||||
|
||||
const storedShortcuts = window.electron.ipcRenderer.sendSync('get-store-value', 'shortcuts');
|
||||
console.log('storedShortcuts', storedShortcuts);
|
||||
if (storedShortcuts) {
|
||||
shortcuts.value = storedShortcuts;
|
||||
tempShortcuts.value = { ...storedShortcuts };
|
||||
} else {
|
||||
shortcuts.value = { ...defaultShortcuts };
|
||||
tempShortcuts.value = { ...defaultShortcuts };
|
||||
window.electron.ipcRenderer.send('set-store-value', 'shortcuts', defaultShortcuts);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const shortcutLabels: Record<keyof Shortcuts, string> = {
|
||||
togglePlay: '播放/暂停',
|
||||
prevPlay: '上一首',
|
||||
nextPlay: '下一首',
|
||||
volumeUp: '音量增加',
|
||||
volumeDown: '音量减少',
|
||||
toggleFavorite: '收藏/取消收藏',
|
||||
toggleWindow: '显示/隐藏窗口'
|
||||
};
|
||||
|
||||
const getShortcutLabel = (key: keyof Shortcuts) => shortcutLabels[key];
|
||||
|
||||
const isRecording = ref(false);
|
||||
const currentKey = ref<keyof Shortcuts | ''>('');
|
||||
const message = useMessage();
|
||||
|
||||
// 检查快捷键冲突
|
||||
const duplicateKeys = computed(() => {
|
||||
const result: Record<string, boolean> = {};
|
||||
const usedShortcuts = new Set<string>();
|
||||
|
||||
Object.entries(tempShortcuts.value).forEach(([key, shortcut]) => {
|
||||
if (usedShortcuts.has(shortcut)) {
|
||||
result[key] = true;
|
||||
} else {
|
||||
usedShortcuts.add(shortcut);
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
// 是否存在冲突
|
||||
const hasConflict = computed(() => Object.keys(duplicateKeys.value).length > 0);
|
||||
|
||||
const startRecording = (key: keyof Shortcuts) => {
|
||||
isRecording.value = true;
|
||||
currentKey.value = key;
|
||||
// 禁用全局快捷键
|
||||
if (isElectron) {
|
||||
window.electron.ipcRenderer.send('disable-shortcuts');
|
||||
}
|
||||
};
|
||||
|
||||
const stopRecording = () => {
|
||||
isRecording.value = false;
|
||||
currentKey.value = '';
|
||||
// 重新启用全局快捷键
|
||||
if (isElectron) {
|
||||
window.electron.ipcRenderer.send('enable-shortcuts');
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent, key: keyof Shortcuts) => {
|
||||
if (!isRecording.value || currentKey.value !== key) return;
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
const modifiers: string[] = [];
|
||||
|
||||
// 统一使用 CommandOrControl
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
modifiers.push('CommandOrControl');
|
||||
}
|
||||
if (e.altKey) modifiers.push('Alt');
|
||||
if (e.shiftKey) modifiers.push('Shift');
|
||||
|
||||
let keyName = e.key;
|
||||
|
||||
// 特殊按键处理
|
||||
switch (e.key) {
|
||||
case 'ArrowLeft':
|
||||
keyName = 'Left';
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
keyName = 'Right';
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
keyName = 'Up';
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
keyName = 'Down';
|
||||
break;
|
||||
case 'Control':
|
||||
case 'Alt':
|
||||
case 'Shift':
|
||||
case 'Meta':
|
||||
case 'Command':
|
||||
return; // 忽略单独的修饰键
|
||||
default:
|
||||
keyName = e.key.length === 1 ? e.key.toUpperCase() : e.key;
|
||||
}
|
||||
|
||||
if (!['Control', 'Alt', 'Shift', 'Meta', 'Command'].includes(keyName)) {
|
||||
tempShortcuts.value[key] = [...modifiers, keyName].join('+');
|
||||
}
|
||||
};
|
||||
|
||||
const resetShortcuts = () => {
|
||||
tempShortcuts.value = { ...defaultShortcuts };
|
||||
message.success('已恢复默认快捷键,请记得保存');
|
||||
};
|
||||
|
||||
const saveShortcuts = () => {
|
||||
if (hasConflict.value) {
|
||||
message.error('存在冲突的快捷键,请重新设置');
|
||||
return;
|
||||
}
|
||||
|
||||
// 创建一个新的 Shortcuts 对象
|
||||
const shortcutsToSave = cloneDeep(tempShortcuts.value);
|
||||
|
||||
shortcuts.value = shortcutsToSave;
|
||||
|
||||
if (isElectron) {
|
||||
try {
|
||||
// 先保存到 store
|
||||
window.electron.ipcRenderer.send('set-store-value', 'shortcuts', shortcutsToSave);
|
||||
// 然后更新快捷键
|
||||
window.electron.ipcRenderer.send('update-shortcuts');
|
||||
message.success('快捷键设置已保存');
|
||||
} catch (error) {
|
||||
console.error('保存快捷键失败:', error);
|
||||
message.error('保存快捷键失败,请重试');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
tempShortcuts.value = { ...shortcuts.value };
|
||||
message.info('已取消修改');
|
||||
emit('update:show', false);
|
||||
};
|
||||
|
||||
// 组件卸载时确保快捷键被重新启用
|
||||
onUnmounted(() => {
|
||||
if (isElectron) {
|
||||
window.electron.ipcRenderer.send('enable-shortcuts');
|
||||
}
|
||||
});
|
||||
|
||||
// 格式化快捷键显示
|
||||
const formatShortcut = (shortcut: string) => {
|
||||
const isMac = isElectron
|
||||
? window.electron.ipcRenderer.sendSync('get-platform') === 'darwin'
|
||||
: false;
|
||||
return shortcut
|
||||
.replace(/CommandOrControl/g, isMac ? '⌘' : 'Ctrl')
|
||||
.replace(/\+/g, ' + ')
|
||||
.replace(/Meta/g, isMac ? '⌘' : 'Win')
|
||||
.replace(/Control/g, isMac ? '⌃' : 'Ctrl')
|
||||
.replace(/Alt/g, isMac ? '⌥' : 'Alt')
|
||||
.replace(/Shift/g, isMac ? '⇧' : 'Shift')
|
||||
.replace(/ArrowUp/g, '↑')
|
||||
.replace(/ArrowDown/g, '↓')
|
||||
.replace(/ArrowLeft/g, '←')
|
||||
.replace(/ArrowRight/g, '→');
|
||||
};
|
||||
|
||||
const visible = ref(false);
|
||||
const emit = defineEmits(['update:show', 'change']);
|
||||
|
||||
// 接收外部的 show 属性
|
||||
const props = defineProps<{
|
||||
show?: boolean;
|
||||
}>();
|
||||
|
||||
// 监听 show 属性变化
|
||||
watch(
|
||||
() => props.show,
|
||||
(newVal) => {
|
||||
visible.value = newVal;
|
||||
}
|
||||
);
|
||||
|
||||
// 监听内部 visible 变化
|
||||
watch(visible, (newVal) => {
|
||||
emit('update:show', newVal);
|
||||
});
|
||||
|
||||
// 处理弹窗关闭后的事件
|
||||
const handleAfterLeave = () => {
|
||||
// 重置临时数据
|
||||
tempShortcuts.value = { ...shortcuts.value };
|
||||
};
|
||||
|
||||
// 处理取消按钮点击
|
||||
const handleCancel = () => {
|
||||
visible.value = false;
|
||||
cancelEdit();
|
||||
};
|
||||
|
||||
// 处理保存按钮点击
|
||||
const handleSave = () => {
|
||||
saveShortcuts();
|
||||
visible.value = false;
|
||||
emit('change', shortcuts.value);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.shortcut-settings {
|
||||
height: 500px;
|
||||
|
||||
.shortcut-card {
|
||||
@apply flex flex-col h-full;
|
||||
|
||||
.shortcut-footer {
|
||||
@apply p-4 border-t border-gray-100 dark:border-gray-800;
|
||||
}
|
||||
|
||||
.shortcut-content {
|
||||
@apply flex-1 overflow-hidden;
|
||||
|
||||
:deep(.n-scrollbar) {
|
||||
@apply h-full;
|
||||
|
||||
.n-scrollbar-content {
|
||||
@apply p-4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.shortcut-item {
|
||||
@apply flex items-center justify-between p-3 rounded-lg transition-all mb-3;
|
||||
@apply bg-gray-50 dark:bg-gray-800;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.shortcut-info {
|
||||
@apply flex flex-col;
|
||||
|
||||
.shortcut-label {
|
||||
@apply text-base font-medium;
|
||||
}
|
||||
}
|
||||
|
||||
.shortcut-input {
|
||||
@apply flex items-center gap-2;
|
||||
min-width: 200px;
|
||||
|
||||
:deep(.n-input) {
|
||||
.n-input__input-el {
|
||||
@apply text-center font-mono;
|
||||
}
|
||||
}
|
||||
|
||||
.error-icon {
|
||||
@apply text-red-500;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,24 +1,29 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { ref } from 'vue';
|
||||
|
||||
// 定义表配置的泛型接口
|
||||
export interface StoreConfig<T extends string> {
|
||||
name: T;
|
||||
keyPath?: string;
|
||||
}
|
||||
|
||||
// 创建一个使用 IndexedDB 的组合函数
|
||||
const useIndexedDB = () => {
|
||||
const db = ref<IDBDatabase | null>(null); // 数据库引用
|
||||
const useIndexedDB = async <T extends string, S extends Record<T, Record<string, any>>>(
|
||||
dbName: string,
|
||||
stores: StoreConfig<T>[],
|
||||
version: number = 1
|
||||
) => {
|
||||
const db = ref<IDBDatabase | null>(null);
|
||||
|
||||
// 打开数据库并创建表
|
||||
const initDB = (
|
||||
dbName: string,
|
||||
version: number,
|
||||
stores: { name: string; keyPath?: string }[]
|
||||
) => {
|
||||
const initDB = () => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const request = indexedDB.open(dbName, version); // 打开数据库请求
|
||||
const request = indexedDB.open(dbName, version);
|
||||
|
||||
request.onupgradeneeded = (event: any) => {
|
||||
const db = event.target.result; // 获取数据库实例
|
||||
const db = event.target.result;
|
||||
stores.forEach((store) => {
|
||||
if (!db.objectStoreNames.contains(store.name)) {
|
||||
// 确保对象存储(表)创建
|
||||
db.createObjectStore(store.name, {
|
||||
keyPath: store.keyPath || 'id',
|
||||
autoIncrement: true
|
||||
@@ -28,39 +33,41 @@ const useIndexedDB = () => {
|
||||
};
|
||||
|
||||
request.onsuccess = (event: any) => {
|
||||
db.value = event.target.result; // 保存数据库实例
|
||||
resolve(); // 成功时解析 Promise
|
||||
db.value = event.target.result;
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = (event: any) => {
|
||||
reject(event.target.error); // 失败时拒绝 Promise
|
||||
reject(event.target.error);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// 通用新增数据
|
||||
const addData = (storeName: string, value: any) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化'); // 检查数据库是否已初始化
|
||||
const tx = db.value.transaction(storeName, 'readwrite'); // 创建事务
|
||||
const store = tx.objectStore(storeName); // 获取对象存储
|
||||
await initDB();
|
||||
|
||||
const request = store.add(value); // 添加数据请求
|
||||
// 通用新增数据
|
||||
const addData = <K extends T>(storeName: K, value: S[K]) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readwrite');
|
||||
const store = tx.objectStore(storeName);
|
||||
|
||||
const request = store.add(value);
|
||||
|
||||
request.onsuccess = () => {
|
||||
console.log('成功'); // 成功时输出
|
||||
resolve(); // 解析 Promise
|
||||
console.log('成功');
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = (event) => {
|
||||
console.error('新增失败:', (event.target as IDBRequest).error); // 输出错误
|
||||
reject((event.target as IDBRequest).error); // 拒绝 Promise
|
||||
console.error('新增失败:', (event.target as IDBRequest).error);
|
||||
reject((event.target as IDBRequest).error);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// 通用保存数据(新增或更新)
|
||||
const saveData = (storeName: string, value: any) => {
|
||||
const saveData = <K extends T>(storeName: K, value: S[K]) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readwrite');
|
||||
@@ -79,8 +86,8 @@ const useIndexedDB = () => {
|
||||
};
|
||||
|
||||
// 通用获取数据
|
||||
const getData = (storeName: string, key: string | number) => {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
const getData = <K extends T>(storeName: K, key: string | number) => {
|
||||
return new Promise<S[K]>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readonly');
|
||||
const store = tx.objectStore(storeName);
|
||||
@@ -101,7 +108,7 @@ const useIndexedDB = () => {
|
||||
};
|
||||
|
||||
// 删除数据
|
||||
const deleteData = (storeName: string, key: string | number) => {
|
||||
const deleteData = <K extends T>(storeName: K, key: string | number) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readwrite');
|
||||
@@ -120,8 +127,8 @@ const useIndexedDB = () => {
|
||||
};
|
||||
|
||||
// 查询所有数据
|
||||
const getAllData = (storeName: string) => {
|
||||
return new Promise<any[]>((resolve, reject) => {
|
||||
const getAllData = <K extends T>(storeName: K) => {
|
||||
return new Promise<S[K][]>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readonly');
|
||||
const store = tx.objectStore(storeName);
|
||||
@@ -142,29 +149,29 @@ const useIndexedDB = () => {
|
||||
};
|
||||
|
||||
// 分页查询数据
|
||||
const getDataWithPagination = (storeName: string, page: number, pageSize: number) => {
|
||||
return new Promise<any[]>((resolve, reject) => {
|
||||
const getDataWithPagination = <K extends T>(storeName: K, page: number, pageSize: number) => {
|
||||
return new Promise<S[K][]>((resolve, reject) => {
|
||||
if (!db.value) return reject('数据库未初始化');
|
||||
const tx = db.value.transaction(storeName, 'readonly');
|
||||
const store = tx.objectStore(storeName);
|
||||
const request = store.openCursor(); // 打开游标请求
|
||||
const results: any[] = []; // 存储结果的数组
|
||||
let index = 0; // 当前索引
|
||||
const skip = (page - 1) * pageSize; // 计算跳过的数量
|
||||
const request = store.openCursor();
|
||||
const results: S[K][] = [];
|
||||
let index = 0;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
request.onsuccess = (event: any) => {
|
||||
const cursor = event.target.result; // 获取游标
|
||||
const cursor = event.target.result;
|
||||
if (!cursor) {
|
||||
resolve(results); // 如果没有更多数据,解析结果
|
||||
resolve(results);
|
||||
return;
|
||||
}
|
||||
|
||||
if (index >= skip && results.length < pageSize) {
|
||||
results.push(cursor.value); // 添加当前游标值到结果
|
||||
results.push(cursor.value);
|
||||
}
|
||||
|
||||
index++; // 增加索引
|
||||
cursor.continue(); // 继续游标
|
||||
index++;
|
||||
cursor.continue();
|
||||
};
|
||||
|
||||
request.onerror = (event: any) => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
|
||||
import useIndexedDB from '@/hooks/IndexDBHook';
|
||||
import { audioService } from '@/services/audioService';
|
||||
import store from '@/store';
|
||||
import type { ILyricText, SongResult } from '@/type/music';
|
||||
import { getTextColors } from '@/utils/linearColor';
|
||||
import type { Artist, ILyricText, SongResult } from '@/type/music';
|
||||
import { isElectron } from '@/utils';
|
||||
|
||||
import { getTextColors } from '@/utils/linearColor';
|
||||
import { createDiscreteApi } from 'naive-ui';
|
||||
const windowData = window as any;
|
||||
|
||||
export const lrcArray = ref<ILyricText[]>([]); // 歌词数组
|
||||
@@ -18,7 +19,16 @@ export const currentLrcProgress = ref(0); // 来存储当前歌词的进度
|
||||
export const playMusic = computed(() => store.state.playMusic as SongResult); // 当前播放歌曲
|
||||
export const sound = ref<Howl | null>(audioService.getCurrentSound());
|
||||
export const isLyricWindowOpen = ref(false); // 新增状态
|
||||
export const textColors = ref(getTextColors());
|
||||
export const textColors = ref<any>(getTextColors());
|
||||
export const artistList = computed(
|
||||
() => (store.state.playMusic.ar || store.state.playMusic?.song?.artists) as Artist[]
|
||||
);
|
||||
|
||||
export const musicDB = await useIndexedDB('musicDB', [
|
||||
{ name: 'music', keyPath: 'id' },
|
||||
{ name: 'music_lyric', keyPath: 'id' },
|
||||
{ name: 'api_cache', keyPath: 'id' }
|
||||
]);
|
||||
|
||||
document.onkeyup = (e) => {
|
||||
// 检查事件目标是否是输入框元素
|
||||
@@ -41,13 +51,24 @@ document.onkeyup = (e) => {
|
||||
}
|
||||
};
|
||||
|
||||
const { message } = createDiscreteApi(['message']);
|
||||
|
||||
watch(
|
||||
() => store.state.playMusicUrl,
|
||||
(newVal) => {
|
||||
if (newVal) {
|
||||
audioService.play(newVal);
|
||||
sound.value = audioService.getCurrentSound();
|
||||
audioServiceOn(audioService);
|
||||
async (newVal) => {
|
||||
if (newVal && playMusic.value) {
|
||||
try {
|
||||
const newSound = await audioService.play(newVal, playMusic.value);
|
||||
sound.value = newSound as Howl;
|
||||
setupAudioListeners();
|
||||
} catch (error) {
|
||||
|
||||
console.error('播放音频失败:', error);
|
||||
store.commit('setPlayMusic', false);
|
||||
message.error('当前歌曲播放失败,播放下一首');
|
||||
// 下一首
|
||||
store.commit('nextPlay');
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -70,59 +91,111 @@ watch(
|
||||
}
|
||||
);
|
||||
|
||||
export const audioServiceOn = (audio: typeof audioService) => {
|
||||
const setupAudioListeners = () => {
|
||||
let interval: any = null;
|
||||
|
||||
const clearInterval = () => {
|
||||
if (interval) {
|
||||
window.clearInterval(interval);
|
||||
interval = null;
|
||||
}
|
||||
};
|
||||
|
||||
// 清理所有事件监听器
|
||||
audioService.clearAllListeners();
|
||||
|
||||
// 监听播放
|
||||
audio.onPlay(() => {
|
||||
audioService.on('play', () => {
|
||||
store.commit('setPlayMusic', true);
|
||||
interval = setInterval(() => {
|
||||
nowTime.value = sound.value?.seek() as number;
|
||||
allTime.value = sound.value?.duration() as number;
|
||||
const newIndex = getLrcIndex(nowTime.value);
|
||||
if (newIndex !== nowIndex.value) {
|
||||
nowIndex.value = newIndex;
|
||||
currentLrcProgress.value = 0;
|
||||
// 当歌词索引更新时,发送歌词数据
|
||||
clearInterval();
|
||||
interval = window.setInterval(() => {
|
||||
try {
|
||||
const currentSound = sound.value;
|
||||
if (!currentSound || typeof currentSound.seek !== 'function') {
|
||||
console.error('Invalid sound object or seek function');
|
||||
clearInterval();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTime = currentSound.seek() as number;
|
||||
if (typeof currentTime !== 'number' || Number.isNaN(currentTime)) {
|
||||
console.error('Invalid current time:', currentTime);
|
||||
clearInterval();
|
||||
return;
|
||||
}
|
||||
|
||||
nowTime.value = currentTime;
|
||||
allTime.value = currentSound.duration() as number;
|
||||
const newIndex = getLrcIndex(nowTime.value);
|
||||
if (newIndex !== nowIndex.value) {
|
||||
nowIndex.value = newIndex;
|
||||
currentLrcProgress.value = 0;
|
||||
if (isElectron && isLyricWindowOpen.value) {
|
||||
sendLyricToWin();
|
||||
}
|
||||
}
|
||||
if (isElectron && isLyricWindowOpen.value) {
|
||||
sendLyricToWin();
|
||||
}
|
||||
}
|
||||
// 定期发送歌词数据更新
|
||||
if (isElectron && isLyricWindowOpen.value) {
|
||||
sendLyricToWin();
|
||||
} catch (error) {
|
||||
console.error('Error in interval:', error);
|
||||
clearInterval();
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
|
||||
// 监听暂停
|
||||
audio.onPause(() => {
|
||||
audioService.on('pause', () => {
|
||||
store.commit('setPlayMusic', false);
|
||||
clearInterval(interval);
|
||||
// 暂停时也发送一次状态更新
|
||||
clearInterval();
|
||||
if (isElectron && isLyricWindowOpen.value) {
|
||||
sendLyricToWin();
|
||||
}
|
||||
});
|
||||
|
||||
const replayMusic = async () => {
|
||||
try {
|
||||
// 如果当前有音频实例,先停止并销毁
|
||||
if (sound.value) {
|
||||
sound.value.stop();
|
||||
sound.value.unload();
|
||||
sound.value = null;
|
||||
}
|
||||
|
||||
// 重新播放当前歌曲
|
||||
if (store.state.playMusicUrl && playMusic.value) {
|
||||
const newSound = await audioService.play(store.state.playMusicUrl, playMusic.value);
|
||||
sound.value = newSound as Howl;
|
||||
setupAudioListeners();
|
||||
} else {
|
||||
console.error('No music URL or playMusic data available');
|
||||
store.commit('nextPlay');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error replaying song:', error);
|
||||
store.commit('nextPlay');
|
||||
}
|
||||
};
|
||||
|
||||
// 监听结束
|
||||
audio.onEnd(() => {
|
||||
audioService.on('end', () => {
|
||||
clearInterval();
|
||||
|
||||
if (store.state.playMode === 1) {
|
||||
// 单曲循环模式
|
||||
audio.getCurrentSound()?.play();
|
||||
if (sound.value) {
|
||||
replayMusic();
|
||||
}
|
||||
} else if (store.state.playMode === 2) {
|
||||
// 随机播放模式
|
||||
const { playList } = store.state;
|
||||
if (playList.length <= 1) {
|
||||
// 如果播放列表只有一首歌或为空,则重新播放当前歌曲
|
||||
audio.getCurrentSound()?.play();
|
||||
replayMusic();
|
||||
} else {
|
||||
// 随机选择一首不同的歌
|
||||
let randomIndex;
|
||||
do {
|
||||
randomIndex = Math.floor(Math.random() * playList.length);
|
||||
} while (randomIndex === store.state.playListIndex && playList.length > 1);
|
||||
|
||||
store.state.playListIndex = randomIndex;
|
||||
store.commit('setPlay', playList[randomIndex]);
|
||||
}
|
||||
@@ -131,6 +204,8 @@ export const audioServiceOn = (audio: typeof audioService) => {
|
||||
store.commit('nextPlay');
|
||||
}
|
||||
});
|
||||
|
||||
return clearInterval;
|
||||
};
|
||||
|
||||
export const play = () => {
|
||||
@@ -195,20 +270,47 @@ export const useLyricProgress = () => {
|
||||
let animationFrameId: number | null = null;
|
||||
|
||||
const updateProgress = () => {
|
||||
if (!isPlaying.value) return;
|
||||
if (!isPlaying.value) {
|
||||
stopProgressAnimation();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentSound = sound.value;
|
||||
if (!currentSound) return;
|
||||
if (!currentSound || typeof currentSound.seek !== 'function') {
|
||||
console.error('Invalid sound object or seek function');
|
||||
stopProgressAnimation();
|
||||
return;
|
||||
}
|
||||
|
||||
const { start, end } = currentLrcTiming.value;
|
||||
const duration = end - start;
|
||||
const elapsed = (currentSound.seek() as number) - start;
|
||||
currentLrcProgress.value = Math.min(Math.max((elapsed / duration) * 100, 0), 100);
|
||||
try {
|
||||
const { start, end } = currentLrcTiming.value;
|
||||
if (typeof start !== 'number' || typeof end !== 'number' || start === end) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTime = currentSound.seek() as number;
|
||||
if (typeof currentTime !== 'number' || Number.isNaN(currentTime)) {
|
||||
console.error('Invalid current time:', currentTime);
|
||||
return;
|
||||
}
|
||||
|
||||
const elapsed = currentTime - start;
|
||||
const duration = end - start;
|
||||
const progress = (elapsed / duration) * 100;
|
||||
|
||||
// 确保进度在 0-100 之间
|
||||
currentLrcProgress.value = Math.min(Math.max(progress, 0), 100);
|
||||
} catch (error) {
|
||||
console.error('Error updating progress:', error);
|
||||
}
|
||||
|
||||
// 继续下一帧更新
|
||||
animationFrameId = requestAnimationFrame(updateProgress);
|
||||
};
|
||||
|
||||
const startProgressAnimation = () => {
|
||||
if (!animationFrameId && isPlaying.value) {
|
||||
stopProgressAnimation(); // 先停止之前的动画
|
||||
if (isPlaying.value) {
|
||||
updateProgress();
|
||||
}
|
||||
};
|
||||
@@ -220,8 +322,30 @@ export const useLyricProgress = () => {
|
||||
}
|
||||
};
|
||||
|
||||
watch(isPlaying, (newIsPlaying) => {
|
||||
if (newIsPlaying) {
|
||||
// 监听播放状态变化
|
||||
watch(
|
||||
isPlaying,
|
||||
(newIsPlaying) => {
|
||||
if (newIsPlaying) {
|
||||
startProgressAnimation();
|
||||
} else {
|
||||
stopProgressAnimation();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 监听当前歌词索引变化
|
||||
watch(nowIndex, () => {
|
||||
currentLrcProgress.value = 0;
|
||||
if (isPlaying.value) {
|
||||
startProgressAnimation();
|
||||
}
|
||||
});
|
||||
|
||||
// 监听音频对象变化
|
||||
watch(sound, (newSound) => {
|
||||
if (newSound && isPlaying.value) {
|
||||
startProgressAnimation();
|
||||
} else {
|
||||
stopProgressAnimation();
|
||||
@@ -357,3 +481,9 @@ if (isElectron) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 在组件挂载时设置监听器
|
||||
onMounted(() => {
|
||||
setupAudioListeners();
|
||||
useLyricProgress(); // 直接调用,不需要解构返回值
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Howl } from 'howler';
|
||||
import { cloneDeep } from 'lodash';
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { getMusicLrc, getMusicUrl, getParsingMusicUrl } from '@/api/music';
|
||||
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
|
||||
@@ -6,29 +8,36 @@ import { audioService } from '@/services/audioService';
|
||||
import type { ILyric, ILyricText, SongResult } from '@/type/music';
|
||||
import { getImgUrl } from '@/utils';
|
||||
import { getImageLinearBackground } from '@/utils/linearColor';
|
||||
import { cloneDeep } from 'lodash';
|
||||
|
||||
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);
|
||||
let url = '';
|
||||
let songDetail = null;
|
||||
try {
|
||||
if (data.data[0].freeTrialInfo || !data.data[0].url) {
|
||||
const res = await getParsingMusicUrl(id, songData);
|
||||
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
|
||||
@@ -55,43 +64,91 @@ export const useMusicListHook = () => {
|
||||
fetchSongs(state, playListIndex + 1, playListIndex + 6);
|
||||
};
|
||||
|
||||
const preloadingSounds = ref<Howl[]>([]);
|
||||
|
||||
// 用于预加载下一首歌曲的 MP3 数据
|
||||
const preloadNextSong = (nextSongUrl: string) => {
|
||||
const sound = new Howl({
|
||||
src: [nextSongUrl],
|
||||
html5: true,
|
||||
preload: true,
|
||||
autoplay: false
|
||||
});
|
||||
return sound;
|
||||
try {
|
||||
// 限制同时预加载的数量
|
||||
if (preloadingSounds.value.length >= 2) {
|
||||
const oldestSound = preloadingSounds.value.shift();
|
||||
if (oldestSound) {
|
||||
oldestSound.unload();
|
||||
}
|
||||
}
|
||||
|
||||
const sound = new Howl({
|
||||
src: [nextSongUrl],
|
||||
html5: true,
|
||||
preload: true,
|
||||
autoplay: false
|
||||
});
|
||||
|
||||
preloadingSounds.value.push(sound);
|
||||
|
||||
// 添加加载错误处理
|
||||
sound.on('loaderror', () => {
|
||||
console.error('预加载音频失败:', nextSongUrl);
|
||||
const index = preloadingSounds.value.indexOf(sound);
|
||||
if (index > -1) {
|
||||
preloadingSounds.value.splice(index, 1);
|
||||
}
|
||||
sound.unload();
|
||||
});
|
||||
|
||||
return sound;
|
||||
} catch (error) {
|
||||
console.error('预加载音频出错:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const fetchSongs = async (state: any, startIndex: number, endIndex: number) => {
|
||||
const songs = state.playList.slice(
|
||||
Math.max(0, startIndex),
|
||||
Math.min(endIndex, state.playList.length)
|
||||
);
|
||||
try {
|
||||
const songs = state.playList.slice(
|
||||
Math.max(0, startIndex),
|
||||
Math.min(endIndex, state.playList.length)
|
||||
);
|
||||
|
||||
const detailedSongs = await Promise.all(
|
||||
songs.map(async (song: SongResult) => {
|
||||
// 如果歌曲详情已经存在,就不重复请求
|
||||
if (!song.playMusicUrl) {
|
||||
return await getSongDetail(song);
|
||||
const detailedSongs = await Promise.all(
|
||||
songs.map(async (song: SongResult) => {
|
||||
try {
|
||||
// 如果歌曲详情已经存在,就不重复请求
|
||||
if (!song.playMusicUrl) {
|
||||
return await getSongDetail(song);
|
||||
}
|
||||
return song;
|
||||
} catch (error) {
|
||||
console.error('获取歌曲详情失败:', error);
|
||||
return song;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// 加载下一首的歌词
|
||||
const nextSong = detailedSongs[0];
|
||||
if (nextSong && !(nextSong.lyric && nextSong.lyric.lrcTimeArray.length > 0)) {
|
||||
try {
|
||||
nextSong.lyric = await loadLrc(nextSong.id);
|
||||
} catch (error) {
|
||||
console.error('加载歌词失败:', error);
|
||||
}
|
||||
return song;
|
||||
})
|
||||
);
|
||||
// 加载下一首的歌词
|
||||
const nextSong = detailedSongs[0];
|
||||
if (!(nextSong.lyric && nextSong.lyric.lrcTimeArray.length > 0)) {
|
||||
nextSong.lyric = await loadLrc(nextSong.id);
|
||||
}
|
||||
}
|
||||
|
||||
// 更新播放列表中的歌曲详情
|
||||
detailedSongs.forEach((song, index) => {
|
||||
state.playList[startIndex + index] = song;
|
||||
});
|
||||
preloadNextSong(nextSong.playMusicUrl);
|
||||
// 更新播放列表中的歌曲详情
|
||||
detailedSongs.forEach((song, index) => {
|
||||
if (song && startIndex + index < state.playList.length) {
|
||||
state.playList[startIndex + index] = song;
|
||||
}
|
||||
});
|
||||
|
||||
// 只预加载下一首歌曲
|
||||
if (nextSong && nextSong.playMusicUrl) {
|
||||
preloadNextSong(nextSong.playMusicUrl);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取歌曲列表失败:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const nextPlay = async (state: any) => {
|
||||
@@ -145,7 +202,7 @@ export const useMusicListHook = () => {
|
||||
const { lyrics, times } = parseLyrics(data.lrc.lyric);
|
||||
const tlyric: Record<string, string> = {};
|
||||
|
||||
if (data.tlyric.lyric) {
|
||||
if (data.tlyric && data.tlyric.lyric) {
|
||||
const { lyrics: tLyrics, times: tTimes } = parseLyrics(data.tlyric.lyric);
|
||||
tLyrics.forEach((lyric, index) => {
|
||||
tlyric[tTimes[index].toString()] = lyric.text;
|
||||
@@ -185,6 +242,12 @@ export const useMusicListHook = () => {
|
||||
audioService.getCurrentSound()?.pause();
|
||||
};
|
||||
|
||||
// 在组件卸载时清理预加载的音频
|
||||
onUnmounted(() => {
|
||||
preloadingSounds.value.forEach((sound) => sound.unload());
|
||||
preloadingSounds.value = [];
|
||||
});
|
||||
|
||||
return {
|
||||
handlePlayMusic,
|
||||
nextPlay,
|
||||
|
||||
@@ -11,7 +11,12 @@
|
||||
}
|
||||
|
||||
.n-slider-handle-indicator--top {
|
||||
@apply bg-transparent dark:text-[#ffffffdd] text-[#000000dd] text-2xl px-2 py-1 shadow-none mb-0 !important;
|
||||
@apply bg-transparent text-2xl px-2 py-1 shadow-none mb-0 dark:text-[#ffffffdd] text-[#000000dd] !important;
|
||||
mix-blend-mode: difference !important;
|
||||
}
|
||||
|
||||
.v-binder-follower-container:has(.n-slider-handle-indicator--top) {
|
||||
z-index: 999999999 !important;
|
||||
}
|
||||
|
||||
.text-el {
|
||||
@@ -56,3 +61,11 @@
|
||||
--text-color-300: #3d3d3d;
|
||||
--primary-color: #22c55e;
|
||||
}
|
||||
|
||||
:root {
|
||||
--text-color: #000000dd;
|
||||
}
|
||||
|
||||
:root[class='dark'] {
|
||||
--text-color: #ffffffdd;
|
||||
}
|
||||
|
||||
@@ -28,12 +28,10 @@
|
||||
<meta name="apple-mobile-web-app-title" content="网抑云音乐" />
|
||||
<!-- 资源预加载 -->
|
||||
<link rel="preload" href="./assets/icon/iconfont.css" as="style" />
|
||||
<link rel="preload" href="./assets/css/animate.css" as="style" />
|
||||
<link rel="preload" href="./assets/css/base.css" as="style" />
|
||||
|
||||
<!-- 样式表 -->
|
||||
<link rel="stylesheet" href="./assets/icon/iconfont.css" />
|
||||
<link rel="stylesheet" href="./assets/css/animate.css" />
|
||||
<link rel="stylesheet" href="./assets/css/base.css" />
|
||||
<script defer src="https://cn.vercount.one/js"></script>
|
||||
|
||||
|
||||
@@ -25,23 +25,28 @@
|
||||
</div>
|
||||
</div>
|
||||
<!-- 底部音乐播放 -->
|
||||
<play-bar v-if="isPlay" :style="isMobile && store.state.musicFull ? 'bottom: 0;' : ''" />
|
||||
<play-bar v-show="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"/>
|
||||
<update-modal v-if="isElectron" />
|
||||
<artist-drawer ref="artistDrawerRef" :show="artistDrawerShow" />
|
||||
<playlist-drawer v-model="showPlaylistDrawer" :song-id="currentSongId" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, defineAsyncComponent, onMounted } from 'vue';
|
||||
import { computed, defineAsyncComponent, nextTick, onMounted, provide, ref, watch } 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';
|
||||
import homeRouter from '@/router/home';
|
||||
import { isElectron, isMobile } from '@/utils';
|
||||
import UpdateModal from '@/components/common/UpdateModal.vue';
|
||||
|
||||
const keepAliveInclude = computed(() =>
|
||||
homeRouter
|
||||
@@ -58,6 +63,9 @@ const PlayBar = defineAsyncComponent(() => import('./components/PlayBar.vue'));
|
||||
const SearchBar = defineAsyncComponent(() => import('./components/SearchBar.vue'));
|
||||
const TitleBar = defineAsyncComponent(() => import('./components/TitleBar.vue'));
|
||||
|
||||
const ArtistDrawer = defineAsyncComponent(() => import('@/components/common/ArtistDrawer.vue'));
|
||||
const PlaylistDrawer = defineAsyncComponent(() => import('@/components/common/PlaylistDrawer.vue'));
|
||||
|
||||
const store = useStore();
|
||||
|
||||
const isPlay = computed(() => store.state.isPlay as boolean);
|
||||
@@ -68,6 +76,37 @@ onMounted(() => {
|
||||
store.dispatch('initializeSettings');
|
||||
store.dispatch('initializeTheme');
|
||||
});
|
||||
|
||||
const artistDrawerRef = ref<InstanceType<typeof ArtistDrawer>>();
|
||||
const artistDrawerShow = computed({
|
||||
get: () => store.state.showArtistDrawer,
|
||||
set: (val) => store.commit('setShowArtistDrawer', val)
|
||||
});
|
||||
|
||||
// 监听歌手ID变化
|
||||
watch(
|
||||
() => store.state.currentArtistId,
|
||||
(newId) => {
|
||||
if (newId) {
|
||||
artistDrawerShow.value = true;
|
||||
nextTick(() => {
|
||||
artistDrawerRef.value?.loadArtistInfo(newId);
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const showPlaylistDrawer = ref(false);
|
||||
const currentSongId = ref<number | undefined>();
|
||||
|
||||
// 提供一个方法来打开歌单抽屉
|
||||
const openPlaylistDrawer = (songId: number) => {
|
||||
currentSongId.value = songId;
|
||||
showPlaylistDrawer.value = true;
|
||||
};
|
||||
|
||||
// 将方法提供给全局
|
||||
provide('openPlaylistDrawer', openPlaylistDrawer);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
|
||||
@@ -1,14 +1,35 @@
|
||||
<template>
|
||||
<n-drawer
|
||||
:show="musicFull"
|
||||
v-model:show="isVisible"
|
||||
height="100%"
|
||||
placement="bottom"
|
||||
:style="{ background: currentBackground || background }"
|
||||
:to="`#layout-main`"
|
||||
:z-index="9998"
|
||||
>
|
||||
<div id="drawer-target">
|
||||
<div class="drawer-back"></div>
|
||||
<div id="drawer-target" :class="[config.theme]">
|
||||
<div
|
||||
class="control-btn absolute top-8 left-8"
|
||||
:class="{ 'pure-mode': config.pureModeEnabled }"
|
||||
@click="isVisible = false"
|
||||
>
|
||||
<i class="ri-arrow-down-s-line"></i>
|
||||
</div>
|
||||
|
||||
<n-popover trigger="click" placement="bottom">
|
||||
<template #trigger>
|
||||
<div
|
||||
class="control-btn absolute top-8 right-8"
|
||||
:class="{ 'pure-mode': config.pureModeEnabled }"
|
||||
>
|
||||
<i class="ri-settings-3-line"></i>
|
||||
</div>
|
||||
</template>
|
||||
<lyric-settings ref="lyricSettingsRef" />
|
||||
</n-popover>
|
||||
|
||||
<div
|
||||
v-show="!config.hideCover"
|
||||
class="music-img"
|
||||
:style="{ color: textColors.theme === 'dark' ? '#000000' : '#ffffff' }"
|
||||
>
|
||||
@@ -22,23 +43,60 @@
|
||||
<div>
|
||||
<div class="music-content-name">{{ playMusic.name }}</div>
|
||||
<div class="music-content-singer">
|
||||
<span v-for="(item, index) in playMusic.ar || playMusic.song.artists" :key="index">
|
||||
{{ item.name
|
||||
}}{{ index < (playMusic.ar || playMusic.song.artists).length - 1 ? ' / ' : '' }}
|
||||
</span>
|
||||
<n-ellipsis
|
||||
class="text-ellipsis"
|
||||
line-clamp="2"
|
||||
:tooltip="{
|
||||
contentStyle: { maxWidth: '600px' },
|
||||
zIndex: 99999
|
||||
}"
|
||||
>
|
||||
<span
|
||||
v-for="(item, index) in artistList"
|
||||
:key="index"
|
||||
class="cursor-pointer hover:text-green-500"
|
||||
@click="handleArtistClick(item.id)"
|
||||
>
|
||||
{{ item.name }}
|
||||
{{ index < artistList.length - 1 ? ' / ' : '' }}
|
||||
</span>
|
||||
</n-ellipsis>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="music-content">
|
||||
<div class="music-content" :class="{ center: config.centerLyrics && config.hideCover }">
|
||||
<n-layout
|
||||
ref="lrcSider"
|
||||
class="music-lrc"
|
||||
style="height: 60vh"
|
||||
:style="{
|
||||
height: config.hidePlayBar ? '85vh' : '65vh',
|
||||
width: config.hideCover ? '50vw' : '500px'
|
||||
}"
|
||||
:native-scrollbar="false"
|
||||
@mouseover="mouseOverLayout"
|
||||
@mouseleave="mouseLeaveLayout"
|
||||
>
|
||||
<div ref="lrcContainer">
|
||||
<!-- 歌曲信息 -->
|
||||
|
||||
<div ref="lrcContainer" class="music-lrc-container">
|
||||
<div
|
||||
v-if="config.hideCover"
|
||||
class="music-info-header"
|
||||
:style="{ textAlign: config.centerLyrics ? 'center' : 'left' }"
|
||||
>
|
||||
<div class="music-info-name">{{ playMusic.name }}</div>
|
||||
<div class="music-info-singer">
|
||||
<span
|
||||
v-for="(item, index) in artistList"
|
||||
:key="index"
|
||||
class="cursor-pointer hover:text-green-500"
|
||||
@click="handleArtistClick(item.id)"
|
||||
>
|
||||
{{ item.name }}
|
||||
{{ index < artistList.length - 1 ? ' / ' : '' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-for="(item, index) in lrcArray"
|
||||
:id="`music-lrc-text-${index}`"
|
||||
@@ -48,7 +106,9 @@
|
||||
@click="setAudioTime(index)"
|
||||
>
|
||||
<span :style="getLrcStyle(index)">{{ item.text }}</span>
|
||||
<div class="music-lrc-text-tr">{{ item.trText }}</div>
|
||||
<div v-show="config.showTranslation" class="music-lrc-text-tr">
|
||||
{{ item.trText }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 无歌词 -->
|
||||
@@ -69,9 +129,12 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
import { onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import LyricSettings from '@/components/lyric/LyricSettings.vue';
|
||||
import {
|
||||
artistList,
|
||||
lrcArray,
|
||||
nowIndex,
|
||||
playMusic,
|
||||
@@ -89,9 +152,59 @@ const lrcContainer = ref<HTMLElement | null>(null);
|
||||
const currentBackground = ref('');
|
||||
const animationFrame = ref<number | null>(null);
|
||||
const isDark = ref(false);
|
||||
const showStickyHeader = ref(false);
|
||||
const lyricSettingsRef = ref<InstanceType<typeof LyricSettings>>();
|
||||
|
||||
interface LyricConfig {
|
||||
hideCover: boolean;
|
||||
centerLyrics: boolean;
|
||||
fontSize: number;
|
||||
letterSpacing: number;
|
||||
lineHeight: number;
|
||||
showTranslation: boolean;
|
||||
theme: 'default' | 'light' | 'dark';
|
||||
hidePlayBar: boolean;
|
||||
pureModeEnabled: boolean;
|
||||
}
|
||||
|
||||
// 移除 computed 配置
|
||||
const config = ref<LyricConfig>({
|
||||
hideCover: false,
|
||||
centerLyrics: false,
|
||||
fontSize: 22,
|
||||
letterSpacing: 0,
|
||||
lineHeight: 1.5,
|
||||
showTranslation: true,
|
||||
theme: 'default',
|
||||
hidePlayBar: false,
|
||||
pureModeEnabled: false
|
||||
});
|
||||
|
||||
// 监听设置组件的配置变化
|
||||
watch(
|
||||
() => lyricSettingsRef.value?.config,
|
||||
(newConfig) => {
|
||||
if (newConfig) {
|
||||
config.value = newConfig;
|
||||
}
|
||||
},
|
||||
{ deep: true, immediate: true }
|
||||
);
|
||||
|
||||
// 监听本地配置变化,保存到 localStorage
|
||||
watch(
|
||||
() => config.value,
|
||||
(newConfig) => {
|
||||
localStorage.setItem('music-full-config', JSON.stringify(newConfig));
|
||||
if (lyricSettingsRef.value) {
|
||||
lyricSettingsRef.value.config = newConfig;
|
||||
}
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
const props = defineProps({
|
||||
musicFull: {
|
||||
modelValue: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
@@ -101,26 +214,58 @@ const props = defineProps({
|
||||
}
|
||||
});
|
||||
|
||||
const themeMusic = {
|
||||
light: 'linear-gradient(to bottom, #ffffff, #f5f5f5)',
|
||||
dark: 'linear-gradient(to bottom, #1a1a1a, #000000)'
|
||||
};
|
||||
|
||||
const emit = defineEmits(['update:modelValue']);
|
||||
|
||||
const isVisible = computed({
|
||||
get: () => props.modelValue,
|
||||
set: (value) => emit('update:modelValue', value)
|
||||
});
|
||||
|
||||
// 歌词滚动方法
|
||||
const lrcScroll = (behavior = 'smooth') => {
|
||||
const nowEl = document.querySelector(`#music-lrc-text-${nowIndex.value}`);
|
||||
if (props.musicFull && !isMouse.value && nowEl && lrcContainer.value) {
|
||||
const containerRect = lrcContainer.value.getBoundingClientRect();
|
||||
const nowElRect = nowEl.getBoundingClientRect();
|
||||
const relativeTop = nowElRect.top - containerRect.top;
|
||||
const scrollTop = relativeTop - lrcSider.value.$el.getBoundingClientRect().height / 2;
|
||||
lrcSider.value.scrollTo({ top: scrollTop, behavior });
|
||||
const lrcScroll = (behavior: ScrollBehavior = 'smooth', forceTop: boolean = false) => {
|
||||
if (!isVisible.value || !lrcSider.value) return;
|
||||
|
||||
if (forceTop) {
|
||||
lrcSider.value.scrollTo({
|
||||
top: 0,
|
||||
behavior
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isMouse.value) return;
|
||||
|
||||
const nowEl = document.querySelector(`#music-lrc-text-${nowIndex.value}`) as HTMLElement;
|
||||
if (nowEl) {
|
||||
const containerHeight = lrcSider.value.$el.clientHeight;
|
||||
const elementTop = nowEl.offsetTop;
|
||||
const scrollTop = elementTop - containerHeight / 2 + nowEl.clientHeight / 2;
|
||||
|
||||
lrcSider.value.scrollTo({
|
||||
top: scrollTop,
|
||||
behavior
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const debouncedLrcScroll = useDebounceFn(lrcScroll, 200);
|
||||
|
||||
const mouseOverLayout = () => {
|
||||
if(isMobile.value) {return}
|
||||
if (isMobile.value) {
|
||||
return;
|
||||
}
|
||||
isMouse.value = true;
|
||||
};
|
||||
|
||||
const mouseLeaveLayout = () => {
|
||||
if(isMobile.value) {return}
|
||||
if (isMobile.value) {
|
||||
return;
|
||||
}
|
||||
setTimeout(() => {
|
||||
isMouse.value = false;
|
||||
lrcScroll();
|
||||
@@ -132,9 +277,9 @@ watch(nowIndex, () => {
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.musicFull,
|
||||
() => isVisible.value,
|
||||
() => {
|
||||
if (props.musicFull) {
|
||||
if (isVisible.value) {
|
||||
nextTick(() => {
|
||||
lrcScroll('instant');
|
||||
});
|
||||
@@ -142,41 +287,51 @@ watch(
|
||||
}
|
||||
);
|
||||
|
||||
const setTextColors = (background: string) => {
|
||||
if (!background) {
|
||||
textColors.value = getTextColors();
|
||||
document.documentElement.style.setProperty('--hover-bg-color', getHoverBackgroundColor(false));
|
||||
document.documentElement.style.setProperty('--text-color-primary', textColors.value.primary);
|
||||
document.documentElement.style.setProperty('--text-color-active', textColors.value.active);
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新文字颜色
|
||||
textColors.value = getTextColors(background);
|
||||
isDark.value = textColors.value.active === '#000000';
|
||||
|
||||
document.documentElement.style.setProperty(
|
||||
'--hover-bg-color',
|
||||
getHoverBackgroundColor(isDark.value)
|
||||
);
|
||||
document.documentElement.style.setProperty('--text-color-primary', textColors.value.primary);
|
||||
document.documentElement.style.setProperty('--text-color-active', textColors.value.active);
|
||||
|
||||
// 处理背景颜色动画
|
||||
if (currentBackground.value) {
|
||||
if (animationFrame.value) {
|
||||
cancelAnimationFrame(animationFrame.value);
|
||||
}
|
||||
const result = animateGradient(currentBackground.value, background, (gradient) => {
|
||||
currentBackground.value = gradient;
|
||||
});
|
||||
if (typeof result === 'number') {
|
||||
animationFrame.value = result;
|
||||
}
|
||||
} else {
|
||||
currentBackground.value = background;
|
||||
}
|
||||
};
|
||||
|
||||
// 监听背景变化
|
||||
watch(
|
||||
() => props.background,
|
||||
(newBg) => {
|
||||
if (!newBg) {
|
||||
textColors.value = getTextColors();
|
||||
document.documentElement.style.setProperty(
|
||||
'--hover-bg-color',
|
||||
getHoverBackgroundColor(false)
|
||||
);
|
||||
document.documentElement.style.setProperty('--text-color-primary', textColors.value.primary);
|
||||
document.documentElement.style.setProperty('--text-color-active', textColors.value.active);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentBackground.value) {
|
||||
if (animationFrame.value) {
|
||||
cancelAnimationFrame(animationFrame.value);
|
||||
}
|
||||
animationFrame.value = animateGradient(currentBackground.value, newBg, (gradient) => {
|
||||
currentBackground.value = gradient;
|
||||
});
|
||||
if (config.value.theme === 'default') {
|
||||
setTextColors(newBg);
|
||||
} else {
|
||||
currentBackground.value = newBg;
|
||||
setTextColors(themeMusic[config.value.theme] || props.background);
|
||||
}
|
||||
|
||||
textColors.value = getTextColors(newBg);
|
||||
isDark.value = textColors.value.active === '#000000';
|
||||
|
||||
document.documentElement.style.setProperty(
|
||||
'--hover-bg-color',
|
||||
getHoverBackgroundColor(isDark.value)
|
||||
);
|
||||
document.documentElement.style.setProperty('--text-color-primary', textColors.value.primary);
|
||||
document.documentElement.style.setProperty('--text-color-active', textColors.value.active);
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
@@ -215,8 +370,137 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const store = useStore();
|
||||
const handleArtistClick = (id: number) => {
|
||||
isVisible.value = false;
|
||||
store.commit('setCurrentArtistId', id);
|
||||
};
|
||||
|
||||
const setData = computed(() => store.state.setData);
|
||||
|
||||
// 监听字体变化并更新 CSS 变量
|
||||
watch(
|
||||
() => [setData.value.fontFamily, setData.value.fontScope],
|
||||
([newFont, fontScope]) => {
|
||||
const defaultFonts =
|
||||
'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
|
||||
|
||||
// 如果不是歌词模式或全局模式,使用默认字体
|
||||
if (fontScope !== 'lyric' && fontScope !== 'global') {
|
||||
document.documentElement.style.setProperty('--current-font-family', defaultFonts);
|
||||
return;
|
||||
}
|
||||
|
||||
if (newFont === 'system-ui') {
|
||||
document.documentElement.style.setProperty('--current-font-family', defaultFonts);
|
||||
} else {
|
||||
// 处理多个字体,确保每个字体名都被正确引用
|
||||
const fontList = newFont.split(',').map((font) => {
|
||||
const trimmedFont = font.trim();
|
||||
// 如果字体名包含空格或特殊字符,添加引号(如果还没有引号的话)
|
||||
return /[\s'"()]/.test(trimmedFont) && !/^['"].*['"]$/.test(trimmedFont)
|
||||
? `"${trimmedFont}"`
|
||||
: trimmedFont;
|
||||
});
|
||||
|
||||
// 将选择的字体和默认字体组合
|
||||
document.documentElement.style.setProperty(
|
||||
'--current-font-family',
|
||||
`${fontList.join(', ')}, ${defaultFonts}`
|
||||
);
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 监听配置变化并保存到本地存储
|
||||
watch(
|
||||
() => config.value,
|
||||
(newConfig) => {
|
||||
localStorage.setItem('music-full-config', JSON.stringify(newConfig));
|
||||
},
|
||||
{ deep: true }
|
||||
);
|
||||
|
||||
// 监听滚动事件
|
||||
const handleScroll = () => {
|
||||
if (!lrcSider.value || !config.value.hideCover) return;
|
||||
const { scrollTop } = lrcSider.value.$el;
|
||||
showStickyHeader.value = scrollTop > 100;
|
||||
};
|
||||
|
||||
// 添加滚动监听
|
||||
onMounted(() => {
|
||||
if (lrcSider.value?.$el) {
|
||||
lrcSider.value.$el.addEventListener('scroll', handleScroll);
|
||||
}
|
||||
});
|
||||
|
||||
// 移除滚动监听
|
||||
onBeforeUnmount(() => {
|
||||
if (animationFrame.value) {
|
||||
cancelAnimationFrame(animationFrame.value);
|
||||
}
|
||||
if (lrcSider.value?.$el) {
|
||||
lrcSider.value.$el.removeEventListener('scroll', handleScroll);
|
||||
}
|
||||
});
|
||||
|
||||
// 监听字体大小变化
|
||||
watch(
|
||||
() => config.value.fontSize,
|
||||
(newSize) => {
|
||||
document.documentElement.style.setProperty('--lyric-font-size', `${newSize}px`);
|
||||
}
|
||||
);
|
||||
|
||||
// 监听主题变化
|
||||
watch(
|
||||
() => config.value.theme,
|
||||
(newTheme) => {
|
||||
const newBackground = themeMusic[newTheme] || props.background;
|
||||
setTextColors(newBackground);
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 添加文字间距监听
|
||||
watch(
|
||||
() => config.value.letterSpacing,
|
||||
(newSpacing) => {
|
||||
document.documentElement.style.setProperty('--lyric-letter-spacing', `${newSpacing}px`);
|
||||
}
|
||||
);
|
||||
|
||||
// 添加行高监听
|
||||
watch(
|
||||
() => config.value.lineHeight,
|
||||
(newLineHeight) => {
|
||||
document.documentElement.style.setProperty('--lyric-line-height', newLineHeight.toString());
|
||||
}
|
||||
);
|
||||
|
||||
// 加载保存的配置
|
||||
onMounted(() => {
|
||||
const savedConfig = localStorage.getItem('music-full-config');
|
||||
if (savedConfig) {
|
||||
config.value = { ...config.value, ...JSON.parse(savedConfig) };
|
||||
}
|
||||
if (lrcSider.value?.$el) {
|
||||
lrcSider.value.$el.addEventListener('scroll', handleScroll);
|
||||
}
|
||||
});
|
||||
|
||||
// 添加对 playMusic 的监听
|
||||
watch(playMusic, () => {
|
||||
nextTick(() => {
|
||||
lrcScroll('instant', true);
|
||||
});
|
||||
});
|
||||
|
||||
defineExpose({
|
||||
lrcScroll
|
||||
lrcScroll,
|
||||
config
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -243,7 +527,7 @@ defineExpose({
|
||||
}
|
||||
|
||||
#drawer-target {
|
||||
@apply top-0 left-0 absolute overflow-hidden rounded px-24 flex items-center justify-center w-full h-full pb-8;
|
||||
@apply top-0 left-0 absolute overflow-hidden rounded px-24 flex items-center justify-center w-full h-full py-8;
|
||||
animation-duration: 300ms;
|
||||
|
||||
.music-img {
|
||||
@@ -251,15 +535,26 @@ defineExpose({
|
||||
max-width: 360px;
|
||||
max-height: 360px;
|
||||
.img {
|
||||
@apply rounded-xl w-full h-full shadow-2xl;
|
||||
@apply rounded-xl w-full h-full shadow-2xl;
|
||||
}
|
||||
}
|
||||
|
||||
.music-content {
|
||||
@apply flex flex-col justify-center items-center relative;
|
||||
width: 500px;
|
||||
|
||||
&.center {
|
||||
@apply w-full;
|
||||
.music-lrc {
|
||||
@apply w-full max-w-3xl mx-auto;
|
||||
}
|
||||
.music-lrc-text {
|
||||
@apply text-center;
|
||||
}
|
||||
}
|
||||
|
||||
&-name {
|
||||
@apply font-bold text-xl pb-1 pt-4;
|
||||
@apply font-bold text-2xl pb-1 pt-4;
|
||||
}
|
||||
|
||||
&-singer {
|
||||
@@ -271,15 +566,46 @@ defineExpose({
|
||||
display: none;
|
||||
@apply flex justify-center items-center;
|
||||
}
|
||||
|
||||
.music-lrc-container {
|
||||
padding-top: 30vh;
|
||||
}
|
||||
|
||||
.music-lrc {
|
||||
background-color: inherit;
|
||||
width: 500px;
|
||||
height: 550px;
|
||||
position: relative;
|
||||
mask-image: linear-gradient(to bottom, transparent 0%, black 10%, black 90%, transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(
|
||||
to bottom,
|
||||
transparent 0%,
|
||||
black 10%,
|
||||
black 90%,
|
||||
transparent 100%
|
||||
);
|
||||
|
||||
.music-info-header {
|
||||
@apply mb-8;
|
||||
|
||||
.music-info-name {
|
||||
@apply text-4xl font-bold mb-2;
|
||||
color: var(--text-color-active);
|
||||
}
|
||||
|
||||
.music-info-singer {
|
||||
@apply text-base;
|
||||
color: var(--text-color-primary);
|
||||
}
|
||||
}
|
||||
|
||||
&-text {
|
||||
@apply text-2xl cursor-pointer font-bold px-2 py-4;
|
||||
transition: all 0.3s ease;
|
||||
background-color: transparent;
|
||||
font-size: var(--lyric-font-size, 22px) !important;
|
||||
letter-spacing: var(--lyric-letter-spacing, 0) !important;
|
||||
line-height: var(--lyric-line-height, 2) !important;
|
||||
|
||||
span {
|
||||
background-clip: text !important;
|
||||
@@ -332,4 +658,57 @@ defineExpose({
|
||||
.music-drawer {
|
||||
transition: none; // 移除之前的过渡效果,现在使用 JS 动画
|
||||
}
|
||||
|
||||
// 添加全局字体样式
|
||||
:root {
|
||||
--current-font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
|
||||
'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
#drawer-target {
|
||||
@apply top-0 left-0 absolute overflow-hidden rounded px-24 flex items-center justify-center w-full h-full py-8;
|
||||
animation-duration: 300ms;
|
||||
|
||||
.music-lrc-text {
|
||||
font-family: var(--current-font-family);
|
||||
}
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
opacity: 0.3;
|
||||
transition: opacity 0.3s ease;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.control-btn {
|
||||
@apply w-9 h-9 flex items-center justify-center rounded cursor-pointer transition-all duration-300;
|
||||
background: rgba(142, 142, 142, 0.192);
|
||||
backdrop-filter: blur(12px);
|
||||
|
||||
i {
|
||||
@apply text-xl;
|
||||
color: var(--text-color-active);
|
||||
}
|
||||
|
||||
&.pure-mode {
|
||||
background: transparent;
|
||||
backdrop-filter: none;
|
||||
|
||||
&:not(:hover) {
|
||||
i {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(126, 121, 121, 0.2);
|
||||
i {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<template>
|
||||
<!-- 展开全屏 -->
|
||||
<!-- 底部播放栏 -->
|
||||
|
||||
<div
|
||||
class="music-play-bar"
|
||||
:class="
|
||||
setAnimationClass('animate__bounceInUp') + ' ' + (musicFullVisible ? 'play-bar-opcity' : '')
|
||||
"
|
||||
:class="[
|
||||
setAnimationClass('animate__bounceInUp'),
|
||||
musicFullVisible ? 'play-bar-opcity' : '',
|
||||
musicFullVisible && MusicFullRef?.config?.hidePlayBar
|
||||
? 'animate__animated animate__slideOutDown'
|
||||
: ''
|
||||
]"
|
||||
:style="{
|
||||
color: musicFullVisible
|
||||
? textColors.theme === 'dark'
|
||||
@@ -28,7 +29,7 @@
|
||||
</div>
|
||||
<div class="play-bar-img-wrapper" @click="setMusicFull">
|
||||
<n-image
|
||||
:src="getImgUrl(playMusic?.picUrl, '500y500')"
|
||||
:src="getImgUrl(playMusic?.picUrl, '100y100')"
|
||||
class="play-bar-img"
|
||||
lazy
|
||||
preview-disabled
|
||||
@@ -51,15 +52,22 @@
|
||||
</n-ellipsis>
|
||||
</div>
|
||||
<div class="music-content-name">
|
||||
<n-ellipsis class="text-ellipsis" line-clamp="1">
|
||||
<n-ellipsis
|
||||
class="text-ellipsis"
|
||||
line-clamp="1"
|
||||
:tooltip="{
|
||||
contentStyle: { maxWidth: '600px' },
|
||||
zIndex: 99999
|
||||
}"
|
||||
>
|
||||
<span
|
||||
v-for="(artists, artistsindex) in playMusic.ar || playMusic.song.artists"
|
||||
v-for="(artists, artistsindex) in artistList"
|
||||
:key="artistsindex"
|
||||
>{{ artists.name
|
||||
}}{{
|
||||
artistsindex < (playMusic.ar || playMusic.song.artists).length - 1 ? ' / ' : ''
|
||||
}}</span
|
||||
class="cursor-pointer hover:text-green-500"
|
||||
@click="handleArtistClick(artists.id)"
|
||||
>
|
||||
{{ artists.name }}{{ artistsindex < artistList.length - 1 ? ' / ' : '' }}
|
||||
</span>
|
||||
</n-ellipsis>
|
||||
</div>
|
||||
</div>
|
||||
@@ -140,37 +148,40 @@
|
||||
</n-popover>
|
||||
</div>
|
||||
<!-- 播放音乐 -->
|
||||
<music-full ref="MusicFullRef" v-model:music-full="musicFullVisible" :background="background" />
|
||||
<music-full ref="MusicFullRef" v-model="musicFullVisible" :background="background" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useThrottleFn } from '@vueuse/core';
|
||||
import { useTemplateRef } from 'vue';
|
||||
import { computed, ref, useTemplateRef, watch } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
import {
|
||||
allTime,
|
||||
artistList,
|
||||
isLyricWindowOpen,
|
||||
nowTime,
|
||||
openLyric,
|
||||
playMusic,
|
||||
sound,
|
||||
textColors
|
||||
} from '@/hooks/MusicHook';
|
||||
import { audioService } from '@/services/audioService';
|
||||
import type { SongResult } from '@/type/music';
|
||||
import { getImgUrl, isMobile, secondToMinute, setAnimationClass, isElectron } from '@/utils';
|
||||
import { getImgUrl, isElectron, isMobile, secondToMinute, setAnimationClass } from '@/utils';
|
||||
import { showShortcutToast } from '@/utils/shortcutToast';
|
||||
|
||||
import MusicFull from './MusicFull.vue';
|
||||
|
||||
const store = useStore();
|
||||
|
||||
// 播放的音乐信息
|
||||
const playMusic = computed(() => store.state.playMusic as SongResult);
|
||||
// 是否播放
|
||||
const play = computed(() => store.state.play as boolean);
|
||||
// 播放列表
|
||||
const playList = computed(() => store.state.playList as SongResult[]);
|
||||
|
||||
// 背景颜色
|
||||
const background = ref('#000');
|
||||
|
||||
watch(
|
||||
@@ -181,7 +192,7 @@ watch(
|
||||
{ immediate: true, deep: true }
|
||||
);
|
||||
|
||||
// 使用 useThrottleFn 创建节流版本的 seek 函数
|
||||
// 节流版本的 seek 函数
|
||||
const throttledSeek = useThrottleFn((value: number) => {
|
||||
if (!sound.value) return;
|
||||
sound.value.seek(value);
|
||||
@@ -276,16 +287,34 @@ const MusicFullRef = ref<any>(null);
|
||||
|
||||
// 播放暂停按钮事件
|
||||
const playMusicEvent = async () => {
|
||||
if (play.value) {
|
||||
if (sound.value) {
|
||||
sound.value.pause();
|
||||
try {
|
||||
// 检查是否有有效的音乐对象和 URL
|
||||
if (!playMusic.value?.id || !store.state.playMusicUrl) {
|
||||
console.warn('No valid music or URL available');
|
||||
store.commit('setPlay', playMusic.value);
|
||||
return;
|
||||
}
|
||||
store.commit('setPlayMusic', false);
|
||||
} else {
|
||||
if (sound.value) {
|
||||
sound.value.play();
|
||||
|
||||
if (play.value) {
|
||||
// 暂停播放
|
||||
if (audioService.getCurrentSound()) {
|
||||
audioService.pause();
|
||||
store.commit('setPlayMusic', false);
|
||||
}
|
||||
} else {
|
||||
// 开始播放
|
||||
if (audioService.getCurrentSound()) {
|
||||
// 如果已经有音频实例,直接播放
|
||||
audioService.play();
|
||||
} else {
|
||||
// 如果没有音频实例,重新创建并播放
|
||||
await audioService.play(store.state.playMusicUrl, playMusic.value);
|
||||
}
|
||||
store.commit('setPlayMusic', true);
|
||||
}
|
||||
store.commit('setPlayMusic', true);
|
||||
} catch (error) {
|
||||
console.error('播放出错:', error);
|
||||
store.commit('nextPlay');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -295,6 +324,9 @@ const musicFullVisible = ref(false);
|
||||
const setMusicFull = () => {
|
||||
musicFullVisible.value = !musicFullVisible.value;
|
||||
store.commit('setMusicFull', musicFullVisible.value);
|
||||
if (musicFullVisible.value) {
|
||||
store.commit('setShowArtistDrawer', false);
|
||||
}
|
||||
};
|
||||
|
||||
const palyListRef = useTemplateRef('palyListRef');
|
||||
@@ -322,6 +354,67 @@ const toggleFavorite = async (e: Event) => {
|
||||
const openLyricWindow = () => {
|
||||
openLyric();
|
||||
};
|
||||
|
||||
const handleArtistClick = (id: number) => {
|
||||
musicFullVisible.value = false;
|
||||
store.commit('setCurrentArtistId', id);
|
||||
};
|
||||
|
||||
// 添加全局快捷键处理
|
||||
if (isElectron) {
|
||||
window.electron.ipcRenderer.on('global-shortcut', (_, action: string) => {
|
||||
console.log('action', action);
|
||||
switch (action) {
|
||||
case 'togglePlay':
|
||||
playMusicEvent();
|
||||
showShortcutToast(
|
||||
store.state.play ? '开始播放' : '暂停播放',
|
||||
store.state.play ? 'ri-pause-circle-line' : 'ri-play-circle-line'
|
||||
);
|
||||
break;
|
||||
case 'prevPlay':
|
||||
handlePrev();
|
||||
showShortcutToast('上一首', 'ri-skip-back-line');
|
||||
break;
|
||||
case 'nextPlay':
|
||||
handleNext();
|
||||
showShortcutToast('下一首', 'ri-skip-forward-line');
|
||||
break;
|
||||
case 'volumeUp':
|
||||
if (volumeSlider.value < 100) {
|
||||
volumeSlider.value = Math.min(volumeSlider.value + 10, 100);
|
||||
showShortcutToast(`音量${volumeSlider.value}%`, 'ri-volume-up-line');
|
||||
}
|
||||
break;
|
||||
case 'volumeDown':
|
||||
if (volumeSlider.value > 0) {
|
||||
volumeSlider.value = Math.max(volumeSlider.value - 10, 0);
|
||||
showShortcutToast(`音量${volumeSlider.value}%`, 'ri-volume-down-line');
|
||||
}
|
||||
break;
|
||||
case 'toggleFavorite':
|
||||
toggleFavorite(new Event('click'));
|
||||
showShortcutToast(
|
||||
isFavorite.value ? `已收藏${playMusic.value.name}` : `已取消收藏${playMusic.value.name}`,
|
||||
isFavorite.value ? 'ri-heart-fill' : 'ri-heart-line'
|
||||
);
|
||||
break;
|
||||
default:
|
||||
console.log('未知的快捷键动作:', action);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 监听播放栏显示状态
|
||||
watch(
|
||||
() => MusicFullRef.value?.config?.hidePlayBar,
|
||||
(newVal) => {
|
||||
if (newVal && musicFullVisible.value) {
|
||||
// 使用 animate.css 动画,不需要手动设置样式
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -335,6 +428,16 @@ const openLyricWindow = () => {
|
||||
z-index: 9999;
|
||||
animation-duration: 0.5s !important;
|
||||
|
||||
&.play-bar-opcity {
|
||||
@apply bg-transparent !important;
|
||||
box-shadow: 0 0 20px 5px #0000001d;
|
||||
}
|
||||
|
||||
&.animate__slideOutDown {
|
||||
animation-duration: 0.3s !important;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.music-content {
|
||||
width: 160px;
|
||||
@apply ml-4;
|
||||
@@ -349,11 +452,6 @@ const openLyricWindow = () => {
|
||||
}
|
||||
}
|
||||
|
||||
.play-bar-opcity {
|
||||
@apply bg-transparent !important;
|
||||
box-shadow: 0 0 20px 5px #0000001d;
|
||||
}
|
||||
|
||||
.play-bar-img {
|
||||
@apply w-14 h-14 rounded-2xl;
|
||||
}
|
||||
@@ -379,7 +477,7 @@ const openLyricWindow = () => {
|
||||
|
||||
&-play {
|
||||
@apply flex justify-center items-center w-20 h-12 rounded-full mx-4 transition text-gray-500;
|
||||
@apply bg-gray-100 bg-opacity-60 hover:bg-gray-200;
|
||||
@apply bg-gray-100 bg-opacity-60 dark:bg-gray-800 dark:bg-opacity-60 hover:bg-gray-200;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,8 +73,12 @@
|
||||
<i class="iconfont ri-restart-line"></i>
|
||||
<span>重启</span>
|
||||
</div>
|
||||
<div class="menu-item" @click="toGithubRelease">
|
||||
<div class="menu-item" @click="selectItem('refresh')">
|
||||
<i class="iconfont ri-refresh-line"></i>
|
||||
<span>刷新</span>
|
||||
</div>
|
||||
<div class="menu-item" @click="toGithubRelease">
|
||||
<i class="iconfont ri-github-fill"></i>
|
||||
<span>当前版本</span>
|
||||
<div class="version-info">
|
||||
<span class="version-number">{{ updateInfo.currentVersion }}</span>
|
||||
@@ -96,7 +100,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { onMounted, ref, watchEffect, computed } from 'vue';
|
||||
import { computed, onMounted, ref, watchEffect } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
@@ -212,6 +216,9 @@ const selectItem = async (key: string) => {
|
||||
case 'user':
|
||||
router.push('/user');
|
||||
break;
|
||||
case 'refresh':
|
||||
window.location.reload();
|
||||
break;
|
||||
default:
|
||||
}
|
||||
};
|
||||
@@ -240,7 +247,7 @@ const checkForUpdates = async () => {
|
||||
|
||||
const toGithubRelease = () => {
|
||||
if (updateInfo.value.hasUpdate) {
|
||||
store.commit('setShowUpdateModal', true)
|
||||
store.commit('setShowUpdateModal', true);
|
||||
} else {
|
||||
window.open('https://github.com/algerkong/AlgerMusicPlayer/releases', '_blank');
|
||||
}
|
||||
@@ -286,7 +293,7 @@ const toGithubRelease = () => {
|
||||
}
|
||||
|
||||
.user-popover {
|
||||
@apply min-w-[280px] p-0 rounded-xl overflow-hidden;
|
||||
@apply min-w-[220px] p-0 rounded-xl overflow-hidden;
|
||||
@apply bg-light dark:bg-black;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
|
||||
@@ -303,7 +310,7 @@ const toGithubRelease = () => {
|
||||
@apply py-1;
|
||||
|
||||
.menu-item {
|
||||
@apply flex items-center px-3 py-2 text-sm cursor-pointer;
|
||||
@apply flex items-center px-3 py-1 text-sm cursor-pointer;
|
||||
@apply text-gray-700 dark:text-gray-300;
|
||||
transition: background-color 0.2s;
|
||||
|
||||
@@ -317,7 +324,7 @@ const toGithubRelease = () => {
|
||||
|
||||
.version-info {
|
||||
@apply ml-auto flex items-center;
|
||||
|
||||
|
||||
.version-number {
|
||||
@apply text-xs px-2 py-0.5 rounded;
|
||||
@apply bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300;
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
<div id="title-bar" @mousedown="drag">
|
||||
<div id="title">Alger Music</div>
|
||||
<div id="buttons">
|
||||
<button @click="minimize">
|
||||
<div class="button" @click="minimize">
|
||||
<i class="iconfont icon-minisize"></i>
|
||||
</button>
|
||||
<button @click="close">
|
||||
</div>
|
||||
<div class="button" @click="close">
|
||||
<i class="iconfont icon-close"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { isElectron } from '@/utils';
|
||||
|
||||
const store = useStore();
|
||||
@@ -56,7 +57,7 @@ const handleAction = (action: 'minimize' | 'close') => {
|
||||
closeAction: action
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (action === 'minimize') {
|
||||
window.api.miniTray();
|
||||
} else {
|
||||
@@ -70,13 +71,13 @@ const close = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
const closeAction = store.state.setData.closeAction;
|
||||
|
||||
const { closeAction } = store.state.setData;
|
||||
|
||||
if (closeAction === 'minimize') {
|
||||
window.api.miniTray();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (closeAction === 'close') {
|
||||
window.api.close();
|
||||
return;
|
||||
@@ -98,7 +99,7 @@ const drag = (event: MouseEvent) => {
|
||||
-webkit-app-region: drag;
|
||||
@apply flex justify-between px-6 py-2 select-none relative;
|
||||
@apply text-dark dark:text-white;
|
||||
z-index: 9999999;
|
||||
z-index: 3000;
|
||||
}
|
||||
|
||||
#buttons {
|
||||
@@ -106,7 +107,7 @@ const drag = (event: MouseEvent) => {
|
||||
-webkit-app-region: no-drag;
|
||||
}
|
||||
|
||||
button {
|
||||
.button {
|
||||
@apply text-gray-600 dark:text-gray-400 hover:text-green-500;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'vfonts/Lato.css';
|
||||
import 'vfonts/FiraCode.css';
|
||||
// tailwind css
|
||||
import './index.css';
|
||||
import 'animate.css';
|
||||
import 'remixicon/fonts/remixicon.css';
|
||||
|
||||
import { createApp } from 'vue';
|
||||
|
||||
@@ -1,57 +1,272 @@
|
||||
import { Howl } from 'howler';
|
||||
|
||||
import type { SongResult } from '@/type/music';
|
||||
|
||||
class AudioService {
|
||||
private currentSound: Howl | null = null;
|
||||
|
||||
play(url: string) {
|
||||
if (this.currentSound) {
|
||||
this.currentSound.unload();
|
||||
private currentTrack: SongResult | null = null;
|
||||
|
||||
constructor() {
|
||||
if ('mediaSession' in navigator) {
|
||||
this.initMediaSession();
|
||||
}
|
||||
this.currentSound = null;
|
||||
this.currentSound = new Howl({
|
||||
src: [url],
|
||||
html5: true,
|
||||
autoplay: true,
|
||||
volume: localStorage.getItem('volume')
|
||||
? parseFloat(localStorage.getItem('volume') as string)
|
||||
: 1
|
||||
}
|
||||
|
||||
private initMediaSession() {
|
||||
navigator.mediaSession.setActionHandler('play', () => {
|
||||
this.currentSound?.play();
|
||||
});
|
||||
|
||||
return this.currentSound;
|
||||
navigator.mediaSession.setActionHandler('pause', () => {
|
||||
this.currentSound?.pause();
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('stop', () => {
|
||||
this.stop();
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('seekto', (event) => {
|
||||
if (event.seekTime && this.currentSound) {
|
||||
this.currentSound.seek(event.seekTime);
|
||||
}
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('seekbackward', (event) => {
|
||||
if (this.currentSound) {
|
||||
const currentTime = this.currentSound.seek() as number;
|
||||
this.currentSound.seek(currentTime - (event.seekOffset || 10));
|
||||
}
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('seekforward', (event) => {
|
||||
if (this.currentSound) {
|
||||
const currentTime = this.currentSound.seek() as number;
|
||||
this.currentSound.seek(currentTime + (event.seekOffset || 10));
|
||||
}
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('previoustrack', () => {
|
||||
// 这里需要通过回调通知外部
|
||||
this.emit('previoustrack');
|
||||
});
|
||||
|
||||
navigator.mediaSession.setActionHandler('nexttrack', () => {
|
||||
// 这里需要通过回调通知外部
|
||||
this.emit('nexttrack');
|
||||
});
|
||||
}
|
||||
|
||||
private updateMediaSessionMetadata(track: SongResult) {
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
|
||||
const artists = track.ar ? track.ar.map((a) => a.name) : track.song.artists?.map((a) => a.name);
|
||||
const album = track.al ? track.al.name : track.song.album.name;
|
||||
const artwork = ['96', '128', '192', '256', '384', '512'].map((size) => ({
|
||||
src: `${track.picUrl}?param=${size}y${size}`,
|
||||
type: 'image/jpg',
|
||||
sizes: `${size}x${size}`
|
||||
}));
|
||||
const metadata = {
|
||||
title: track.name || '',
|
||||
artist: artists ? artists.join(',') : '',
|
||||
album: album || '',
|
||||
artwork
|
||||
};
|
||||
|
||||
navigator.mediaSession.metadata = new window.MediaMetadata(metadata);
|
||||
}
|
||||
|
||||
private updateMediaSessionState(isPlaying: boolean) {
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
|
||||
navigator.mediaSession.playbackState = isPlaying ? 'playing' : 'paused';
|
||||
this.updateMediaSessionPositionState();
|
||||
}
|
||||
|
||||
private updateMediaSessionPositionState() {
|
||||
if (!this.currentSound || !('mediaSession' in navigator)) return;
|
||||
|
||||
if ('setPositionState' in navigator.mediaSession) {
|
||||
navigator.mediaSession.setPositionState({
|
||||
duration: this.currentSound.duration(),
|
||||
playbackRate: 1.0,
|
||||
position: this.currentSound.seek() as number
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 事件处理相关
|
||||
private callbacks: { [key: string]: Function[] } = {};
|
||||
|
||||
private emit(event: string, ...args: any[]) {
|
||||
const eventCallbacks = this.callbacks[event];
|
||||
if (eventCallbacks) {
|
||||
eventCallbacks.forEach((callback) => callback(...args));
|
||||
}
|
||||
}
|
||||
|
||||
on(event: string, callback: Function) {
|
||||
if (!this.callbacks[event]) {
|
||||
this.callbacks[event] = [];
|
||||
}
|
||||
this.callbacks[event].push(callback);
|
||||
}
|
||||
|
||||
off(event: string, callback: Function) {
|
||||
const eventCallbacks = this.callbacks[event];
|
||||
if (eventCallbacks) {
|
||||
this.callbacks[event] = eventCallbacks.filter((cb) => cb !== callback);
|
||||
}
|
||||
}
|
||||
|
||||
// 播放控制相关
|
||||
play(url?: string, track?: SongResult): Promise<Howl> {
|
||||
// 如果没有提供新的 URL 和 track,且当前有音频实例,则继续播放
|
||||
if (this.currentSound && !url && !track) {
|
||||
this.currentSound.play();
|
||||
return Promise.resolve(this.currentSound);
|
||||
}
|
||||
|
||||
// 如果没有提供必要的参数,返回错误
|
||||
if (!url || !track) {
|
||||
return Promise.reject(new Error('Missing required parameters: url and track'));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let retryCount = 0;
|
||||
const maxRetries = 1;
|
||||
|
||||
const tryPlay = () => {
|
||||
// 清理现有的音频实例
|
||||
if (this.currentSound) {
|
||||
this.currentSound.unload();
|
||||
this.currentSound = null;
|
||||
}
|
||||
|
||||
try {
|
||||
this.currentTrack = track;
|
||||
this.currentSound = new Howl({
|
||||
src: [url],
|
||||
html5: true,
|
||||
autoplay: true,
|
||||
volume: localStorage.getItem('volume')
|
||||
? parseFloat(localStorage.getItem('volume') as string)
|
||||
: 1,
|
||||
format: ['mp3', 'aac'],
|
||||
onloaderror: (_, error) => {
|
||||
console.error('Audio load error:', error);
|
||||
if (retryCount < maxRetries) {
|
||||
retryCount++;
|
||||
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
|
||||
setTimeout(tryPlay, 1000 * retryCount);
|
||||
} else {
|
||||
reject(new Error('音频加载失败,请尝试切换其他歌曲'));
|
||||
}
|
||||
},
|
||||
onplayerror: (_, error) => {
|
||||
console.error('Audio play error:', error);
|
||||
if (retryCount < maxRetries) {
|
||||
retryCount++;
|
||||
console.log(`Retrying playback (${retryCount}/${maxRetries})...`);
|
||||
setTimeout(tryPlay, 1000 * retryCount);
|
||||
} else {
|
||||
reject(new Error('音频播放失败,请尝试切换其他歌曲'));
|
||||
}
|
||||
},
|
||||
onload: () => {
|
||||
// 音频加载成功后更新媒体会话
|
||||
if (track && this.currentSound) {
|
||||
this.updateMediaSessionMetadata(track);
|
||||
this.updateMediaSessionPositionState();
|
||||
this.emit('load');
|
||||
resolve(this.currentSound);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 设置音频事件监听
|
||||
if (this.currentSound) {
|
||||
this.currentSound.on('play', () => {
|
||||
this.updateMediaSessionState(true);
|
||||
this.emit('play');
|
||||
});
|
||||
|
||||
this.currentSound.on('pause', () => {
|
||||
this.updateMediaSessionState(false);
|
||||
this.emit('pause');
|
||||
});
|
||||
|
||||
this.currentSound.on('end', () => {
|
||||
this.emit('end');
|
||||
});
|
||||
|
||||
this.currentSound.on('seek', () => {
|
||||
this.updateMediaSessionPositionState();
|
||||
this.emit('seek');
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating audio instance:', error);
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
tryPlay();
|
||||
});
|
||||
}
|
||||
|
||||
getCurrentSound() {
|
||||
return this.currentSound;
|
||||
}
|
||||
|
||||
getCurrentTrack() {
|
||||
return this.currentTrack;
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.currentSound) {
|
||||
this.currentSound.stop();
|
||||
this.currentSound.unload();
|
||||
try {
|
||||
this.currentSound.stop();
|
||||
this.currentSound.unload();
|
||||
} catch (error) {
|
||||
console.error('Error stopping audio:', error);
|
||||
}
|
||||
this.currentSound = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 监听播放
|
||||
onPlay(callback: () => void) {
|
||||
if (this.currentSound) {
|
||||
this.currentSound.on('play', callback);
|
||||
this.currentTrack = null;
|
||||
if ('mediaSession' in navigator) {
|
||||
navigator.mediaSession.playbackState = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// 监听暂停
|
||||
onPause(callback: () => void) {
|
||||
setVolume(volume: number) {
|
||||
if (this.currentSound) {
|
||||
this.currentSound.on('pause', callback);
|
||||
this.currentSound.volume(volume);
|
||||
localStorage.setItem('volume', volume.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// 监听结束
|
||||
onEnd(callback: () => void) {
|
||||
seek(time: number) {
|
||||
if (this.currentSound) {
|
||||
this.currentSound.on('end', callback);
|
||||
this.currentSound.seek(time);
|
||||
this.updateMediaSessionPositionState();
|
||||
}
|
||||
}
|
||||
|
||||
pause() {
|
||||
if (this.currentSound) {
|
||||
try {
|
||||
this.currentSound.pause();
|
||||
} catch (error) {
|
||||
console.error('Error pausing audio:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
clearAllListeners() {
|
||||
this.callbacks = {};
|
||||
}
|
||||
}
|
||||
|
||||
export const audioService = new AudioService();
|
||||
|
||||
@@ -1,22 +1,76 @@
|
||||
import { createStore } from 'vuex';
|
||||
|
||||
import setData from '@/../main/set.json';
|
||||
import { getLikedList, likeSong } from '@/api/music';
|
||||
import { useMusicListHook } from '@/hooks/MusicListHook';
|
||||
import homeRouter from '@/router/home';
|
||||
import type { SongResult } from '@/type/music';
|
||||
import { applyTheme, getCurrentTheme, ThemeType } from '@/utils/theme';
|
||||
import { isElectron } from '@/utils';
|
||||
import { likeSong, getLikedList } from '@/api/music';
|
||||
import setData from '@/../main/set.json'
|
||||
import { applyTheme, getCurrentTheme, ThemeType } from '@/utils/theme';
|
||||
|
||||
// 默认设置
|
||||
const defaultSettings = setData;
|
||||
|
||||
function getLocalStorageItem<T>(key: string, defaultValue: T): T {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : defaultValue;
|
||||
function isValidUrl(urlString: string): boolean {
|
||||
try {
|
||||
return Boolean(new URL(urlString));
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface State {
|
||||
function getLocalStorageItem<T>(key: string, defaultValue: T): T {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
if (!item) return defaultValue;
|
||||
|
||||
// 尝试解析 JSON
|
||||
const parsedItem = JSON.parse(item);
|
||||
|
||||
// 对于音乐 URL,检查是否是有效的 URL 格式或本地文件路径
|
||||
if (key === 'currentPlayMusicUrl' && typeof parsedItem === 'string') {
|
||||
if (!parsedItem.startsWith('local://') && !isValidUrl(parsedItem)) {
|
||||
console.warn(`Invalid URL in localStorage for key ${key}, using default value`);
|
||||
localStorage.removeItem(key);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
// 对于播放列表,检查是否是数组且每个项都有必要的字段
|
||||
if (key === 'playList') {
|
||||
if (!Array.isArray(parsedItem)) {
|
||||
console.warn(`Invalid playList format in localStorage, using default value`);
|
||||
localStorage.removeItem(key);
|
||||
return defaultValue;
|
||||
}
|
||||
// 检查每个歌曲对象是否有必要的字段
|
||||
const isValid = parsedItem.every((item) => item && typeof item === 'object' && 'id' in item);
|
||||
if (!isValid) {
|
||||
console.warn(`Invalid song objects in playList, using default value`);
|
||||
localStorage.removeItem(key);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
// 对于当前播放音乐,检查是否是对象且包含必要的字段
|
||||
if (key === 'currentPlayMusic') {
|
||||
if (!parsedItem || typeof parsedItem !== 'object' || !('id' in parsedItem)) {
|
||||
console.warn(`Invalid currentPlayMusic format in localStorage, using default value`);
|
||||
localStorage.removeItem(key);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
return parsedItem;
|
||||
} catch (error) {
|
||||
console.warn(`Error parsing localStorage item for key ${key}:`, error);
|
||||
// 如果解析失败,删除可能损坏的数据
|
||||
localStorage.removeItem(key);
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
export interface State {
|
||||
menus: any[];
|
||||
play: boolean;
|
||||
isPlay: boolean;
|
||||
@@ -35,17 +89,20 @@ interface State {
|
||||
theme: ThemeType;
|
||||
musicFull: boolean;
|
||||
showUpdateModal: boolean;
|
||||
showArtistDrawer: boolean;
|
||||
currentArtistId: number | null;
|
||||
systemFonts: { label: string; value: string }[];
|
||||
}
|
||||
|
||||
const state: State = {
|
||||
menus: homeRouter,
|
||||
play: false,
|
||||
isPlay: false,
|
||||
playMusic: {} as SongResult,
|
||||
playMusicUrl: '',
|
||||
playMusic: getLocalStorageItem('currentPlayMusic', {} as SongResult),
|
||||
playMusicUrl: getLocalStorageItem('currentPlayMusicUrl', ''),
|
||||
user: getLocalStorageItem('user', null),
|
||||
playList: [],
|
||||
playListIndex: 0,
|
||||
playList: getLocalStorageItem('playList', []),
|
||||
playListIndex: getLocalStorageItem('playListIndex', 0),
|
||||
setData: defaultSettings,
|
||||
lyric: {},
|
||||
isMobile: false,
|
||||
@@ -55,7 +112,10 @@ const state: State = {
|
||||
playMode: getLocalStorageItem('playMode', 0),
|
||||
theme: getCurrentTheme(),
|
||||
musicFull: false,
|
||||
showUpdateModal: false
|
||||
showUpdateModal: false,
|
||||
showArtistDrawer: false,
|
||||
currentArtistId: null,
|
||||
systemFonts: [{ label: '系统默认', value: 'system-ui' }]
|
||||
};
|
||||
|
||||
const { handlePlayMusic, nextPlay, prevPlay } = useMusicListHook();
|
||||
@@ -66,12 +126,16 @@ const mutations = {
|
||||
},
|
||||
async setPlay(state: State, playMusic: SongResult) {
|
||||
await handlePlayMusic(state, playMusic);
|
||||
localStorage.setItem('currentPlayMusic', JSON.stringify(state.playMusic));
|
||||
localStorage.setItem('currentPlayMusicUrl', state.playMusicUrl);
|
||||
},
|
||||
setIsPlay(state: State, isPlay: boolean) {
|
||||
state.isPlay = isPlay;
|
||||
localStorage.setItem('isPlaying', isPlay.toString());
|
||||
},
|
||||
setPlayMusic(state: State, play: boolean) {
|
||||
async setPlayMusic(state: State, play: boolean) {
|
||||
state.play = play;
|
||||
localStorage.setItem('isPlaying', play.toString());
|
||||
},
|
||||
setMusicFull(state: State, musicFull: boolean) {
|
||||
state.musicFull = musicFull;
|
||||
@@ -79,6 +143,8 @@ const mutations = {
|
||||
setPlayList(state: State, playList: SongResult[]) {
|
||||
state.playListIndex = playList.findIndex((item) => item.id === state.playMusic.id);
|
||||
state.playList = playList;
|
||||
localStorage.setItem('playList', JSON.stringify(playList));
|
||||
localStorage.setItem('playListIndex', state.playListIndex.toString());
|
||||
},
|
||||
async nextPlay(state: State) {
|
||||
await nextPlay(state);
|
||||
@@ -86,6 +152,27 @@ const mutations = {
|
||||
async prevPlay(state: State) {
|
||||
await prevPlay(state);
|
||||
},
|
||||
// 添加到下一首播放
|
||||
addToNextPlay(state: State, song: SongResult) {
|
||||
const playList = [...state.playList];
|
||||
const currentIndex = state.playListIndex;
|
||||
|
||||
// 检查歌曲是否已经在播放列表中
|
||||
const existingIndex = playList.findIndex((item) => item.id === song.id);
|
||||
if (existingIndex !== -1) {
|
||||
// 如果歌曲已经在列表中,将其移动到当前播放歌曲的下一个位置
|
||||
playList.splice(existingIndex, 1);
|
||||
}
|
||||
|
||||
// 在当前播放歌曲后插入新歌曲
|
||||
playList.splice(currentIndex + 1, 0, song);
|
||||
|
||||
// 更新播放列表
|
||||
state.playList = playList;
|
||||
state.playListIndex = playList.findIndex((item) => item.id === state.playMusic.id);
|
||||
localStorage.setItem('playList', JSON.stringify(playList));
|
||||
localStorage.setItem('playListIndex', state.playListIndex.toString());
|
||||
},
|
||||
setSetData(state: State, setData: any) {
|
||||
state.setData = setData;
|
||||
if (isElectron) {
|
||||
@@ -93,29 +180,43 @@ const mutations = {
|
||||
// 'set',
|
||||
// JSON.parse(JSON.stringify(setData))
|
||||
// );
|
||||
window.electron.ipcRenderer.send('set-store-value', 'set', JSON.parse(JSON.stringify(setData)));
|
||||
window.electron.ipcRenderer.send(
|
||||
'set-store-value',
|
||||
'set',
|
||||
JSON.parse(JSON.stringify(setData))
|
||||
);
|
||||
} else {
|
||||
localStorage.setItem('appSettings', JSON.stringify(setData));
|
||||
}
|
||||
},
|
||||
async addToFavorite(state: State, songId: number) {
|
||||
try {
|
||||
state.user && localStorage.getItem('token') && await likeSong(songId, true);
|
||||
if (!state.favoriteList.includes(songId)) {
|
||||
state.favoriteList = [songId, ...state.favoriteList];
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
// 先添加到本地
|
||||
if (!state.favoriteList.includes(songId)) {
|
||||
state.favoriteList = [songId, ...state.favoriteList];
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
}
|
||||
|
||||
// 如果用户已登录,尝试同步到服务器
|
||||
if (state.user && localStorage.getItem('token')) {
|
||||
try {
|
||||
await likeSong(songId, true);
|
||||
} catch (error) {
|
||||
console.error('同步收藏到服务器失败,但已保存在本地:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('收藏歌曲失败:', error);
|
||||
}
|
||||
},
|
||||
async removeFromFavorite(state: State, songId: number) {
|
||||
try {
|
||||
state.user && localStorage.getItem('token') && await likeSong(songId, false);
|
||||
state.favoriteList = state.favoriteList.filter((id) => id !== songId);
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
} catch (error) {
|
||||
console.error('取消收藏歌曲失败:', error);
|
||||
// 先从本地移除
|
||||
state.favoriteList = state.favoriteList.filter((id) => id !== songId);
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
|
||||
// 如果用户已登录,尝试同步到服务器
|
||||
if (state.user && localStorage.getItem('token')) {
|
||||
try {
|
||||
await likeSong(songId, false);
|
||||
} catch (error) {
|
||||
console.error('同步取消收藏到服务器失败,但已在本地移除:', error);
|
||||
}
|
||||
}
|
||||
},
|
||||
togglePlayMode(state: State) {
|
||||
@@ -127,12 +228,30 @@ const mutations = {
|
||||
applyTheme(state.theme);
|
||||
},
|
||||
setShowUpdateModal(state, value) {
|
||||
state.showUpdateModal = value
|
||||
state.showUpdateModal = value;
|
||||
},
|
||||
logout(state: State) {
|
||||
state.user = null;
|
||||
localStorage.removeItem('user');
|
||||
localStorage.removeItem('token');
|
||||
},
|
||||
setShowArtistDrawer(state, show: boolean) {
|
||||
state.showArtistDrawer = show;
|
||||
if (!show) {
|
||||
state.currentArtistId = null;
|
||||
}
|
||||
},
|
||||
setCurrentArtistId(state, id: number) {
|
||||
state.currentArtistId = id;
|
||||
},
|
||||
setSystemFonts(state, fonts: string[]) {
|
||||
state.systemFonts = [
|
||||
{ label: '系统默认', value: 'system-ui' },
|
||||
...fonts.map((font) => ({
|
||||
label: font,
|
||||
value: font
|
||||
}))
|
||||
];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -140,7 +259,10 @@ const actions = {
|
||||
initializeSettings({ commit }: { commit: any }) {
|
||||
if (isElectron) {
|
||||
const setData = window.electron.ipcRenderer.sendSync('get-store-value', 'set');
|
||||
commit('setSetData', setData || defaultSettings);
|
||||
commit('setSetData', {
|
||||
...defaultSettings,
|
||||
...setData
|
||||
});
|
||||
} else {
|
||||
const savedSettings = localStorage.getItem('appSettings');
|
||||
if (savedSettings) {
|
||||
@@ -157,21 +279,78 @@ const actions = {
|
||||
applyTheme(state.theme);
|
||||
},
|
||||
async initializeFavoriteList({ state }: { state: State }) {
|
||||
try {
|
||||
if(state.user && localStorage.getItem('token')){
|
||||
// 先获取本地收藏列表
|
||||
const localFavoriteList = localStorage.getItem('favoriteList');
|
||||
const localList: number[] = localFavoriteList ? JSON.parse(localFavoriteList) : [];
|
||||
|
||||
// 如果用户已登录,尝试获取服务器收藏列表并合并
|
||||
if (state.user && localStorage.getItem('token')) {
|
||||
try {
|
||||
const res = await getLikedList();
|
||||
if (res.data?.ids) {
|
||||
state.favoriteList = res.data.ids.reverse();
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
}
|
||||
}else{
|
||||
const localFavoriteList = localStorage.getItem('favoriteList');
|
||||
if (localFavoriteList) {
|
||||
state.favoriteList = JSON.parse(localFavoriteList);
|
||||
// 合并本地和服务器的收藏列表,去重
|
||||
const serverList = res.data.ids.reverse();
|
||||
const mergedList = Array.from(new Set([...localList, ...serverList]));
|
||||
state.favoriteList = mergedList;
|
||||
} else {
|
||||
state.favoriteList = localList;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取服务器收藏列表失败,使用本地数据:', error);
|
||||
state.favoriteList = localList;
|
||||
}
|
||||
} else {
|
||||
state.favoriteList = localList;
|
||||
}
|
||||
|
||||
// 更新本地存储
|
||||
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
|
||||
},
|
||||
showArtist({ commit }, id: number) {
|
||||
commit('setCurrentArtistId', id);
|
||||
},
|
||||
async initializeSystemFonts({ commit, state }) {
|
||||
// 如果已经有字体列表(不只是默认字体),则不重复获取
|
||||
if (state.systemFonts.length > 1) return;
|
||||
|
||||
try {
|
||||
const fonts = await window.api.invoke('get-system-fonts');
|
||||
commit('setSystemFonts', fonts);
|
||||
} catch (error) {
|
||||
console.error('获取收藏列表失败:', error);
|
||||
console.error('获取系统字体失败:', error);
|
||||
}
|
||||
},
|
||||
async initializePlayState({ state, commit }: { state: State; commit: any }) {
|
||||
const savedPlayList = getLocalStorageItem('playList', []);
|
||||
const savedPlayMusic = getLocalStorageItem('currentPlayMusic', null);
|
||||
|
||||
if (savedPlayList.length > 0) {
|
||||
commit('setPlayList', savedPlayList);
|
||||
}
|
||||
|
||||
if (savedPlayMusic && Object.keys(savedPlayMusic).length > 0) {
|
||||
// 不直接使用保存的 URL,而是重新获取
|
||||
try {
|
||||
// 使用 handlePlayMusic 来重新获取音乐 URL
|
||||
|
||||
// 根据自动播放设置决定是否恢复播放状态
|
||||
const shouldAutoPlay = state.setData.autoPlay;
|
||||
if (shouldAutoPlay) {
|
||||
await handlePlayMusic(state, savedPlayMusic);
|
||||
}
|
||||
state.play = shouldAutoPlay;
|
||||
state.isPlay = true;
|
||||
} catch (error) {
|
||||
console.error('重新获取音乐链接失败:', error);
|
||||
// 清除无效的播放状态
|
||||
state.play = false;
|
||||
state.isPlay = false;
|
||||
state.playMusic = {} as SongResult;
|
||||
state.playMusicUrl = '';
|
||||
localStorage.removeItem('currentPlayMusic');
|
||||
localStorage.removeItem('currentPlayMusicUrl');
|
||||
localStorage.removeItem('isPlaying');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
110
src/renderer/type/artist.ts
Normal file
110
src/renderer/type/artist.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
export interface IArtistDetail {
|
||||
videoCount: number;
|
||||
vipRights: VipRights;
|
||||
identify: Identify;
|
||||
artist: IArtist;
|
||||
blacklist: boolean;
|
||||
preferShow: number;
|
||||
showPriMsg: boolean;
|
||||
secondaryExpertIdentiy: SecondaryExpertIdentiy[];
|
||||
eventCount: number;
|
||||
user: User;
|
||||
}
|
||||
|
||||
interface User {
|
||||
backgroundUrl: string;
|
||||
birthday: number;
|
||||
detailDescription: string;
|
||||
authenticated: boolean;
|
||||
gender: number;
|
||||
city: number;
|
||||
signature: null;
|
||||
description: string;
|
||||
remarkName: null;
|
||||
shortUserName: string;
|
||||
accountStatus: number;
|
||||
locationStatus: number;
|
||||
avatarImgId: number;
|
||||
defaultAvatar: boolean;
|
||||
province: number;
|
||||
nickname: string;
|
||||
expertTags: null;
|
||||
djStatus: number;
|
||||
avatarUrl: string;
|
||||
accountType: number;
|
||||
authStatus: number;
|
||||
vipType: number;
|
||||
userName: string;
|
||||
followed: boolean;
|
||||
userId: number;
|
||||
lastLoginIP: string;
|
||||
lastLoginTime: number;
|
||||
authenticationTypes: number;
|
||||
mutual: boolean;
|
||||
createTime: number;
|
||||
anchor: boolean;
|
||||
authority: number;
|
||||
backgroundImgId: number;
|
||||
userType: number;
|
||||
experts: null;
|
||||
avatarDetail: AvatarDetail;
|
||||
}
|
||||
|
||||
interface AvatarDetail {
|
||||
userType: number;
|
||||
identityLevel: number;
|
||||
identityIconUrl: string;
|
||||
}
|
||||
|
||||
interface SecondaryExpertIdentiy {
|
||||
expertIdentiyId: number;
|
||||
expertIdentiyName: string;
|
||||
expertIdentiyCount: number;
|
||||
}
|
||||
|
||||
export interface IArtist {
|
||||
id: number;
|
||||
cover: string;
|
||||
avatar: string;
|
||||
name: string;
|
||||
transNames: any[];
|
||||
alias: any[];
|
||||
identities: any[];
|
||||
identifyTag: string[];
|
||||
briefDesc: string;
|
||||
rank: Rank;
|
||||
albumSize: number;
|
||||
musicSize: number;
|
||||
mvSize: number;
|
||||
}
|
||||
|
||||
interface Rank {
|
||||
rank: number;
|
||||
type: number;
|
||||
}
|
||||
|
||||
interface Identify {
|
||||
imageUrl: string;
|
||||
imageDesc: string;
|
||||
actionUrl: string;
|
||||
}
|
||||
|
||||
interface VipRights {
|
||||
rightsInfoDetailDtoList: RightsInfoDetailDtoList[];
|
||||
oldProtocol: boolean;
|
||||
redVipAnnualCount: number;
|
||||
redVipLevel: number;
|
||||
now: number;
|
||||
}
|
||||
|
||||
interface RightsInfoDetailDtoList {
|
||||
vipCode: number;
|
||||
expireTime: number;
|
||||
iconUrl: null;
|
||||
dynamicIconUrl: null;
|
||||
vipLevel: number;
|
||||
signIap: boolean;
|
||||
signDeduct: boolean;
|
||||
signIapDeduct: boolean;
|
||||
sign: boolean;
|
||||
}
|
||||
@@ -160,7 +160,7 @@ interface Album {
|
||||
picId_str: string;
|
||||
}
|
||||
|
||||
interface Artist {
|
||||
export interface Artist {
|
||||
name: string;
|
||||
id: number;
|
||||
picId: number;
|
||||
|
||||
@@ -43,7 +43,7 @@ interface Profile {
|
||||
createTime: number;
|
||||
nickname: string;
|
||||
avatarUrl: string;
|
||||
experts: Experts;
|
||||
experts: any;
|
||||
expertTags?: any;
|
||||
djStatus: number;
|
||||
accountStatus: number;
|
||||
@@ -79,8 +79,6 @@ interface Profile {
|
||||
newFollows: number;
|
||||
}
|
||||
|
||||
interface Experts {}
|
||||
|
||||
interface UserPoint {
|
||||
userId: number;
|
||||
balance: number;
|
||||
|
||||
2
src/renderer/types/electron.d.ts
vendored
2
src/renderer/types/electron.d.ts
vendored
@@ -19,4 +19,4 @@ declare global {
|
||||
interface Window {
|
||||
api: IElectronAPI;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,4 +29,4 @@ export const openDirectory = (path: string | undefined, message: MessageApi, sho
|
||||
} else if (showTip) {
|
||||
message.info('目录不存在');
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { computed } from 'vue';
|
||||
|
||||
import store from '@/store';
|
||||
|
||||
// 设置歌手背景图片
|
||||
@@ -22,6 +23,9 @@ export const setAnimationClass = (type: String) => {
|
||||
};
|
||||
// 设置动画延时
|
||||
export const setAnimationDelay = (index: number = 6, time: number = 50) => {
|
||||
if (store.state.setData?.noAnimate) {
|
||||
return '';
|
||||
}
|
||||
const speed = store.state.setData?.animationSpeed || 1;
|
||||
return `animation-delay:${(index * time) / (speed * 2)}ms`;
|
||||
};
|
||||
@@ -71,4 +75,4 @@ export const isMobile = computed(() => {
|
||||
return !!flag;
|
||||
});
|
||||
|
||||
export const isElectron = (window as any).electron !== undefined;
|
||||
export const isElectron = (window as any).electron !== undefined;
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
import tinycolor from 'tinycolor2';
|
||||
|
||||
interface IColor {
|
||||
backgroundColor: string;
|
||||
primaryColor: string;
|
||||
}
|
||||
|
||||
interface ITextColors {
|
||||
primary: string;
|
||||
active: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
export const getImageLinearBackground = async (imageSrc: string): Promise<IColor> => {
|
||||
try {
|
||||
const primaryColor = await getImagePrimaryColor(imageSrc);
|
||||
@@ -96,126 +105,43 @@ const getAverageColor = (data: Uint8ClampedArray): number[] => {
|
||||
};
|
||||
|
||||
const generateGradientBackground = (color: string): string => {
|
||||
const [r, g, b] = color.match(/\d+/g)?.map(Number) || [0, 0, 0];
|
||||
const [h, s, l] = rgbToHsl(r, g, b);
|
||||
const tc = tinycolor(color);
|
||||
const hsl = tc.toHsl();
|
||||
|
||||
// 增加亮度和暗度的差异
|
||||
const lightL = Math.min(l + 0.2, 0.95);
|
||||
const darkL = Math.max(l - 0.3, 0.05);
|
||||
const midL = (lightL + darkL) / 2;
|
||||
const lightColor = tinycolor({ h: hsl.h, s: hsl.s * 0.8, l: Math.min(hsl.l + 0.2, 0.95) });
|
||||
const midColor = tinycolor({ h: hsl.h, s: hsl.s, l: hsl.l });
|
||||
const darkColor = tinycolor({
|
||||
h: hsl.h,
|
||||
s: Math.min(hsl.s * 1.2, 1),
|
||||
l: Math.max(hsl.l - 0.3, 0.05)
|
||||
});
|
||||
|
||||
// 调整饱和度以增强效果
|
||||
const lightS = Math.min(s * 0.8, 1);
|
||||
const darkS = Math.min(s * 1.2, 1);
|
||||
|
||||
const [lightR, lightG, lightB] = hslToRgb(h, lightS, lightL);
|
||||
const [midR, midG, midB] = hslToRgb(h, s, midL);
|
||||
const [darkR, darkG, darkB] = hslToRgb(h, darkS, darkL);
|
||||
|
||||
const lightColor = `rgb(${lightR}, ${lightG}, ${lightB})`;
|
||||
const midColor = `rgb(${midR}, ${midG}, ${midB})`;
|
||||
const darkColor = `rgb(${darkR}, ${darkG}, ${darkB})`;
|
||||
|
||||
// 使用三个颜色点创建更丰富的渐变
|
||||
return `linear-gradient(to bottom, ${lightColor} 0%, ${midColor} 50%, ${darkColor} 100%)`;
|
||||
};
|
||||
|
||||
// Helper functions (unchanged)
|
||||
function rgbToHsl(r: number, g: number, b: number): [number, number, number] {
|
||||
r /= 255;
|
||||
g /= 255;
|
||||
b /= 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h = 0;
|
||||
let s;
|
||||
const l = (max + min) / 2;
|
||||
|
||||
if (max === min) {
|
||||
h = s = 0;
|
||||
} else {
|
||||
const d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
switch (max) {
|
||||
case r:
|
||||
h = (g - b) / d + (g < b ? 6 : 0);
|
||||
break;
|
||||
case g:
|
||||
h = (b - r) / d + 2;
|
||||
break;
|
||||
case b:
|
||||
h = (r - g) / d + 4;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
h /= 6;
|
||||
}
|
||||
|
||||
return [h, s, l];
|
||||
}
|
||||
|
||||
function hslToRgb(h: number, s: number, l: number): [number, number, number] {
|
||||
let r;
|
||||
let g;
|
||||
let b;
|
||||
|
||||
if (s === 0) {
|
||||
r = g = b = l;
|
||||
} else {
|
||||
const hue2rgb = (p: number, q: number, t: number) => {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
};
|
||||
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
r = hue2rgb(p, q, h + 1 / 3);
|
||||
g = hue2rgb(p, q, h);
|
||||
b = hue2rgb(p, q, h - 1 / 3);
|
||||
}
|
||||
|
||||
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
|
||||
}
|
||||
|
||||
// 添加新的接口
|
||||
interface ITextColors {
|
||||
primary: string;
|
||||
active: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
// 添加新的函数
|
||||
export const calculateBrightness = (r: number, g: number, b: number): number => {
|
||||
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
|
||||
return `linear-gradient(to bottom, ${lightColor.toRgbString()} 0%, ${midColor.toRgbString()} 50%, ${darkColor.toRgbString()} 100%)`;
|
||||
};
|
||||
|
||||
export const parseGradient = (gradientStr: string) => {
|
||||
const matches = gradientStr.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/g);
|
||||
if (!matches) return [];
|
||||
return matches.map((rgb) => {
|
||||
const [r, g, b] = rgb.match(/\d+/g)!.map(Number);
|
||||
return { r, g, b };
|
||||
if (!gradientStr) return [];
|
||||
|
||||
// 处理非渐变色
|
||||
if (!gradientStr.startsWith('linear-gradient')) {
|
||||
const color = tinycolor(gradientStr);
|
||||
if (color.isValid()) {
|
||||
const rgb = color.toRgb();
|
||||
return [{ r: rgb.r, g: rgb.g, b: rgb.b }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// 处理渐变色,支持 rgb、rgba 和十六进制颜色
|
||||
const colorMatches = gradientStr.match(/(?:(?:rgb|rgba)\([^)]+\)|#[0-9a-fA-F]{3,8})/g) || [];
|
||||
return colorMatches.map((color) => {
|
||||
const tc = tinycolor(color);
|
||||
const rgb = tc.toRgb();
|
||||
return { r: rgb.r, g: rgb.g, b: rgb.b };
|
||||
});
|
||||
};
|
||||
|
||||
export const interpolateRGB = (start: number, end: number, progress: number) => {
|
||||
return Math.round(start + (end - start) * progress);
|
||||
};
|
||||
|
||||
export const createGradientString = (
|
||||
colors: { r: number; g: number; b: number }[],
|
||||
percentages = [0, 50, 100]
|
||||
) => {
|
||||
return `linear-gradient(to bottom, ${colors
|
||||
.map((color, i) => `rgb(${color.r}, ${color.g}, ${color.b}) ${percentages[i]}%`)
|
||||
.join(', ')})`;
|
||||
};
|
||||
|
||||
export const getTextColors = (gradient: string = ''): ITextColors => {
|
||||
const defaultColors = {
|
||||
primary: 'rgba(255, 255, 255, 0.54)',
|
||||
@@ -228,9 +154,9 @@ export const getTextColors = (gradient: string = ''): ITextColors => {
|
||||
const colors = parseGradient(gradient);
|
||||
if (!colors.length) return defaultColors;
|
||||
|
||||
const mainColor = colors[1] || colors[0];
|
||||
const brightness = calculateBrightness(mainColor.r, mainColor.g, mainColor.b);
|
||||
const isDark = brightness > 0.6;
|
||||
const mainColor = colors.length === 1 ? colors[0] : colors[1] || colors[0];
|
||||
const tc = tinycolor(mainColor);
|
||||
const isDark = tc.getBrightness() > 155; // tinycolor 的亮度范围是 0-255
|
||||
|
||||
return {
|
||||
primary: isDark ? 'rgba(0, 0, 0, 0.54)' : 'rgba(255, 255, 255, 0.54)',
|
||||
@@ -243,35 +169,130 @@ export const getHoverBackgroundColor = (isDark: boolean): string => {
|
||||
return isDark ? 'rgba(0, 0, 0, 0.08)' : 'rgba(255, 255, 255, 0.08)';
|
||||
};
|
||||
|
||||
export const animateGradient = (
|
||||
oldGradient: string,
|
||||
newGradient: string,
|
||||
onUpdate: (gradient: string) => void,
|
||||
duration = 1000
|
||||
) => {
|
||||
const startColors = parseGradient(oldGradient);
|
||||
const endColors = parseGradient(newGradient);
|
||||
if (startColors.length !== endColors.length) return null;
|
||||
export const animateGradient = (() => {
|
||||
let currentAnimation: number | null = null;
|
||||
let isAnimating = false;
|
||||
let lastProgress = 0;
|
||||
|
||||
const startTime = performance.now();
|
||||
|
||||
const animate = (currentTime: number) => {
|
||||
const elapsed = currentTime - startTime;
|
||||
const progress = Math.min(elapsed / duration, 1);
|
||||
|
||||
const currentColors = startColors.map((startColor, i) => ({
|
||||
r: interpolateRGB(startColor.r, endColors[i].r, progress),
|
||||
g: interpolateRGB(startColor.g, endColors[i].g, progress),
|
||||
b: interpolateRGB(startColor.b, endColors[i].b, progress)
|
||||
}));
|
||||
|
||||
onUpdate(createGradientString(currentColors));
|
||||
|
||||
if (progress < 1) {
|
||||
return requestAnimationFrame(animate);
|
||||
}
|
||||
return null;
|
||||
const validateColors = (colors: ReturnType<typeof parseGradient>) => {
|
||||
return colors.every(
|
||||
(color) =>
|
||||
typeof color.r === 'number' &&
|
||||
typeof color.g === 'number' &&
|
||||
typeof color.b === 'number' &&
|
||||
!Number.isNaN(color.r) &&
|
||||
!Number.isNaN(color.g) &&
|
||||
!Number.isNaN(color.b)
|
||||
);
|
||||
};
|
||||
|
||||
return requestAnimationFrame(animate);
|
||||
const easeInOutCubic = (x: number): number => {
|
||||
return x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2;
|
||||
};
|
||||
|
||||
const animate = (
|
||||
oldGradient: string,
|
||||
newGradient: string,
|
||||
onUpdate: (gradient: string) => void,
|
||||
duration = 300
|
||||
) => {
|
||||
// 如果新旧渐变色相同,不执行动画
|
||||
if (oldGradient === newGradient) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 如果正在动画中,取消当前动画
|
||||
if (currentAnimation !== null) {
|
||||
cancelAnimationFrame(currentAnimation);
|
||||
currentAnimation = null;
|
||||
}
|
||||
|
||||
// 解析颜色
|
||||
const startColors = parseGradient(oldGradient);
|
||||
const endColors = parseGradient(newGradient);
|
||||
|
||||
// 验证颜色数组
|
||||
if (
|
||||
!startColors.length ||
|
||||
!endColors.length ||
|
||||
!validateColors(startColors) ||
|
||||
!validateColors(endColors)
|
||||
) {
|
||||
console.warn('Invalid color values detected');
|
||||
onUpdate(newGradient); // 直接更新到目标颜色
|
||||
return null;
|
||||
}
|
||||
|
||||
// 如果颜色数量不匹配,直接更新到目标颜色
|
||||
if (startColors.length !== endColors.length) {
|
||||
onUpdate(newGradient);
|
||||
return null;
|
||||
}
|
||||
|
||||
isAnimating = true;
|
||||
const startTime = performance.now();
|
||||
|
||||
const animateFrame = (currentTime: number) => {
|
||||
if (!isAnimating) return null;
|
||||
|
||||
const elapsed = currentTime - startTime;
|
||||
const rawProgress = Math.min(elapsed / duration, 1);
|
||||
// 使用缓动函数使动画更平滑
|
||||
const progress = easeInOutCubic(rawProgress);
|
||||
|
||||
try {
|
||||
// 使用上一帧的进度来平滑过渡
|
||||
const effectiveProgress = lastProgress + (progress - lastProgress) * 0.6;
|
||||
lastProgress = effectiveProgress;
|
||||
|
||||
const currentColors = startColors.map((startColor, i) => {
|
||||
const start = tinycolor(startColor);
|
||||
const end = tinycolor(endColors[i]);
|
||||
return tinycolor.mix(start, end, effectiveProgress * 100);
|
||||
});
|
||||
|
||||
const gradientString = createGradientString(
|
||||
currentColors.map((c) => {
|
||||
const rgb = c.toRgb();
|
||||
return { r: rgb.r, g: rgb.g, b: rgb.b };
|
||||
})
|
||||
);
|
||||
|
||||
onUpdate(gradientString);
|
||||
|
||||
if (rawProgress < 1) {
|
||||
currentAnimation = requestAnimationFrame(animateFrame);
|
||||
return currentAnimation;
|
||||
}
|
||||
// 确保最终颜色正确
|
||||
onUpdate(newGradient);
|
||||
isAnimating = false;
|
||||
currentAnimation = null;
|
||||
lastProgress = 0;
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('Animation error:', error);
|
||||
onUpdate(newGradient);
|
||||
isAnimating = false;
|
||||
currentAnimation = null;
|
||||
lastProgress = 0;
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
currentAnimation = requestAnimationFrame(animateFrame);
|
||||
return currentAnimation;
|
||||
};
|
||||
|
||||
// 使用更短的防抖时间
|
||||
return useDebounceFn(animate, 50);
|
||||
})();
|
||||
|
||||
export const createGradientString = (
|
||||
colors: { r: number; g: number; b: number }[],
|
||||
percentages = [0, 50, 100]
|
||||
) => {
|
||||
return `linear-gradient(to bottom, ${colors
|
||||
.map((color, i) => `rgb(${color.r}, ${color.g}, ${color.b}) ${percentages[i]}%`)
|
||||
.join(', ')})`;
|
||||
};
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
import axios, { InternalAxiosRequestConfig } from 'axios';
|
||||
import { isElectron } from '.';
|
||||
import { createDiscreteApi } from 'naive-ui';
|
||||
|
||||
import store from '@/store';
|
||||
import { createDiscreteApi } from 'naive-ui'
|
||||
|
||||
import { isElectron } from '.';
|
||||
|
||||
const { notification } = createDiscreteApi(
|
||||
['notification']
|
||||
)
|
||||
const { notification } = createDiscreteApi(['notification']);
|
||||
|
||||
let setData: any = null;
|
||||
const getSetData = ()=>{
|
||||
const getSetData = () => {
|
||||
if (window.electron) {
|
||||
setData = window.electron.ipcRenderer.sendSync('get-store-value', 'set');
|
||||
}
|
||||
}
|
||||
getSetData()
|
||||
};
|
||||
getSetData();
|
||||
// 扩展请求配置接口
|
||||
interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
|
||||
retryCount?: number;
|
||||
}
|
||||
|
||||
const baseURL = window.electron ? `http://127.0.0.1:${setData?.musicApiPort}` : import.meta.env.VITE_API;
|
||||
const baseURL = window.electron
|
||||
? `http://127.0.0.1:${setData?.musicApiPort}`
|
||||
: import.meta.env.VITE_API;
|
||||
|
||||
const request = axios.create({
|
||||
baseURL,
|
||||
@@ -43,26 +44,21 @@ request.interceptors.request.use(
|
||||
|
||||
// 在请求发送之前做一些处理
|
||||
// 在get请求params中添加timestamp
|
||||
if (config.method === 'get') {
|
||||
config.params = {
|
||||
...config.params,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.params.cookie = token + ' os=pc;';
|
||||
}else{
|
||||
config.params.cookie = 'os=pc;';
|
||||
}
|
||||
config.params = {
|
||||
...config.params,
|
||||
timestamp: Date.now()
|
||||
};
|
||||
const token = localStorage.getItem('token');
|
||||
if (token) {
|
||||
config.params.cookie = `${token} os=pc;`;
|
||||
}
|
||||
|
||||
if(isElectron){
|
||||
const proxyConfig = setData?.proxyConfig
|
||||
if (isElectron) {
|
||||
const proxyConfig = setData?.proxyConfig;
|
||||
if (proxyConfig?.enable && ['http', 'https'].includes(proxyConfig?.protocol)) {
|
||||
config.params.proxy = `${proxyConfig.protocol}://${proxyConfig.host}:${proxyConfig.port}`
|
||||
config.params.proxy = `${proxyConfig.protocol}://${proxyConfig.host}:${proxyConfig.port}`;
|
||||
}
|
||||
if(setData.enableRealIP && setData.realIP){
|
||||
config.params.realIP = setData.realIP
|
||||
if (setData.enableRealIP && setData.realIP) {
|
||||
config.params.realIP = setData.realIP;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +76,7 @@ request.interceptors.response.use(
|
||||
return response;
|
||||
},
|
||||
async (error) => {
|
||||
console.log('error',error)
|
||||
console.log('error', error);
|
||||
const config = error.config as CustomAxiosRequestConfig;
|
||||
|
||||
// 如果没有配置,直接返回错误
|
||||
@@ -102,7 +98,7 @@ request.interceptors.response.use(
|
||||
meta: '请重新登录',
|
||||
duration: 2500,
|
||||
keepAliveOnHover: true
|
||||
})
|
||||
});
|
||||
|
||||
// 延迟重试
|
||||
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
|
||||
|
||||
40
src/renderer/utils/shortcutToast.ts
Normal file
40
src/renderer/utils/shortcutToast.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { createVNode, render } from 'vue';
|
||||
|
||||
import ShortcutToast from '@/components/ShortcutToast.vue';
|
||||
|
||||
let container: HTMLDivElement | null = null;
|
||||
let toastInstance: any = null;
|
||||
|
||||
export function showShortcutToast(message: string, iconName: string) {
|
||||
// 如果容器不存在,创建一个新的容器
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
// 如果已经有实例,先销毁它
|
||||
if (toastInstance) {
|
||||
render(null, container);
|
||||
toastInstance = null;
|
||||
}
|
||||
|
||||
// 创建新的 toast 实例
|
||||
const vnode = createVNode(ShortcutToast, {
|
||||
onDestroy: () => {
|
||||
if (container) {
|
||||
render(null, container);
|
||||
document.body.removeChild(container);
|
||||
container = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 渲染 toast
|
||||
render(vnode, container);
|
||||
toastInstance = vnode.component?.exposed;
|
||||
|
||||
// 显示 toast
|
||||
if (toastInstance) {
|
||||
toastInstance.show(message, iconName);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import axios from 'axios';
|
||||
import config from '../../../package.json';
|
||||
import { useDateFormat } from '@vueuse/core';
|
||||
import axios from 'axios';
|
||||
|
||||
import config from '../../../package.json';
|
||||
|
||||
interface GithubReleaseInfo {
|
||||
tag_name: string;
|
||||
body: string;
|
||||
@@ -39,15 +41,15 @@ export const getLatestReleaseInfo = async (): Promise<GithubReleaseInfo | null>
|
||||
const apiUrls = [
|
||||
// 原始地址
|
||||
'https://api.github.com/repos/algerkong/AlgerMusicPlayer/releases/latest',
|
||||
|
||||
|
||||
// 使用 ghproxy.com 代理
|
||||
'https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/package.json',
|
||||
|
||||
'https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/package.json'
|
||||
|
||||
// 使用 gitee 镜像(如果有的话)
|
||||
// 'https://gitee.com/api/v5/repos/[用户名]/AlgerMusicPlayer/releases/latest'
|
||||
];
|
||||
if (token) {
|
||||
headers['Authorization'] = `token ${token}`;
|
||||
headers['Authorization'] = `token ${token}`;
|
||||
}
|
||||
|
||||
for (const url of apiUrls) {
|
||||
@@ -58,7 +60,11 @@ export const getLatestReleaseInfo = async (): Promise<GithubReleaseInfo | null>
|
||||
// 如果是 package.json,直接读取版本号
|
||||
return {
|
||||
tag_name: response.data.version,
|
||||
body:(await axios.get('https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/CHANGELOG.md')).data,
|
||||
body: (
|
||||
await axios.get(
|
||||
'https://www.ghproxy.cn/https://raw.githubusercontent.com/algerkong/AlgerMusicPlayer/dev_electron/CHANGELOG.md'
|
||||
)
|
||||
).data,
|
||||
html_url: 'https://github.com/algerkong/AlgerMusicPlayer/releases/latest',
|
||||
assets: []
|
||||
} as unknown as GithubReleaseInfo;
|
||||
@@ -86,10 +92,12 @@ export const formatDate = (dateStr: string): string => {
|
||||
/**
|
||||
* 检查更新
|
||||
*/
|
||||
export const checkUpdate = async (currentVersion: string = config.version): Promise<UpdateResult | null> => {
|
||||
export const checkUpdate = async (
|
||||
currentVersion: string = config.version
|
||||
): Promise<UpdateResult | null> => {
|
||||
try {
|
||||
const releaseInfo = await getLatestReleaseInfo();
|
||||
console.log('releaseInfo',releaseInfo)
|
||||
console.log('releaseInfo', releaseInfo);
|
||||
if (!releaseInfo) {
|
||||
return null;
|
||||
}
|
||||
@@ -98,8 +106,8 @@ export const checkUpdate = async (currentVersion: string = config.version): Prom
|
||||
if (latestVersion === currentVersion) {
|
||||
return null;
|
||||
}
|
||||
console.log('latestVersion',latestVersion)
|
||||
console.log('currentVersion',currentVersion)
|
||||
console.log('latestVersion', latestVersion);
|
||||
console.log('currentVersion', currentVersion);
|
||||
|
||||
return {
|
||||
hasUpdate: true,
|
||||
@@ -109,7 +117,7 @@ export const checkUpdate = async (currentVersion: string = config.version): Prom
|
||||
tag_name: latestVersion,
|
||||
body: `## 更新内容\n\n- 版本: ${latestVersion}\n${releaseInfo.body}`,
|
||||
html_url: releaseInfo.html_url,
|
||||
assets: releaseInfo.assets.map(asset => ({
|
||||
assets: releaseInfo.assets.map((asset) => ({
|
||||
browser_download_url: asset.browser_download_url,
|
||||
name: asset.name
|
||||
}))
|
||||
@@ -119,4 +127,4 @@ export const checkUpdate = async (currentVersion: string = config.version): Prom
|
||||
console.error('检查更新失败:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,8 +1,51 @@
|
||||
<template>
|
||||
<div v-if="isComponent ? favoriteSongs.length : true" class="favorite-page">
|
||||
<div class="favorite-header" :class="setAnimationClass('animate__fadeInLeft')">
|
||||
<h2>我的收藏</h2>
|
||||
<div class="favorite-count">共 {{ favoriteList.length }} 首</div>
|
||||
<div class="favorite-header-left">
|
||||
<h2>我的收藏</h2>
|
||||
<div class="favorite-count">共 {{ favoriteList.length }} 首</div>
|
||||
</div>
|
||||
<div v-if="!isComponent && isElectron" class="favorite-header-right">
|
||||
<n-button
|
||||
v-if="!isSelecting"
|
||||
secondary
|
||||
type="primary"
|
||||
size="small"
|
||||
class="select-btn"
|
||||
@click="startSelect"
|
||||
>
|
||||
<template #icon>
|
||||
<i class="iconfont ri-checkbox-multiple-line"></i>
|
||||
</template>
|
||||
批量下载
|
||||
</n-button>
|
||||
<div v-else class="select-controls">
|
||||
<n-checkbox
|
||||
class="select-all-checkbox"
|
||||
:checked="isAllSelected"
|
||||
:indeterminate="isIndeterminate"
|
||||
@update:checked="handleSelectAll"
|
||||
>
|
||||
全选
|
||||
</n-checkbox>
|
||||
<n-button-group class="operation-btns">
|
||||
<n-button
|
||||
type="primary"
|
||||
size="small"
|
||||
:loading="isDownloading"
|
||||
:disabled="selectedSongs.length === 0"
|
||||
class="download-btn"
|
||||
@click="handleBatchDownload"
|
||||
>
|
||||
<template #icon>
|
||||
<i class="iconfont ri-download-line"></i>
|
||||
</template>
|
||||
下载 ({{ selectedSongs.length }})
|
||||
</n-button>
|
||||
<n-button size="small" class="cancel-btn" @click="cancelSelect"> 取消 </n-button>
|
||||
</n-button-group>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="favorite-main" :class="setAnimationClass('animate__bounceInRight')">
|
||||
<n-scrollbar ref="scrollbarRef" class="favorite-content" @scroll="handleScroll">
|
||||
@@ -17,7 +60,10 @@
|
||||
:favorite="!isComponent"
|
||||
:class="setAnimationClass('animate__bounceInLeft')"
|
||||
:style="getItemAnimationDelay(index)"
|
||||
:selectable="isSelecting"
|
||||
:selected="selectedSongs.includes(song.id)"
|
||||
@play="handlePlay"
|
||||
@select="handleSelect"
|
||||
/>
|
||||
<div v-if="isComponent" class="favorite-list-more text-center">
|
||||
<n-button text type="primary" @click="handleMore">查看更多</n-button>
|
||||
@@ -35,26 +81,134 @@
|
||||
</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';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
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();
|
||||
const favoriteList = computed(() => store.state.favoriteList);
|
||||
const favoriteSongs = ref<SongResult[]>([]);
|
||||
const loading = ref(false);
|
||||
const noMore = ref(false);
|
||||
const scrollbarRef = ref();
|
||||
|
||||
// 多选相关
|
||||
const isSelecting = ref(false);
|
||||
const selectedSongs = ref<number[]>([]);
|
||||
const isDownloading = ref(false);
|
||||
|
||||
// 开始多选
|
||||
const startSelect = () => {
|
||||
isSelecting.value = true;
|
||||
selectedSongs.value = [];
|
||||
};
|
||||
|
||||
// 取消多选
|
||||
const cancelSelect = () => {
|
||||
isSelecting.value = false;
|
||||
selectedSongs.value = [];
|
||||
};
|
||||
|
||||
// 处理选择
|
||||
const handleSelect = (songId: number, selected: boolean) => {
|
||||
if (selected) {
|
||||
selectedSongs.value.push(songId);
|
||||
} else {
|
||||
selectedSongs.value = selectedSongs.value.filter((id) => id !== songId);
|
||||
}
|
||||
};
|
||||
|
||||
// 批量下载
|
||||
const handleBatchDownload = async () => {
|
||||
if (isDownloading.value) {
|
||||
message.warning('正在下载中,请稍候...');
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedSongs.value.length === 0) {
|
||||
message.warning('请先选择要下载的歌曲');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isDownloading.value = true;
|
||||
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 {
|
||||
failCount++;
|
||||
}
|
||||
|
||||
// 当所有下载完成时
|
||||
if (successCount + failCount === selectedSongs.value.length) {
|
||||
isDownloading.value = false;
|
||||
message.success(`下载完成`);
|
||||
cancelSelect();
|
||||
}
|
||||
});
|
||||
|
||||
// 获取选中歌曲的信息
|
||||
const selectedSongsList = selectedSongs.value
|
||||
.map((songId) => favoriteSongs.value.find((s) => s.id === songId))
|
||||
.filter((song) => song) as SongResult[];
|
||||
|
||||
// 并行获取所有歌曲的下载链接
|
||||
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++;
|
||||
return;
|
||||
}
|
||||
|
||||
window.electron.ipcRenderer.send('download-music', {
|
||||
url,
|
||||
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('下载失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 无限滚动相关
|
||||
const pageSize = 16;
|
||||
const currentPage = ref(1);
|
||||
|
||||
|
||||
const props = defineProps({
|
||||
isComponent: {
|
||||
type: Boolean,
|
||||
@@ -144,7 +298,27 @@ const getItemAnimationDelay = (index: number) => {
|
||||
|
||||
const router = useRouter();
|
||||
const handleMore = () => {
|
||||
router.push('/favorite');
|
||||
router.push('/history');
|
||||
};
|
||||
|
||||
// 全选相关
|
||||
const isAllSelected = computed(() => {
|
||||
return (
|
||||
favoriteSongs.value.length > 0 && selectedSongs.value.length === favoriteSongs.value.length
|
||||
);
|
||||
});
|
||||
|
||||
const isIndeterminate = computed(() => {
|
||||
return selectedSongs.value.length > 0 && selectedSongs.value.length < favoriteSongs.value.length;
|
||||
});
|
||||
|
||||
// 处理全选/取消全选
|
||||
const handleSelectAll = (checked: boolean) => {
|
||||
if (checked) {
|
||||
selectedSongs.value = favoriteSongs.value.map((song) => song.id);
|
||||
} else {
|
||||
selectedSongs.value = [];
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
@@ -154,15 +328,68 @@ const handleMore = () => {
|
||||
@apply bg-light dark:bg-black;
|
||||
|
||||
.favorite-header {
|
||||
@apply flex items-center justify-between flex-shrink-0 px-4;
|
||||
@apply flex items-center justify-between flex-shrink-0 px-4 pb-2;
|
||||
|
||||
h2 {
|
||||
@apply text-xl font-bold pb-2;
|
||||
@apply text-gray-900 dark:text-white;
|
||||
&-left {
|
||||
@apply flex items-center gap-4;
|
||||
|
||||
h2 {
|
||||
@apply text-xl font-bold;
|
||||
@apply text-gray-900 dark:text-white;
|
||||
}
|
||||
|
||||
.favorite-count {
|
||||
@apply text-gray-500 dark:text-gray-400 text-sm;
|
||||
}
|
||||
}
|
||||
|
||||
.favorite-count {
|
||||
@apply text-gray-500 dark:text-gray-400 text-sm;
|
||||
&-right {
|
||||
@apply flex items-center;
|
||||
|
||||
.select-btn {
|
||||
@apply rounded-full px-4 h-8;
|
||||
@apply transition-all duration-300 ease-in-out;
|
||||
@apply hover:bg-primary hover:text-white;
|
||||
@apply dark:border-gray-600;
|
||||
|
||||
.iconfont {
|
||||
@apply mr-1 text-lg;
|
||||
}
|
||||
}
|
||||
|
||||
.select-controls {
|
||||
@apply flex items-center gap-3;
|
||||
@apply bg-gray-50 dark:bg-gray-800;
|
||||
@apply rounded-full px-3 py-1;
|
||||
@apply border border-gray-200 dark:border-gray-700;
|
||||
@apply transition-all duration-300;
|
||||
|
||||
.select-all-checkbox {
|
||||
@apply text-sm text-gray-900 dark:text-gray-200;
|
||||
}
|
||||
|
||||
.operation-btns {
|
||||
@apply flex items-center gap-2 ml-2;
|
||||
|
||||
.download-btn {
|
||||
@apply rounded-full px-4 h-7;
|
||||
@apply bg-primary text-white;
|
||||
@apply hover:bg-primary-dark;
|
||||
@apply disabled:opacity-50 disabled:cursor-not-allowed;
|
||||
|
||||
.iconfont {
|
||||
@apply mr-1 text-lg;
|
||||
}
|
||||
}
|
||||
|
||||
.cancel-btn {
|
||||
@apply rounded-full px-4 h-7;
|
||||
@apply text-gray-600 dark:text-gray-300;
|
||||
@apply hover:bg-gray-100 dark:hover:bg-gray-700;
|
||||
@apply border-gray-300 dark:border-gray-600;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,10 +34,10 @@ import { onMounted, ref } from 'vue';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { getMusicDetail } from '@/api/music';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
|
||||
import type { SongResult } from '@/type/music';
|
||||
import { setAnimationClass, setAnimationDelay } from '@/utils';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
|
||||
defineOptions({
|
||||
name: 'History'
|
||||
|
||||
@@ -18,7 +18,12 @@
|
||||
</n-scrollbar>
|
||||
</div>
|
||||
<!-- 歌单列表 -->
|
||||
<n-scrollbar class="recommend" style="height: calc(100% - 55px)" :size="100" @scroll="handleScroll">
|
||||
<n-scrollbar
|
||||
class="recommend"
|
||||
style="height: calc(100% - 55px)"
|
||||
:size="100"
|
||||
@scroll="handleScroll"
|
||||
>
|
||||
<div v-loading="loading" class="recommend-list">
|
||||
<div
|
||||
v-for="(item, index) in recommendList"
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -27,10 +27,17 @@
|
||||
<n-layout
|
||||
v-if="isMobile ? searchDetail : true"
|
||||
class="search-list"
|
||||
:class="setAnimationClass('animate__fadeInUp')"
|
||||
:class="setAnimationClass('animate__fadeInDown')"
|
||||
:native-scrollbar="false"
|
||||
@scroll="handleScroll"
|
||||
>
|
||||
<div class="title">{{ hotKeyword }}</div>
|
||||
<div v-if="searchDetail" class="title">
|
||||
<i
|
||||
class="ri-arrow-left-s-line mr-1 cursor-pointer hover:text-gray-500 hover:scale-110"
|
||||
@click="searchDetail = null"
|
||||
></i>
|
||||
{{ hotKeyword }}
|
||||
</div>
|
||||
<div v-loading="searchDetailLoading" class="search-list-box">
|
||||
<template v-if="searchDetail">
|
||||
<div
|
||||
@@ -46,13 +53,49 @@
|
||||
<div
|
||||
v-for="(item, index) in list"
|
||||
:key="item.id"
|
||||
class="mb-3"
|
||||
:class="setAnimationClass('animate__bounceInRight')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
>
|
||||
<SearchItem :item="item" />
|
||||
<search-item :item="item" />
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="isLoadingMore" class="loading-more">
|
||||
<n-spin size="small" />
|
||||
<span class="ml-2">加载中...</span>
|
||||
</div>
|
||||
<div v-if="!hasMore && searchDetail" class="no-more">没有更多了</div>
|
||||
</template>
|
||||
<!-- 搜索历史 -->
|
||||
<template v-else>
|
||||
<div class="search-history">
|
||||
<div class="search-history-header title">
|
||||
<span>搜索历史</span>
|
||||
<n-button text type="error" @click="clearSearchHistory">
|
||||
<template #icon>
|
||||
<i class="ri-delete-bin-line"></i>
|
||||
</template>
|
||||
清空
|
||||
</n-button>
|
||||
</div>
|
||||
<div class="search-history-list">
|
||||
<n-tag
|
||||
v-for="(item, index) in searchHistory"
|
||||
:key="index"
|
||||
:class="setAnimationClass('animate__bounceIn')"
|
||||
:style="setAnimationDelay(index, 50)"
|
||||
class="search-history-item"
|
||||
round
|
||||
closable
|
||||
@click="handleSearchHistory(item)"
|
||||
@close="handleCloseSearchHistory(item)"
|
||||
>
|
||||
{{ item }}
|
||||
</n-tag>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</n-layout>
|
||||
@@ -67,10 +110,10 @@ import { useStore } from 'vuex';
|
||||
|
||||
import { getHotSearch } from '@/api/home';
|
||||
import { getSearch } from '@/api/search';
|
||||
import SearchItem from '@/components/common/SearchItem.vue';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
import type { IHotSearch } from '@/type/search';
|
||||
import { isMobile, setAnimationClass, setAnimationDelay } from '@/utils';
|
||||
import SearchItem from '@/components/common/SearchItem.vue';
|
||||
|
||||
defineOptions({
|
||||
name: 'Search'
|
||||
@@ -82,6 +125,51 @@ const store = useStore();
|
||||
const searchDetail = ref<any>();
|
||||
const searchType = computed(() => store.state.searchType as number);
|
||||
const searchDetailLoading = ref(false);
|
||||
const searchHistory = ref<string[]>([]);
|
||||
|
||||
// 添加分页相关的状态
|
||||
const ITEMS_PER_PAGE = 30; // 每页数量
|
||||
const page = ref(0);
|
||||
const hasMore = ref(true);
|
||||
const isLoadingMore = ref(false);
|
||||
const currentKeyword = ref('');
|
||||
|
||||
// 从 localStorage 加载搜索历史
|
||||
const loadSearchHistory = () => {
|
||||
const history = localStorage.getItem('searchHistory');
|
||||
searchHistory.value = history ? JSON.parse(history) : [];
|
||||
};
|
||||
|
||||
// 保存搜索历史
|
||||
const saveSearchHistory = (keyword: string) => {
|
||||
if (!keyword) return;
|
||||
const history = searchHistory.value;
|
||||
// 移除重复的关键词
|
||||
const index = history.indexOf(keyword);
|
||||
if (index > -1) {
|
||||
history.splice(index, 1);
|
||||
}
|
||||
// 添加到开头
|
||||
history.unshift(keyword);
|
||||
// 只保留最近的20条记录
|
||||
if (history.length > 20) {
|
||||
history.pop();
|
||||
}
|
||||
searchHistory.value = history;
|
||||
localStorage.setItem('searchHistory', JSON.stringify(history));
|
||||
};
|
||||
|
||||
// 清空搜索历史
|
||||
const clearSearchHistory = () => {
|
||||
searchHistory.value = [];
|
||||
localStorage.removeItem('searchHistory');
|
||||
};
|
||||
|
||||
// 删除搜索历史
|
||||
const handleCloseSearchHistory = (keyword: string) => {
|
||||
searchHistory.value = searchHistory.value.filter((item) => item !== keyword);
|
||||
localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value));
|
||||
};
|
||||
|
||||
// 热搜列表
|
||||
const hotSearchData = ref<IHotSearch>();
|
||||
@@ -92,6 +180,7 @@ const loadHotSearch = async () => {
|
||||
|
||||
onMounted(() => {
|
||||
loadHotSearch();
|
||||
loadSearchHistory();
|
||||
loadSearch(route.query.keyword);
|
||||
});
|
||||
|
||||
@@ -114,48 +203,103 @@ watch(
|
||||
);
|
||||
|
||||
const dateFormat = (time: any) => useDateFormat(time, 'YYYY.MM.DD').value;
|
||||
const loadSearch = async (keywords: any, type: any = null) => {
|
||||
hotKeyword.value = keywords;
|
||||
searchDetail.value = undefined;
|
||||
const loadSearch = async (keywords: any, type: any = null, isLoadMore = false) => {
|
||||
if (!keywords) return;
|
||||
|
||||
searchDetailLoading.value = true;
|
||||
const { data } = await getSearch({ keywords, type: type || searchType.value });
|
||||
if (!isLoadMore) {
|
||||
hotKeyword.value = keywords;
|
||||
searchDetail.value = undefined;
|
||||
page.value = 0;
|
||||
hasMore.value = true;
|
||||
currentKeyword.value = keywords;
|
||||
} else if (isLoadingMore.value || !hasMore.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const songs = data.result.songs || [];
|
||||
const albums = data.result.albums || [];
|
||||
const mvs = (data.result.mvs || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.cover,
|
||||
playCount: item.playCount,
|
||||
desc: item.artists.map((artist: any) => artist.name).join('/'),
|
||||
type: 'mv'
|
||||
}));
|
||||
// 保存搜索历史
|
||||
if (!isLoadMore) {
|
||||
saveSearchHistory(keywords);
|
||||
}
|
||||
|
||||
const playlists = (data.result.playlists || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.coverImgUrl,
|
||||
playCount: item.playCount,
|
||||
desc: item.creator.nickname,
|
||||
type: 'playlist'
|
||||
}));
|
||||
if (isLoadMore) {
|
||||
isLoadingMore.value = true;
|
||||
} else {
|
||||
searchDetailLoading.value = true;
|
||||
}
|
||||
|
||||
// songs map 替换属性
|
||||
songs.forEach((item: any) => {
|
||||
item.picUrl = item.al.picUrl;
|
||||
item.artists = item.ar;
|
||||
});
|
||||
albums.forEach((item: any) => {
|
||||
item.desc = `${item.artist.name} ${item.company} ${dateFormat(item.publishTime)}`;
|
||||
});
|
||||
searchDetail.value = {
|
||||
songs,
|
||||
albums,
|
||||
mvs,
|
||||
playlists
|
||||
};
|
||||
try {
|
||||
const { data } = await getSearch({
|
||||
keywords: currentKeyword.value,
|
||||
type: type || searchType.value,
|
||||
limit: ITEMS_PER_PAGE,
|
||||
offset: page.value * ITEMS_PER_PAGE
|
||||
});
|
||||
|
||||
searchDetailLoading.value = false;
|
||||
const songs = data.result.songs || [];
|
||||
const albums = data.result.albums || [];
|
||||
const mvs = (data.result.mvs || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.cover,
|
||||
playCount: item.playCount,
|
||||
desc: item.artists.map((artist: any) => artist.name).join('/'),
|
||||
type: 'mv'
|
||||
}));
|
||||
|
||||
const playlists = (data.result.playlists || []).map((item: any) => ({
|
||||
...item,
|
||||
picUrl: item.coverImgUrl,
|
||||
playCount: item.playCount,
|
||||
desc: item.creator.nickname,
|
||||
type: 'playlist'
|
||||
}));
|
||||
|
||||
// songs map 替换属性
|
||||
songs.forEach((item: any) => {
|
||||
item.picUrl = item.al.picUrl;
|
||||
item.artists = item.ar;
|
||||
});
|
||||
albums.forEach((item: any) => {
|
||||
item.desc = `${item.artist.name} ${item.company} ${dateFormat(item.publishTime)}`;
|
||||
});
|
||||
|
||||
if (isLoadMore && searchDetail.value) {
|
||||
// 合并数据
|
||||
searchDetail.value.songs = [...searchDetail.value.songs, ...songs];
|
||||
searchDetail.value.albums = [...searchDetail.value.albums, ...albums];
|
||||
searchDetail.value.mvs = [...searchDetail.value.mvs, ...mvs];
|
||||
searchDetail.value.playlists = [...searchDetail.value.playlists, ...playlists];
|
||||
} else {
|
||||
searchDetail.value = {
|
||||
songs,
|
||||
albums,
|
||||
mvs,
|
||||
playlists
|
||||
};
|
||||
}
|
||||
|
||||
// 判断是否还有更多数据
|
||||
hasMore.value =
|
||||
songs.length === ITEMS_PER_PAGE ||
|
||||
albums.length === ITEMS_PER_PAGE ||
|
||||
mvs.length === ITEMS_PER_PAGE ||
|
||||
playlists.length === ITEMS_PER_PAGE;
|
||||
|
||||
page.value++;
|
||||
} catch (error) {
|
||||
console.error('搜索失败:', error);
|
||||
} finally {
|
||||
searchDetailLoading.value = false;
|
||||
isLoadingMore.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 添加滚动处理函数
|
||||
const handleScroll = (e: any) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = e.target;
|
||||
// 距离底部100px时加载更多
|
||||
if (scrollTop + clientHeight >= scrollHeight - 100 && !isLoadingMore.value && hasMore.value) {
|
||||
loadSearch(currentKeyword.value, null, true);
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
@@ -171,6 +315,11 @@ const handlePlay = () => {
|
||||
const tracks = searchDetail.value?.songs || [];
|
||||
store.commit('setPlayList', tracks);
|
||||
};
|
||||
|
||||
// 点击搜索历史
|
||||
const handleSearchHistory = (keyword: string) => {
|
||||
loadSearch(keyword, 1);
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -214,6 +363,7 @@ const handlePlay = () => {
|
||||
@apply flex-1 rounded-xl;
|
||||
@apply bg-light-100 dark:bg-dark-100;
|
||||
height: 100%;
|
||||
animation-duration: 0.2s;
|
||||
|
||||
&-box {
|
||||
@apply pb-28;
|
||||
@@ -225,9 +375,35 @@ const handlePlay = () => {
|
||||
@apply text-gray-900 dark:text-white;
|
||||
}
|
||||
|
||||
.search-history {
|
||||
&-header {
|
||||
@apply flex justify-between items-center mb-4;
|
||||
@apply text-gray-900 dark:text-white;
|
||||
}
|
||||
|
||||
&-list {
|
||||
@apply flex flex-wrap gap-2 px-4;
|
||||
}
|
||||
|
||||
&-item {
|
||||
@apply cursor-pointer;
|
||||
animation-duration: 0.2s;
|
||||
}
|
||||
}
|
||||
|
||||
.mobile {
|
||||
.hot-search {
|
||||
@apply mr-0 w-full;
|
||||
}
|
||||
}
|
||||
|
||||
.loading-more {
|
||||
@apply flex justify-center items-center py-4;
|
||||
@apply text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
|
||||
.no-more {
|
||||
@apply text-center py-4;
|
||||
@apply text-gray-500 dark:text-gray-400;
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -84,16 +84,20 @@
|
||||
:song-list="list?.tracks || []"
|
||||
:list-info="list"
|
||||
:loading="listLoading"
|
||||
:can-remove="true"
|
||||
@remove-song="handleRemoveFromPlaylist"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, watch, onBeforeUnmount } from 'vue';
|
||||
import { useMessage } from 'naive-ui';
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useStore } from 'vuex';
|
||||
|
||||
import { getListDetail } from '@/api/list';
|
||||
import { updatePlaylistTracks } from '@/api/music';
|
||||
import { getUserDetail, getUserPlaylist, getUserRecord } from '@/api/user';
|
||||
import PlayBottom from '@/components/common/PlayBottom.vue';
|
||||
import SongItem from '@/components/common/SongItem.vue';
|
||||
@@ -116,6 +120,7 @@ const mounted = ref(true);
|
||||
const isShowList = ref(false);
|
||||
const list = ref<Playlist>();
|
||||
const listLoading = ref(false);
|
||||
const message = useMessage();
|
||||
|
||||
const user = computed(() => store.state.user);
|
||||
|
||||
@@ -123,9 +128,30 @@ 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 +170,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,16 +184,37 @@ const loadPage = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
// 监听用户状态变化
|
||||
watch(() => store.state.user, (newUser) => {
|
||||
if (!mounted.value) return;
|
||||
|
||||
if (!newUser) {
|
||||
router.push('/login');
|
||||
} else {
|
||||
loadPage();
|
||||
// 监听路由变化
|
||||
watch(
|
||||
() => router.currentRoute.value.path,
|
||||
(newPath) => {
|
||||
if (newPath === '/user') {
|
||||
checkLoginStatus();
|
||||
} else {
|
||||
loadPage();
|
||||
}
|
||||
}
|
||||
}, { immediate: true });
|
||||
);
|
||||
|
||||
// 监听用户状态变化
|
||||
watch(
|
||||
() => store.state.user,
|
||||
(newUser) => {
|
||||
if (!mounted.value) return;
|
||||
|
||||
if (!newUser) {
|
||||
router.push('/login');
|
||||
} else {
|
||||
loadPage();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// 页面挂载时检查登录状态
|
||||
onMounted(() => {
|
||||
checkLoginStatus();
|
||||
});
|
||||
|
||||
// 展示歌单
|
||||
const showPlaylist = async (id: number, name: string) => {
|
||||
@@ -170,11 +222,41 @@ const showPlaylist = async (id: number, name: string) => {
|
||||
listLoading.value = true;
|
||||
|
||||
list.value = {
|
||||
name
|
||||
name,
|
||||
id
|
||||
} as Playlist;
|
||||
await loadPlaylistDetail(id);
|
||||
listLoading.value = false;
|
||||
};
|
||||
|
||||
// 加载歌单详情
|
||||
const loadPlaylistDetail = async (id: number) => {
|
||||
const { data } = await getListDetail(id);
|
||||
list.value = data.playlist;
|
||||
listLoading.value = false;
|
||||
};
|
||||
|
||||
// 从歌单中删除歌曲
|
||||
const handleRemoveFromPlaylist = async (songId: number) => {
|
||||
if (!list.value?.id) return;
|
||||
|
||||
try {
|
||||
const res = await updatePlaylistTracks({
|
||||
op: 'del',
|
||||
pid: list.value.id,
|
||||
tracks: songId.toString()
|
||||
});
|
||||
|
||||
if (res.status === 200) {
|
||||
message.success('删除成功');
|
||||
// 重新加载歌单详情
|
||||
await loadPlaylistDetail(list.value.id);
|
||||
} else {
|
||||
throw new Error(res.data?.msg || '删除失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('删除歌曲失败:', error);
|
||||
message.error(error.message || '删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handlePlay = () => {
|
||||
@@ -229,7 +311,7 @@ const handlePlay = () => {
|
||||
.record-list {
|
||||
@apply rounded-2xl;
|
||||
@apply bg-light dark:bg-black;
|
||||
height: calc(100% - 3.75rem);
|
||||
height: calc(100% - 100px);
|
||||
|
||||
.record-item {
|
||||
@apply flex items-center px-4;
|
||||
|
||||
Reference in New Issue
Block a user