Compare commits

..

4 Commits

Author SHA1 Message Date
alger 1e30a11881 fix(core): 修复事件监听器泄漏
- App.vue: offline 监听器添加 onUnmounted 清理,移除冗余 console.log
- MusicHook.ts: document.onkeyup 直接赋值改为 addEventListener + 防重复
- MusicHook.ts: audio-ready 监听器提取为命名函数,先移除再注册防堆叠
2026-03-29 14:22:33 +08:00
alger 34713430e1 fix(player): 修复迷你模式恢复后歌词页面空白偏移
迷你播放栏的 togglePlaylist 设置 document.body.style.height='64px'
和 overflow='hidden',恢复主窗口时未清理,导致歌词 drawer 高度被限制。
在 mini-mode 事件处理中添加 body 样式重置。
2026-03-29 14:04:55 +08:00
alger eaf1636505 refactor(player): 提取播放栏共享逻辑为 composable
- 新增 useVolumeControl:统一音量管理(volumeSlider、mute、滚轮调节)
- 新增 useFavorite:收藏状态与切换
- 新增 usePlaybackControl:播放/暂停、上/下一首
- PlayBar、MiniPlayBar、SimplePlayBar、MobilePlayBar 使用新 composable
- 修复音量存储不一致:MiniPlayBar/SimplePlayBar 原先绕过 playerStore 直接操作 localStorage
2026-03-29 14:04:39 +08:00
alger e032afeae8 docs: 更新 CLAUDE.md,反映播放系统重构(Howler.js → 原生 HTMLAudioElement) 2026-03-29 13:30:36 +08:00
140 changed files with 1616 additions and 3470 deletions
+3 -1
View File
@@ -1,2 +1,4 @@
# 你的接口地址 (必填)
VITE_API = http://127.0.0.1:30488
VITE_API = http://127.0.0.1:30488
# 音乐破解接口地址 web端
VITE_API_MUSIC = ***
-83
View File
@@ -1,83 +0,0 @@
name: PR Check
on:
pull_request:
branches: [main]
types: [opened, edited, synchronize, reopened]
jobs:
# 检查 PR 标题是否符合 Conventional Commits 规范
pr-title:
name: PR Title
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
- name: Install commitlint
run: npm install --no-save @commitlint/cli @commitlint/config-conventional
- name: Validate PR title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "$PR_TITLE" | npx commitlint
# 检查所有提交信息是否符合 Conventional Commits 规范
commit-messages:
name: Commit Messages
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
- name: Install commitlint
run: npm install --no-save @commitlint/cli @commitlint/config-conventional
- name: Validate commit messages
run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
# 运行 lint 和类型检查
code-quality:
name: Code Quality
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 24
# lint:i18n 脚本用 bun 跑(package.json: "bun scripts/check_i18n.ts"),
# CI 默认环境没有 bun 会报 sh: bun: not found
- name: Setup Bun
uses: oven-sh/setup-bun@v2
- name: Install dependencies
run: npm install
- name: Lint
run: npx eslint --max-warnings 0 "src/**/*.{ts,tsx,vue,js}"
# tsconfig.web.json 显式 require src/renderer/{auto-imports,components}.d.ts
# 这两个文件由 unplugin-auto-import / unplugin-vue-components 在 vite 启动时
# 生成,且被 .gitignore 排除(58922dc 维护者主动设置)。CI 直接跑 typecheck
# 拿不到 d.ts 会报 TS2688,先跑一次 build 触发 unplugin 生成
- name: Build (generates auto-import / components d.ts)
run: npm run build
- name: Type check
run: npm run typecheck
- name: I18n check
run: npm run lint:i18n
-3
View File
@@ -46,8 +46,5 @@ AGENTS.md
.auto-imports.d.ts
.components.d.ts
# TypeScript 增量编译缓存
*.tsbuildinfo
src/renderer/auto-imports.d.ts
src/renderer/components.d.ts
-1
View File
@@ -1 +0,0 @@
npx --no -- commitlint --edit "$1"
+423
View File
@@ -0,0 +1,423 @@
# CLAUDE.md
本文件为 Claude Code (claude.ai/code) 提供项目指南。
## 项目概述
Alger Music Player 是基于 **Electron + Vue 3 + TypeScript** 构建的第三方网易云音乐播放器,支持桌面端(Windows/macOS/Linux)、Web 和移动端,具备本地 API 服务、桌面歌词、无损音乐下载、音源解锁、EQ 均衡器等功能。
## 技术栈
- **桌面端**: Electron 40 + electron-vite 5
- **前端框架**: Vue 3.5 (Composition API + `<script setup>`)
- **状态管理**: Pinia 3 + pinia-plugin-persistedstate
- **UI 框架**: naive-ui(自动导入)
- **样式**: Tailwind CSS 3(仅在模板中使用 class,禁止在 `<style>` 中使用 `@apply`
- **图标**: remixicon
- **音频**: 原生 HTMLAudioElement + Web Audio APIEQ 均衡器)
- **工具库**: VueUse, lodash
- **国际化**: vue-i18n5 种语言:zh-CN、en-US、ja-JP、ko-KR、zh-Hant
- **音乐 API**: netease-cloud-music-api-alger + @unblockneteasemusic/server
- **自动更新**: electron-updaterGitHub Releases
- **构建**: Vite 6, electron-builder
## 开发命令
```bash
# 安装依赖(推荐 Node 18+
npm install
# 桌面端开发(推荐)
npm run dev
# Web 端开发(需自建 netease-cloud-music-api 服务)
npm run dev:web
# 类型检查
npm run typecheck # 全部检查
npm run typecheck:node # 主进程
npm run typecheck:web # 渲染进程
# 代码规范
npm run lint # ESLint + i18n 检查
npm run format # Prettier 格式化
# 构建
npm run build # 构建渲染进程和主进程
npm run build:win # Windows 安装包
npm run build:mac # macOS DMG
npm run build:linux # AppImage, deb, rpm
npm run build:unpack # 仅构建不打包
```
## 项目架构
### 目录结构
```
src/
├── main/ # Electron 主进程
│ ├── index.ts # 入口,窗口生命周期
│ ├── modules/ # 功能模块(15 个文件)
│ │ ├── window.ts # 窗口管理(主窗口、迷你模式、歌词窗口)
│ │ ├── tray.ts # 系统托盘
│ │ ├── shortcuts.ts # 全局快捷键
│ │ ├── fileManager.ts # 下载管理
│ │ ├── remoteControl.ts # 远程控制 HTTP API
│ │ └── update.ts # 自动更新(electron-updater
│ ├── lyric.ts # 歌词窗口
│ ├── server.ts # 本地 API 服务
│ └── unblockMusic.ts # 音源解锁服务
├── preload/index.ts # IPC 桥接(暴露 window.api
├── shared/ # 主进程/渲染进程共享代码
│ └── appUpdate.ts # 更新状态类型定义
├── i18n/ # 国际化
│ ├── lang/ # 语言文件(5 语言 × 15 分类 = 75 个文件)
│ ├── main.ts # 主进程 i18n
│ ├── renderer.ts # 渲染进程 i18n
│ └── utils.ts # i18n 工具
└── renderer/ # Vue 应用
├── store/modules/ # Pinia 状态(15 个模块)
│ ├── playerCore.ts # 🔑 播放核心状态(纯状态:播放/暂停、音量、倍速)
│ ├── playlist.ts # 🔑 播放列表管理(上/下一首、播放模式)
│ ├── settings.ts # 应用设置
│ ├── user.ts # 用户认证与同步
│ ├── lyric.ts # 歌词状态
│ ├── music.ts # 音乐元数据
│ └── favorite.ts # 收藏管理
├── services/ # 服务层
│ ├── audioService.ts # 🔑 原生 HTMLAudioElement + Web Audio APIEQ、MediaSession
│ ├── playbackController.ts # 🔑 播放控制流(playTrack 入口、generation 取消、初始化恢复)
│ ├── playbackRequestManager.ts # 请求 ID 追踪(供 usePlayerHooks 内部取消检查)
│ ├── preloadService.ts # 下一首 URL 预验证
│ ├── SongSourceConfigManager.ts # 单曲音源配置
│ └── translation-engines/ # 翻译引擎策略
├── hooks/ # 组合式函数(9 个文件)
│ ├── MusicHook.ts # 🔑 音乐主逻辑(歌词、进度、快捷键)
│ ├── usePlayerHooks.ts # 播放器 hooks
│ ├── useDownload.ts # 下载功能
│ └── IndexDBHook.ts # IndexedDB 封装
├── api/ # API 层(16 个文件)
│ ├── musicParser.ts # 🔑 多音源 URL 解析(策略模式)
│ ├── music.ts # 网易云音乐 API
│ ├── bilibili.ts # B站音源
│ ├── gdmusic.ts # GD Music 平台
│ ├── lxMusicStrategy.ts # LX Music 音源策略
│ ├── donation.ts # 捐赠 API
│ └── parseFromCustomApi.ts # 自定义 API 解析
├── components/ # 组件(59+ 个文件)
│ ├── common/ # 通用组件(24 个)
│ ├── player/ # 播放器组件(10 个)
│ ├── settings/ # 设置弹窗组件(7 个)
│ └── ...
├── views/ # 页面(53 个文件)
│ ├── set/ # 设置页(已拆分为 Tab 组件)
│ │ ├── index.vue # 设置页壳组件(导航 + provide/inject
│ │ ├── keys.ts # InjectionKey 定义
│ │ ├── SBtn.vue # 自定义按钮组件
│ │ ├── SInput.vue # 自定义输入组件
│ │ ├── SSelect.vue # 自定义选择器组件
│ │ ├── SettingItem.vue
│ │ ├── SettingSection.vue
│ │ └── tabs/ # 7 个 Tab 组件
│ │ ├── BasicTab.vue
│ │ ├── PlaybackTab.vue
│ │ ├── ApplicationTab.vue
│ │ ├── NetworkTab.vue
│ │ ├── SystemTab.vue
│ │ ├── AboutTab.vue
│ │ └── DonationTab.vue
│ └── ...
├── router/ # Vue Router3 个文件)
├── types/ # TypeScript 类型(20 个文件)
├── utils/ # 工具函数(17 个文件)
├── directive/ # 自定义指令
├── const/ # 常量定义
└── assets/ # 静态资源
```
### 核心模块职责
| 模块 | 文件 | 职责 |
|------|------|------|
| 播放控制 | `services/playbackController.ts` | 🔑 播放入口(playTrack)、generation 取消、初始化恢复、URL 过期处理 |
| 音频服务 | `services/audioService.ts` | 原生 HTMLAudioElement + Web Audio API、EQ 滤波、MediaSession |
| 播放状态 | `store/playerCore.ts` | 纯状态:播放/暂停、音量、倍速、当前歌曲、音频设备 |
| 播放列表 | `store/playlist.ts` | 列表管理、播放模式、上/下一首 |
| 音源解析 | `api/musicParser.ts` | 多音源 URL 解析与缓存 |
| 音乐钩子 | `hooks/MusicHook.ts` | 歌词解析、进度跟踪、键盘快捷键 |
### 播放系统架构
```
用户操作 / 自动播放
playbackController.playTrack(song) ← 唯一入口,generation++ 取消旧操作
├─ 加载歌词 + 背景色
├─ 获取播放 URLgetSongDetail
└─ audioService.play(url, track)
├─ audio.src = url ← 单一 HTMLAudioElement,换歌改 src
├─ Web Audio API EQ 链 ← createMediaElementSource 只调一次
└─ 原生 DOM 事件 → emit
MusicHook 监听(进度、歌词同步、播放状态)
```
**关键设计**
- **Generation-based 取消**:每次 `playTrack()` 递增 generation,await 后检查是否过期,过期则静默退出
- **单一 HTMLAudioElement**:启动时创建,永不销毁。换歌改 `audio.src`EQ 链不重建
- **Seek**:直接 `audio.currentTime = time`,无 Howler.js 的 pause→play 问题
### 音源解析策略
`musicParser.ts` 使用 **策略模式** 从多个来源解析音乐 URL
**优先级顺序**(可通过 `SongSourceConfigManager` 按曲配置):
1. `custom` - 自定义 API
2. `bilibili` - B站音频
3. `gdmusic` - GD Music 平台
4. `lxmusic` - LX Music HTTP 源
5. `unblock` - UnblockNeteaseMusic 服务
**缓存策略**
- 成功的 URL 在 IndexedDB 缓存 30 分钟(`music_url_cache`
- 失败的尝试在内存中缓存 1 分钟(应用重启自动清除)
- 音源配置变更时缓存失效
### 设置页架构
设置页(`views/set/`)采用 **provide/inject** 模式拆分为 7 个 Tab 组件:
- `index.vue` 作为壳组件:管理 Tab 导航、`setData` 双向绑定与防抖保存
- `keys.ts` 定义类型化的 InjectionKey`SETTINGS_DATA_KEY``SETTINGS_MESSAGE_KEY``SETTINGS_DIALOG_KEY`
- 自定义 UI 组件(`SBtn``SInput``SSelect`)替代部分 naive-ui 组件
- 字体选择器保留 naive-ui `n-select`(需要 filterable + multiple + render-label
## 代码规范
### 命名
- **目录**: kebab-case`components/music-player`
- **组件**: PascalCase`MusicPlayer.vue`
- **组合式函数**: camelCase + `use` 前缀(`usePlayer.ts`
- **Store**: camelCase`playerCore.ts`
- **常量**: UPPER_SNAKE_CASE`MAX_RETRY_COUNT`
### TypeScript
- **优先使用 `type` 而非 `interface`**
- **禁止使用 `enum`,使用 `const` 对象 + `as const`**
- 所有导出函数必须有类型标注
```typescript
// ✅ 正确
type SongResult = { id: number; name: string };
const PlayMode = { ORDER: 'order', LOOP: 'loop' } as const;
// ❌ 避免
interface ISongResult { ... }
enum PlayMode { ... }
```
### Vue 组件结构
```vue
<script setup lang="ts">
// 1. 导入(按类型分组)
import { ref, computed, onMounted } from 'vue';
import { usePlayerStore } from '@/store';
import type { SongResult } from '@/types/music';
// 2. Props & Emits
const props = defineProps<{ id: number }>();
const emit = defineEmits<{ play: [id: number] }>();
// 3. Store
const playerStore = usePlayerStore();
// 4. 响应式状态(使用描述性命名:isLoading, hasError
const isLoading = ref(false);
// 5. 计算属性
const displayName = computed(() => /* ... */);
// 6. 方法(动词开头命名)
const handlePlay = () => { /* ... */ };
// 7. 生命周期钩子
onMounted(() => { /* ... */ });
</script>
<template>
<!-- naive-ui 组件 + Tailwind CSS -->
</template>
```
### 样式规范
- **禁止在 `<style>` 中使用 `@apply`**,所有 Tailwind 类直接写在模板中
- 如发现代码中有 `@apply` 用法,应优化为内联 Tailwind class
- `<style scoped>` 仅用于无法用 Tailwind 实现的 CSS(如 keyframes 动画、`:deep()` 穿透)
### 导入约定
- **naive-ui 组件**:自动导入,无需手动 import
- **Vue 组合式 API**`useDialog``useMessage``useNotification``useLoadingBar` 自动导入
- **路径别名**`@``src/renderer``@i18n``src/i18n`
## 关键实现模式
### 状态持久化
Store 使用 `pinia-plugin-persistedstate` 自动持久化:
```typescript
export const useXxxStore = defineStore('xxx', () => {
// store 逻辑
}, {
persist: {
key: 'xxx-store',
storage: localStorage,
pick: ['fieldsToPersist'] // 仅持久化指定字段
}
});
```
### IPC 通信
```typescript
// 主进程 (src/main/modules/*)
ipcMain.handle('channel-name', async (_, args) => {
return result;
});
// Preload (src/preload/index.ts)
const api = {
methodName: (args) => ipcRenderer.invoke('channel-name', args)
};
contextBridge.exposeInMainWorld('api', api);
// 渲染进程 (src/renderer/*)
const result = await window.api.methodName(args);
```
### IndexedDB 使用
使用 `IndexDBHook` 组合式函数:
```typescript
const db = await useIndexedDB('dbName', [
{ name: 'storeName', keyPath: 'id' }
], version);
const { saveData, getData, deleteData } = db;
await saveData('storeName', { id: 1, data: 'value' });
const data = await getData('storeName', 1);
```
### 新增页面
1. 创建 `src/renderer/views/xxx/index.vue`
2.`src/renderer/router/other.ts` 中添加路由
3.`src/i18n/lang/*/` 下所有 5 种语言中添加 i18n 键值
### 新增 Store
```typescript
// src/renderer/store/modules/xxx.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
export const useXxxStore = defineStore('xxx', () => {
const state = ref(initialValue);
const action = () => { /* ... */ };
return { state, action };
});
// 在 src/renderer/store/index.ts 中导出
export * from './modules/xxx';
```
### 新增音源策略
编辑 `src/renderer/api/musicParser.ts`
```typescript
class NewStrategy implements MusicSourceStrategy {
name = 'new';
priority = 5;
canHandle(sources: string[]) { return sources.includes('new'); }
async parse(id: number, data: any): Promise<ParsedMusicResult> {
// 实现解析逻辑
}
}
// 在 ParserManager 构造函数中注册
this.strategies.push(new NewStrategy());
```
## 平台相关说明
### Web 端开发
运行 `npm run dev:web` 需要:
1. 自建 `netease-cloud-music-api` 服务
2. 在项目根目录创建 `.env.development.local`
```env
VITE_API=https://your-api-server.com
VITE_API_MUSIC=https://your-unblock-server.com
```
### Electron 功能
- **窗口管理**: `src/main/modules/window.ts`(主窗口、迷你模式、歌词窗口)
- **系统托盘**: `src/main/modules/tray.ts`
- **全局快捷键**: `src/main/modules/shortcuts.ts`
- **自动更新**: `src/main/modules/update.ts`electron-updater + GitHub Releases
- **远程控制**: `src/main/modules/remoteControl.ts`HTTP API 远程播放控制)
- **磁盘缓存**: 音乐和歌词文件缓存,支持可配置目录、容量上限、LRU/FIFO 清理策略
## API 请求注意事项
- **axios 响应结构**`request.get('/xxx')` 返回 axios response,实际数据在 `res.data` 中。若 API 本身也有 `data` 字段(如 `/personal_fm` 返回 `{data: [...], code: 200}`),则需要 `res.data.data` 才能拿到真正的数组,**不要** 直接用 `res.data` 当结果。
- **避免并发请求风暴**:首页不要一次性并发请求大量接口(如 15 个歌单详情),会导致本地 API 服务与 `music.163.com` 的 TLS 连接被 reset502)。应使用懒加载(hover 时加载)或严格限制并发数。
- **timestamp 参数**:对 `/personal_fm` 等需要实时数据的接口,传 `timestamp: Date.now()` 避免服务端缓存和 stale 连接。`request.ts` 拦截器已自动添加 timestamp,API 层无需重复添加。
### 本地 API 服务调试
- **地址**`http://127.0.0.1:{port}`,默认端口 `30488`,可在设置中修改
- **API 文档**:基于 [NeteaseCloudMusicApi](https://www.npmjs.com/package/NeteaseCloudMusicApi)v4.29),接口文档参见 node_modules/NeteaseCloudMusicApi/public/docs/home.md
- **调试方式**:可直接用 `curl` 测试接口,例如:
```bash
# 测试私人FM(需登录 cookie
curl "http://127.0.0.1:30488/personal_fm?timestamp=$(date +%s000)"
# 测试歌单详情
curl "http://127.0.0.1:30488/playlist/detail?id=12449928929"
# 测试FM不喜欢
curl -X POST "http://127.0.0.1:30488/fm_trash?id=歌曲ID&timestamp=$(date +%s000)"
```
- **502 排查**:通常是并发请求过多导致 TLS 连接 reset,用 curl 单独调用可验证接口本身是否正常
- **Cookie 传递**:渲染进程通过 `request.ts` 拦截器自动附加 `localStorage` 中的 token
## 重要注意事项
- **主分支**: `dev_electron`PR 目标分支,非 `main`
- **自动导入**: naive-ui 组件、Vue 组合式 API`ref`、`computed` 等)均已自动导入
- **代码风格**: 使用 ESLint + Prettier,通过 husky + lint-staged 在 commit 时自动执行
- **国际化**: 所有面向用户的文字必须翻译为 5 种语言
- **提交规范**: commit message 中禁止包含 `Co-Authored-By` 信息
- **IndexedDB 存储**:
- `music`: 歌曲元数据缓存
- `music_lyric`: 歌词缓存
- `api_cache`: 通用 API 响应缓存
- `music_url_cache`: 音乐 URL 缓存(30 分钟 TTL
+2
View File
@@ -16,5 +16,7 @@
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
<key>com.apple.security.device.microphone</key>
<true/>
</dict>
</plist>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 989 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

-12
View File
@@ -1,12 +0,0 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
['feat', 'fix', 'perf', 'refactor', 'docs', 'style', 'test', 'build', 'ci', 'chore', 'revert']
],
'subject-empty': [2, 'never'],
'type-empty': [2, 'never']
}
};
-11
View File
@@ -35,17 +35,6 @@ export default defineConfig({
})
],
publicDir: resolve('resources'),
build: {
rollupOptions: {
output: {
// 全部代码打到 entry chunk,避免 Vite 默认按共享依赖拆分时
// 与 store/index.ts 的 `export *` 形成 chunk 间循环引用,
// 触发生产构建里的 TDZ(dev 不分包不会暴露此问题)。
// Electron 桌面端本地加载,无 CDN/首屏体积顾虑,单 chunk 合算。
manualChunks: () => 'index'
}
}
},
server: {
host: '0.0.0.0',
port: 2389
+3 -5
View File
@@ -11,7 +11,7 @@ import globals from 'globals';
export default [
// 忽略文件配置
{
ignores: ['node_modules/**', '**/dist/**', 'out/**', '.gitignore']
ignores: ['node_modules/**', 'dist/**', 'out/**', '.gitignore']
},
// 基础 JavaScript 配置
@@ -55,8 +55,7 @@ export default [
defineEmits: 'readonly',
// TypeScript 全局类型
NodeJS: 'readonly',
ScrollBehavior: 'readonly',
ScrollToOptions: 'readonly'
ScrollBehavior: 'readonly'
}
},
plugins: {
@@ -149,8 +148,7 @@ export default [
useMessage: 'readonly',
// TypeScript 全局类型
NodeJS: 'readonly',
ScrollBehavior: 'readonly',
ScrollToOptions: 'readonly'
ScrollBehavior: 'readonly'
}
},
plugins: {
+2 -10
View File
@@ -18,7 +18,6 @@
"dev:web": "vite dev",
"build": "electron-vite build",
"postinstall": "electron-builder install-app-deps",
"fix-sandbox": "node scripts/fix-sandbox.js",
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win --publish never",
"build:mac": "npm run build && electron-builder --mac --x64 --publish never && cp dist/latest-mac.yml dist/latest-mac-x64.yml && electron-builder --mac --arm64 --publish never && cp dist/latest-mac.yml dist/latest-mac-arm64.yml && node scripts/merge_latest_mac_yml.mjs dist/latest-mac-x64.yml dist/latest-mac-arm64.yml dist/latest-mac.yml",
@@ -37,7 +36,6 @@
"dependencies": {
"@electron-toolkit/preload": "^3.0.2",
"@electron-toolkit/utils": "^4.0.0",
"@httptoolkit/dbus-native": "^0.1.5",
"@unblockneteasemusic/server": "^0.27.10",
"cors": "^2.8.5",
"crypto-js": "^4.2.0",
@@ -51,7 +49,6 @@
"form-data": "^4.0.5",
"husky": "^9.1.7",
"jsencrypt": "^3.5.4",
"mpris-service": "^2.1.2",
"music-metadata": "^11.10.3",
"netease-cloud-music-api-alger": "^4.30.0",
"node-fetch": "^2.7.0",
@@ -61,8 +58,6 @@
"vue-i18n": "^11.2.2"
},
"devDependencies": {
"@commitlint/cli": "^20.5.0",
"@commitlint/config-conventional": "^20.5.0",
"@electron-toolkit/eslint-config": "^2.1.0",
"@electron-toolkit/eslint-config-ts": "^3.1.0",
"@electron-toolkit/tsconfig": "^1.0.1",
@@ -153,6 +148,7 @@
"entitlements": "build/entitlements.mac.plist",
"entitlementsInherit": "build/entitlements.mac.plist",
"extendInfo": {
"NSMicrophoneUsageDescription": "AlgerMusicPlayer needs access to the microphone for audio visualization.",
"NSCameraUsageDescription": "Application requests access to the device's camera.",
"NSDocumentsFolderUsageDescription": "Application requests access to the user's Documents folder.",
"NSDownloadsFolderUsageDescription": "Application requests access to the user's Downloads folder."
@@ -180,7 +176,7 @@
"requestedExecutionLevel": "asInvoker"
},
"linux": {
"icon": "build/icons",
"icon": "resources/icon.png",
"target": [
{
"target": "AppImage",
@@ -226,9 +222,5 @@
"electron",
"esbuild"
]
},
"optionalDependencies": {
"jsbi": "^4.3.2",
"x11": "^2.3.0"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 47 KiB

+3 -20
View File
@@ -1,27 +1,10 @@
{
"name": "Alger Music Player",
"short_name": "AlgerMusic",
"description": "AlgerMusicPlayer 音乐播放器,支持在线播放、歌词显示、音乐下载等功能。",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"name": "Alger Music PWA",
"icons": [
{
"src": "/icon-192.png",
"src": "./icon.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/icon-512.png",
"type": "image/png",
"sizes": "512x512"
},
{
"src": "/icon-512-maskable.png",
"type": "image/png",
"sizes": "512x512",
"purpose": "maskable"
"sizes": "256x256"
}
]
}
-13
View File
@@ -1,13 +0,0 @@
// 最小 Service Worker:仅满足 PWA 可安装性要求(需存在 fetch 处理器)。
// 不做任何缓存拦截,所有请求保持浏览器默认网络行为。
self.addEventListener('install', () => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', () => {
// 特意留空:不拦截,默认走网络
});
-21
View File
@@ -1,21 +0,0 @@
/**
* 修复 Linux 下 Electron sandbox 权限问题
* chrome-sandbox 需要 root 拥有且权限为 4755
*
* 注意:此脚本需要 sudo 权限,仅在 CI 环境或手动执行时使用
* 用法:sudo npm run fix-sandbox
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
if (process.platform === 'linux') {
const sandboxPath = path.resolve(__dirname, '../node_modules/electron/dist/chrome-sandbox');
if (fs.existsSync(sandboxPath)) {
execSync(`sudo chown root:root ${sandboxPath}`);
execSync(`sudo chmod 4755 ${sandboxPath}`);
console.log('[fix-sandbox] chrome-sandbox permissions fixed');
} else {
console.log('[fix-sandbox] chrome-sandbox not found, skipping');
}
}
-3
View File
@@ -223,9 +223,6 @@ export default {
operationFailed: 'Operation Failed',
songsAlreadyInPlaylist: 'Songs already in playlist',
locateCurrent: 'Locate current song',
scrollToTop: 'Scroll to top',
compactLayout: 'Compact layout',
normalLayout: 'Normal layout',
historyRecommend: 'Daily History',
fetchDatesFailed: 'Failed to fetch dates',
fetchSongsFailed: 'Failed to fetch songs',
-8
View File
@@ -58,14 +58,6 @@ export default {
success: 'Download records cleared',
failed: 'Failed to clear download records'
},
save: {
title: 'Save Settings',
message: 'Current download settings are not saved. Do you want to save the changes?',
confirm: 'Save',
cancel: 'Cancel',
discard: 'Discard',
saveSuccess: 'Download settings saved'
},
message: {
downloadComplete: '{filename} download completed',
downloadFailed: '{filename} download failed: {error}'
+1 -3
View File
@@ -9,7 +9,5 @@ export default {
emptyState: 'No local music found. Please select a folder to scan.',
fileNotFound: 'File not found or has been moved',
rescan: 'Rescan',
songCount: '{count} songs',
removeFromLibrary: 'Remove from Library',
removedFromLibrary: 'Removed from library (file not deleted)'
songCount: '{count} songs'
};
-1
View File
@@ -59,7 +59,6 @@ export default {
eq: 'Equalizer',
playList: 'Play List',
reparse: 'Reparse',
download: 'Download',
miniPlayBar: 'Mini Play Bar',
playMode: {
sequence: 'Sequence',
-1
View File
@@ -400,7 +400,6 @@ export default {
themeColor: {
title: 'Lyric Theme Color',
presetColors: 'Preset Colors',
reset: 'Reset to Default',
customColor: 'Custom Color',
preview: 'Preview',
previewText: 'Lyric Effect',
-2
View File
@@ -13,8 +13,6 @@ export default {
},
message: {
downloading: 'Downloading, please wait...',
addToPlaylistNeedLogin:
'Please log in with Cookie or QR code to add songs to a playlist (not available for UID login)',
downloadFailed: 'Download failed',
downloadQueued: 'Added to download queue',
addedToNextPlay: 'Added to play next',
-3
View File
@@ -223,9 +223,6 @@ export default {
addToPlaylistSuccess: 'プレイリストに追加しました',
songsAlreadyInPlaylist: '楽曲は既にプレイリストに存在します',
locateCurrent: '再生中の曲を表示',
scrollToTop: 'トップに戻る',
compactLayout: 'コンパクト表示',
normalLayout: '通常表示',
historyRecommend: '履歴の日次推薦',
fetchDatesFailed: '日付リストの取得に失敗しました',
fetchSongsFailed: '楽曲リストの取得に失敗しました',
-8
View File
@@ -58,14 +58,6 @@ export default {
success: 'ダウンロード記録をクリアしました',
failed: 'ダウンロード記録のクリアに失敗しました'
},
save: {
title: '設定を保存',
message: '現在のダウンロード設定が保存されていません。変更を保存しますか?',
confirm: '保存',
cancel: 'キャンセル',
discard: '破棄',
saveSuccess: 'ダウンロード設定を保存しました'
},
message: {
downloadComplete: '{filename}のダウンロードが完了しました',
downloadFailed: '{filename}のダウンロードに失敗しました: {error}'
+1 -3
View File
@@ -9,7 +9,5 @@ export default {
emptyState: 'ローカル音楽がありません。フォルダを選択してスキャンしてください。',
fileNotFound: 'ファイルが見つからないか、移動されました',
rescan: '再スキャン',
songCount: '{count} 曲',
removeFromLibrary: 'ライブラリから削除',
removedFromLibrary: 'ライブラリから削除しました(ファイルは削除されません)'
songCount: '{count} 曲'
};
-1
View File
@@ -59,7 +59,6 @@ export default {
eq: 'イコライザー',
playList: 'プレイリスト',
reparse: '再解析',
download: 'ダウンロード',
playMode: {
sequence: '順次再生',
loop: 'ループ再生',
+7 -8
View File
@@ -128,26 +128,26 @@ export default {
lxMusic: {
tabs: {
sources: '音源選択',
lxMusic: '雪音源',
lxMusic: '雪音源',
customApi: 'カスタムAPI'
},
scripts: {
title: 'インポート済みのスクリプト',
importLocal: 'ローカルインポート',
importOnline: 'オンラインインポート',
urlPlaceholder: '雪音源スクリプトのURLを入力',
urlPlaceholder: '雪音源スクリプトのURLを入力',
importBtn: 'インポート',
empty: 'インポート済みの雪音源はありません',
notConfigured: '未設定(雪音源タブで設定してください)',
empty: 'インポート済みの雪音源はありません',
notConfigured: '未設定(雪音源タブで設定してください)',
importHint: '互換性のあるカスタムAPIプラグインをインポートして音源を拡張します',
noScriptWarning: '先に雪音源スクリプトをインポートしてください',
noSelectionWarning: '先に雪音源を選択してください',
noScriptWarning: '先に雪音源スクリプトをインポートしてください',
noSelectionWarning: '先に雪音源を選択してください',
notFound: '音源が存在しません',
switched: '音源を切り替えました: {name}',
deleted: '音源を削除しました: {name}',
enterUrl: 'スクリプトURLを入力してください',
invalidUrl: '無効なURL形式',
invalidScript: '無効な雪音源スクリプトです(globalThis.lxが見つかりません)',
invalidScript: '無効な雪音源スクリプトです(globalThis.lxが見つかりません)',
nameRequired: '名前を空にすることはできません',
renameSuccess: '名前を変更しました'
}
@@ -399,7 +399,6 @@ export default {
themeColor: {
title: '歌詞テーマカラー',
presetColors: 'プリセットカラー',
reset: 'デフォルトに戻す',
customColor: 'カスタムカラー',
preview: 'プレビュー効果',
previewText: '歌詞効果',
+33 -35
View File
@@ -1,35 +1,33 @@
export default {
menu: {
play: '再生',
playNext: '次に再生',
download: '楽曲をダウンロード',
downloadLyric: '歌詞をダウンロード',
addToPlaylist: 'プレイリストに追加',
favorite: 'いいね',
unfavorite: 'いいね解除',
removeFromPlaylist: 'プレイリストから削除',
dislike: '嫌い',
undislike: '嫌い解除'
},
message: {
downloading: 'ダウンロード中です。しばらくお待ちください...',
addToPlaylistNeedLogin:
'プレイリストに追加するには Cookie または QR コードでログインしてください(UID ログインでは利用できません)',
downloadFailed: 'ダウンロードに失敗しました',
downloadQueued: 'ダウンロードキューに追加しました',
addedToNextPlay: '次の再生に追加しました',
getUrlFailed:
'音楽ダウンロードアドレスの取得に失敗しました。ログインしているか確認してください',
noLyric: 'この楽曲には歌詞がありません',
lyricDownloaded: '歌詞のダウンロードが完了しました',
lyricDownloadFailed: '歌詞のダウンロードに失敗しました'
},
dialog: {
dislike: {
title: 'お知らせ!',
content: 'この楽曲を嫌いにしますか?再度アクセスすると毎日のおすすめから除外されます。',
positiveText: '嫌い',
negativeText: 'キャンセル'
}
}
};
export default {
menu: {
play: '再生',
playNext: '次に再生',
download: '楽曲をダウンロード',
downloadLyric: '歌詞をダウンロード',
addToPlaylist: 'プレイリストに追加',
favorite: 'いいね',
unfavorite: 'いいね解除',
removeFromPlaylist: 'プレイリストから削除',
dislike: '嫌い',
undislike: '嫌い解除'
},
message: {
downloading: 'ダウンロード中です。しばらくお待ちください...',
downloadFailed: 'ダウンロードに失敗しました',
downloadQueued: 'ダウンロードキューに追加しました',
addedToNextPlay: '次の再生に追加しました',
getUrlFailed:
'音楽ダウンロードアドレスの取得に失敗しました。ログインしているか確認してください',
noLyric: 'この楽曲には歌詞がありません',
lyricDownloaded: '歌詞のダウンロードが完了しました',
lyricDownloadFailed: '歌詞のダウンロードに失敗しました'
},
dialog: {
dislike: {
title: 'お知らせ!',
content: 'この楽曲を嫌いにしますか?再度アクセスすると毎日のおすすめから除外されます。',
positiveText: '嫌い',
negativeText: 'キャンセル'
}
}
};
-3
View File
@@ -222,9 +222,6 @@ export default {
addToPlaylistSuccess: '재생 목록에 추가 성공',
songsAlreadyInPlaylist: '곡이 이미 재생 목록에 있습니다',
locateCurrent: '현재 재생 곡 찾기',
scrollToTop: '맨 위로',
compactLayout: '간결한 레이아웃',
normalLayout: '일반 레이아웃',
historyRecommend: '일일 기록 권장',
fetchDatesFailed: '날짜를 가져오지 못했습니다',
fetchSongsFailed: '곡을 가져오지 못했습니다',
-8
View File
@@ -58,14 +58,6 @@ export default {
success: '다운로드 기록이 지워졌습니다',
failed: '다운로드 기록 삭제에 실패했습니다'
},
save: {
title: '설정 저장',
message: '현재 다운로드 설정이 저장되지 않았습니다. 변경 사항을 저장하시겠습니까?',
confirm: '저장',
cancel: '취소',
discard: '포기',
saveSuccess: '다운로드 설정이 저장됨'
},
message: {
downloadComplete: '{filename} 다운로드 완료',
downloadFailed: '{filename} 다운로드 실패: {error}'
+1 -3
View File
@@ -9,7 +9,5 @@ export default {
emptyState: '로컬 음악이 없습니다. 폴더를 선택하여 스캔하세요.',
fileNotFound: '파일을 찾을 수 없거나 이동되었습니다',
rescan: '다시 스캔',
songCount: '{count}곡',
removeFromLibrary: '라이브러리에서 제거',
removedFromLibrary: '라이브러리에서 제거했습니다 (파일은 삭제되지 않음)'
songCount: '{count}곡'
};
-1
View File
@@ -59,7 +59,6 @@ export default {
eq: '이퀄라이저',
playList: '재생 목록',
reparse: '재분석',
download: '다운로드',
playMode: {
sequence: '순차 재생',
loop: '반복 재생',
-1
View File
@@ -400,7 +400,6 @@ export default {
themeColor: {
title: '가사 테마 색상',
presetColors: '미리 설정된 색상',
reset: '기본값으로 복원',
customColor: '사용자 정의 색상',
preview: '미리보기 효과',
previewText: '가사 효과',
+32 -34
View File
@@ -1,34 +1,32 @@
export default {
menu: {
play: '재생',
playNext: '다음에 재생',
download: '곡 다운로드',
downloadLyric: '가사 다운로드',
addToPlaylist: '플레이리스트에 추가',
favorite: '좋아요',
unfavorite: '좋아요 취소',
removeFromPlaylist: '플레이리스트에서 삭제',
dislike: '싫어요',
undislike: '싫어요 취소'
},
message: {
downloading: '다운로드 중입니다. 잠시 기다려주세요...',
addToPlaylistNeedLogin:
'플레이리스트에 추가하려면 Cookie 또는 QR 코드로 로그인하세요 (UID 로그인은 사용 불가)',
downloadFailed: '다운로드 실패',
downloadQueued: '다운로드 대기열에 추가됨',
addedToNextPlay: '다음 재생에 추가됨',
getUrlFailed: '음악 다운로드 주소 가져오기 실패, 로그인 상태를 확인하세요',
noLyric: '이 곡에는 가사가 없습니다',
lyricDownloaded: '가사 다운로드 완료',
lyricDownloadFailed: '가사 다운로드 실패'
},
dialog: {
dislike: {
title: '알림!',
content: '이 곡을 싫어한다고 확인하시겠습니까? 다시 들어가면 일일 추천에서 제외됩니다.',
positiveText: '싫어요',
negativeText: '취소'
}
}
};
export default {
menu: {
play: '재생',
playNext: '다음에 재생',
download: '곡 다운로드',
downloadLyric: '가사 다운로드',
addToPlaylist: '플레이리스트에 추가',
favorite: '좋아요',
unfavorite: '좋아요 취소',
removeFromPlaylist: '플레이리스트에서 삭제',
dislike: '싫어요',
undislike: '싫어요 취소'
},
message: {
downloading: '다운로드 중입니다. 잠시 기다려주세요...',
downloadFailed: '다운로드 실패',
downloadQueued: '다운로드 대기열에 추가됨',
addedToNextPlay: '다음 재생에 추가됨',
getUrlFailed: '음악 다운로드 주소 가져오기 실패, 로그인 상태를 확인하세요',
noLyric: '이 곡에는 가사가 없습니다',
lyricDownloaded: '가사 다운로드 완료',
lyricDownloadFailed: '가사 다운로드 실패'
},
dialog: {
dislike: {
title: '알림!',
content: '이 곡을 싫어한다고 확인하시겠습니까? 다시 들어가면 일일 추천에서 제외됩니다.',
positiveText: '싫어요',
negativeText: '취소'
}
}
};
-3
View File
@@ -216,9 +216,6 @@ export default {
addToPlaylistSuccess: '添加到播放列表成功',
songsAlreadyInPlaylist: '歌曲已存在于播放列表中',
locateCurrent: '定位当前播放',
scrollToTop: '回到顶部',
compactLayout: '紧凑布局',
normalLayout: '常规布局',
historyRecommend: '历史日推',
fetchDatesFailed: '获取日期列表失败',
fetchSongsFailed: '获取歌曲列表失败',
-8
View File
@@ -57,14 +57,6 @@ export default {
success: '下载记录已清空',
failed: '清空下载记录失败'
},
save: {
title: '保存设置',
message: '当前下载设置未保存,是否保存更改?',
confirm: '保存',
cancel: '取消',
discard: '放弃',
saveSuccess: '下载设置已保存'
},
message: {
downloadComplete: '{filename} 下载完成',
downloadFailed: '{filename} 下载失败: {error}'
+1 -3
View File
@@ -9,7 +9,5 @@ export default {
emptyState: '暂无本地音乐,请先选择文件夹进行扫描',
fileNotFound: '文件不存在或已被移动',
rescan: '重新扫描',
songCount: '{count} 首歌曲',
removeFromLibrary: '从本地列表移除',
removedFromLibrary: '已从本地列表移除(不删除文件)'
songCount: '{count} 首歌曲'
};
-1
View File
@@ -58,7 +58,6 @@ export default {
eq: '均衡器',
playList: '播放列表',
reparse: '重新解析',
download: '下载',
playMode: {
sequence: '顺序播放',
loop: '循环播放',
+7 -8
View File
@@ -128,26 +128,26 @@ export default {
lxMusic: {
tabs: {
sources: '音源选择',
lxMusic: '雪音源',
lxMusic: '雪音源',
customApi: '自定义API'
},
scripts: {
title: '已导入的音源脚本',
importLocal: '本地导入',
importOnline: '在线导入',
urlPlaceholder: '输入雪音源脚本 URL',
urlPlaceholder: '输入雪音源脚本 URL',
importBtn: '导入',
empty: '暂无已导入的雪音源',
notConfigured: '未配置 (请去雪音源Tab配置)',
empty: '暂无已导入的雪音源',
notConfigured: '未配置 (请去雪音源Tab配置)',
importHint: '导入兼容的自定义 API 插件以扩展音源',
noScriptWarning: '请先导入雪音源脚本',
noSelectionWarning: '请先选择一个雪音源',
noScriptWarning: '请先导入雪音源脚本',
noSelectionWarning: '请先选择一个雪音源',
notFound: '音源不存在',
switched: '已切换到音源: {name}',
deleted: '已删除音源: {name}',
enterUrl: '请输入脚本 URL',
invalidUrl: '无效的 URL 格式',
invalidScript: '无效的雪音源脚本,未找到 globalThis.lx 相关代码',
invalidScript: '无效的雪音源脚本,未找到 globalThis.lx 相关代码',
nameRequired: '名称不能为空',
renameSuccess: '重命名成功'
}
@@ -396,7 +396,6 @@ export default {
themeColor: {
title: '歌词主题色',
presetColors: '预设颜色',
reset: '恢复默认',
customColor: '自定义颜色',
preview: '预览效果',
previewText: '歌词效果',
-1
View File
@@ -13,7 +13,6 @@ export default {
},
message: {
downloading: '正在下载中,请稍候...',
addToPlaylistNeedLogin: '请使用 Cookie 或扫码登录后再添加到歌单(UID 登录无法使用此功能)',
downloadFailed: '下载失败',
downloadQueued: '已加入下载队列',
addedToNextPlay: '已添加到下一首播放',
-3
View File
@@ -216,9 +216,6 @@ export default {
addToPlaylistSuccess: '新增至播放清單成功',
songsAlreadyInPlaylist: '歌曲已存在於播放清單中',
locateCurrent: '定位當前播放',
scrollToTop: '回到頂部',
compactLayout: '緊湊佈局',
normalLayout: '常規佈局',
historyRecommend: '歷史日推',
fetchDatesFailed: '獲取日期列表失敗',
fetchSongsFailed: '獲取歌曲列表失敗',
-8
View File
@@ -57,14 +57,6 @@ export default {
success: '下載記錄已清空',
failed: '清空下載記錄失敗'
},
save: {
title: '儲存設定',
message: '目前下載設定尚未儲存,是否儲存變更?',
confirm: '儲存',
cancel: '取消',
discard: '放棄',
saveSuccess: '下載設定已儲存'
},
message: {
downloadComplete: '{filename} 下載完成',
downloadFailed: '{filename} 下載失敗: {error}'
+1 -3
View File
@@ -9,7 +9,5 @@ export default {
emptyState: '暫無本地音樂,請先選擇資料夾進行掃描',
fileNotFound: '檔案不存在或已被移動',
rescan: '重新掃描',
songCount: '{count} 首歌曲',
removeFromLibrary: '從本機清單移除',
removedFromLibrary: '已從本機清單移除(不刪除檔案)'
songCount: '{count} 首歌曲'
};
-1
View File
@@ -58,7 +58,6 @@ export default {
eq: '等化器',
playList: '播放清單',
reparse: '重新解析',
download: '下載',
playMode: {
sequence: '順序播放',
loop: '循環播放',
+7 -8
View File
@@ -124,26 +124,26 @@ export default {
lxMusic: {
tabs: {
sources: '音源選擇',
lxMusic: '雪音源',
lxMusic: '雪音源',
customApi: '自訂API'
},
scripts: {
title: '已匯入的音源腳本',
importLocal: '本機匯入',
importOnline: '線上匯入',
urlPlaceholder: '輸入雪音源腳本 URL',
urlPlaceholder: '輸入雪音源腳本 URL',
importBtn: '匯入',
empty: '暫無已匯入的雪音源',
notConfigured: '未設定 (請至雪音源分頁設定)',
empty: '暫無已匯入的雪音源',
notConfigured: '未設定 (請至雪音源分頁設定)',
importHint: '匯入相容的自訂 API 外掛以擴充音源',
noScriptWarning: '請先匯入雪音源腳本',
noSelectionWarning: '請先選擇一個雪音源',
noScriptWarning: '請先匯入雪音源腳本',
noSelectionWarning: '請先選擇一個雪音源',
notFound: '音源不存在',
switched: '已切換到音源: {name}',
deleted: '已刪除音源: {name}',
enterUrl: '請輸入腳本 URL',
invalidUrl: '無效的 URL 格式',
invalidScript: '無效的雪音源腳本,未找到 globalThis.lx 相關程式碼',
invalidScript: '無效的雪音源腳本,未找到 globalThis.lx 相關程式碼',
nameRequired: '名稱不能為空',
renameSuccess: '重新命名成功'
}
@@ -387,7 +387,6 @@ export default {
themeColor: {
title: '歌詞主題色',
presetColors: '預設顏色',
reset: '恢復預設',
customColor: '自訂顏色',
preview: '預覽效果',
previewText: '歌詞效果',
-1
View File
@@ -13,7 +13,6 @@ export default {
},
message: {
downloading: '正在下載中,請稍候...',
addToPlaylistNeedLogin: '請使用 Cookie 或掃碼登入後再新增至播放清單(UID 登入無法使用此功能)',
downloadFailed: '下載失敗',
downloadQueued: '已加入下載佇列',
addedToNextPlay: '已新增至下一首播放',
+2 -6
View File
@@ -18,13 +18,9 @@ const mainI18n = {
},
t(key: string) {
const keys = key.split('.');
// 未知/非法 locale 时回退默认语言,避免 messages[locale] 为 undefined 导致崩溃
let current: any = messages[this.currentLocale] ?? messages[DEFAULT_LANGUAGE as Language];
if (current == null) {
return key;
}
let current: any = messages[this.currentLocale];
for (const k of keys) {
if (current == null || current[k] === undefined) {
if (current[k] === undefined) {
// 如果找不到翻译,返回键名
return key;
}
+3 -53
View File
@@ -1,43 +1,7 @@
import { electronApp, optimizer } from '@electron-toolkit/utils';
import { app, dialog, ipcMain, nativeImage, protocol, session } from 'electron';
import { app, ipcMain, nativeImage, session } from 'electron';
import { join } from 'path';
// 全局兜底(#714):Windows 上 config.json 等文件可能被杀毒/云同步软件短暂锁定,
// electron-store 读写撞锁会抛 EBUSY 等未捕获异常,Electron 默认弹出致命错误框。
// 对带 path 的文件系统锁类错误仅记录日志;其余异常保留报错弹窗以免掩盖真 bug。
const FILE_LOCK_ERROR_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'EAGAIN', 'EMFILE', 'ENFILE']);
process.on('uncaughtException', (error: NodeJS.ErrnoException) => {
if (error?.code && FILE_LOCK_ERROR_CODES.has(error.code) && typeof error.path === 'string') {
console.error('[main] 文件被占用/锁定,已忽略本次读写:', error.message);
return;
}
console.error('[main] 未捕获异常:', error);
dialog.showErrorBox(
'A JavaScript error occurred in the main process',
error?.stack || String(error)
);
});
process.on('unhandledRejection', (reason) => {
console.error('[main] 未处理的 Promise 拒绝:', reason);
});
// 必须在 app.whenReady() 之前注册自定义协议为特权协议,
// 否则 http(s) 页面(dev server、生产环境的 file://)无法把 local:// 当成
// 安全/可 fetch/可流式的资源加载,会触发 CORS 拦截或 net::ERR_UNKNOWN_URL_SCHEME
protocol.registerSchemesAsPrivileged([
{
scheme: 'local',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
stream: true,
bypassCSP: true,
corsEnabled: true
}
}
]);
import type { Language } from '../i18n/main';
import i18n from '../i18n/main';
import { loadLyricWindow } from './lyric';
@@ -49,7 +13,6 @@ import { initializeFonts } from './modules/fonts';
import { initializeLocalMusicScanner } from './modules/localMusicScanner';
import { initializeLoginWindow } from './modules/loginWindow';
import { initLxMusicHttp } from './modules/lxMusicHttp';
import { initializeMpris, updateMprisCurrentSong, updateMprisPlayState } from './modules/mpris';
import { initializeOtherApi } from './modules/otherApi';
import { initializeRemoteControl } from './modules/remoteControl';
import { initializeShortcuts } from './modules/shortcuts';
@@ -119,9 +82,6 @@ function initialize(configStore: any) {
// 初始化远程控制服务
initializeRemoteControl(mainWindow);
// 初始化 MPRIS 服务 (Linux)
initializeMpris(mainWindow);
// 初始化更新处理程序
setupUpdateHandlers(mainWindow);
}
@@ -132,11 +92,6 @@ const isSingleInstance = app.requestSingleInstanceLock();
if (!isSingleInstance) {
app.quit();
} else {
// 禁用 Chromium 内置的 MediaSession MPRIS 服务,避免重复显示
if (process.platform === 'linux') {
app.commandLine.appendSwitch('disable-features', 'MediaSessionService');
}
// 在应用准备就绪前初始化GPU加速设置
// 必须在 app.ready 之前调用 disableHardwareAcceleration
try {
@@ -178,18 +133,15 @@ if (!isSingleInstance) {
// 初始化窗口大小管理器
initWindowSizeManager();
// 媒体设备权限:应用没有任何录音功能,麦克风/摄像头采集一律拒绝,
// 防止依赖库静默调用 getUserMedia 触发系统麦克风授权弹窗(#147/#246/#440/#639 防御性加固)。
// 输出设备切换走 speaker-selection / enumerateDevices,不受影响
// 设置媒体设备权限 - 允许枚举音频输出设备
session.defaultSession.setPermissionRequestHandler((_webContents, permission, callback) => {
if (permission === ('media' as any) || permission === ('audioCapture' as any)) {
callback(false);
callback(true);
return;
}
callback(true);
});
// 保持放行:enumerateDevices 依赖它返回真实设备名(不访问麦克风硬件、不触发系统授权)
session.defaultSession.setPermissionCheckHandler(() => {
return true;
});
@@ -219,13 +171,11 @@ if (!isSingleInstance) {
// 监听播放状态变化
ipcMain.on('update-play-state', (_, playing: boolean) => {
updatePlayState(playing);
updateMprisPlayState(playing);
});
// 监听当前歌曲变化
ipcMain.on('update-current-song', (_, song: any) => {
updateCurrentSong(song);
updateMprisCurrentSong(song);
});
// 所有窗口关闭时的处理
+6 -114
View File
@@ -1,92 +1,15 @@
import { BrowserWindow, IpcMain, screen } from 'electron';
import Store from 'electron-store';
import path, { join } from 'path';
import { getSharedStore } from './modules/config';
const store = getSharedStore();
const store = new Store();
let lyricWindow: BrowserWindow | null = null;
// 歌词窗口 bounds 防抖保存:拖动/缩放时高频触发,
// 直接写盘会加剧 config.json 文件争用(#714 EBUSY
let lyricBoundsSaveTimer: ReturnType<typeof setTimeout> | null = null;
const saveLyricWindowBounds = (bounds: Record<string, number>) => {
if (lyricBoundsSaveTimer) {
clearTimeout(lyricBoundsSaveTimer);
}
lyricBoundsSaveTimer = setTimeout(() => {
lyricBoundsSaveTimer = null;
try {
store.set('lyricWindowBounds', bounds);
} catch (error) {
console.error('保存歌词窗口位置失败:', error);
}
}, 500);
};
// 跟踪拖动状态
let isDragging = false;
// 添加窗口大小变化防护
let originalSize = { width: 0, height: 0 };
// 鼠标位置轮询仅在"锁定 + 可见"时启用,解锁态下 DOM 事件已足够
let mousePresenceTimer: ReturnType<typeof setInterval> | null = null;
let lastMouseInside: boolean | null = null;
let isLyricLocked = false;
let isLyricWindowVisible = false;
const isPointInsideWindow = (
point: { x: number; y: number },
bounds: { x: number; y: number; width: number; height: number }
) => {
return (
point.x >= bounds.x &&
point.x < bounds.x + bounds.width &&
point.y >= bounds.y &&
point.y < bounds.y + bounds.height
);
};
const stopMousePresenceTracking = () => {
if (mousePresenceTimer) {
clearInterval(mousePresenceTimer);
mousePresenceTimer = null;
}
lastMouseInside = null;
};
const emitMousePresence = () => {
if (!lyricWindow || lyricWindow.isDestroyed()) return;
const mousePoint = screen.getCursorScreenPoint();
const bounds = lyricWindow.getBounds();
const isInside = isPointInsideWindow(mousePoint, bounds);
if (isInside === lastMouseInside) return;
lastMouseInside = isInside;
lyricWindow.webContents.send('lyric-mouse-presence', isInside);
};
const startMousePresenceTracking = () => {
if (mousePresenceTimer) return;
emitMousePresence();
mousePresenceTimer = setInterval(() => {
if (!lyricWindow || lyricWindow.isDestroyed()) {
stopMousePresenceTracking();
return;
}
emitMousePresence();
}, 50);
};
const syncMousePresenceTracking = () => {
if (isLyricLocked && isLyricWindowVisible && lyricWindow && !lyricWindow.isDestroyed()) {
startMousePresenceTracking();
} else {
stopMousePresenceTracking();
}
};
const createWin = () => {
console.log('Creating lyric window');
@@ -179,32 +102,12 @@ const createWin = () => {
// 监听窗口关闭事件
lyricWindow.on('closed', () => {
stopMousePresenceTracking();
isLyricLocked = false;
isLyricWindowVisible = false;
if (lyricWindow) {
lyricWindow.destroy();
lyricWindow = null;
}
});
lyricWindow.on('show', () => {
isLyricWindowVisible = true;
syncMousePresenceTracking();
});
lyricWindow.on('hide', () => {
isLyricWindowVisible = false;
stopMousePresenceTracking();
});
lyricWindow.on('minimize', () => {
isLyricWindowVisible = false;
stopMousePresenceTracking();
});
lyricWindow.on('restore', () => {
isLyricWindowVisible = true;
syncMousePresenceTracking();
});
// 监听窗口大小变化事件,保存新的尺寸
lyricWindow.on('resize', () => {
// 如果正在拖动,忽略大小调整事件
@@ -214,8 +117,8 @@ const createWin = () => {
const [width, height] = lyricWindow.getSize();
const [x, y] = lyricWindow.getPosition();
// 保存窗口位置和大小(防抖)
saveLyricWindowBounds({ x, y, width, height });
// 保存窗口位置和大小
store.set('lyricWindowBounds', { x, y, width, height });
}
});
@@ -302,17 +205,6 @@ export const loadLyricWindow = (ipcMain: IpcMain, mainWin: BrowserWindow): void
}
});
ipcMain.on('set-lyric-lock-state', (_, isLocked: boolean) => {
isLyricLocked = isLocked;
if (lyricWindow && !lyricWindow.isDestroyed()) {
// 锁定时禁用 resize,避免鼠标移到边缘仍显示调整光标
lyricWindow.setResizable(!isLocked);
// 设置初始穿透状态,后续 polling 会按实际位置纠正
lyricWindow.setIgnoreMouseEvents(isLocked, { forward: true });
}
syncMousePresenceTracking();
});
// 处理鼠标事件
ipcMain.on('mouseenter-lyric', () => {
if (lyricWindow && !lyricWindow.isDestroyed()) {
@@ -375,7 +267,7 @@ export const loadLyricWindow = (ipcMain: IpcMain, mainWin: BrowserWindow): void
false
);
// 更新存储的位置(防抖,拖动结束后统一落盘)
// 更新存储的位置
const windowBounds = {
x: newX,
y: newY,
@@ -383,7 +275,7 @@ export const loadLyricWindow = (ipcMain: IpcMain, mainWin: BrowserWindow): void
height: windowHeight,
displayId: currentDisplay.id // 记录当前显示器ID,有助于多屏幕处理
};
saveLyricWindowBounds(windowBounds);
store.set('lyricWindowBounds', windowBounds);
} catch (error) {
console.error('Error during window drag:', error);
// 出错时尝试使用更简单的方法
+3 -5
View File
@@ -6,7 +6,6 @@ import Store from 'electron-store';
import * as fs from 'fs';
import * as path from 'path';
import { filePathToLocalUrl } from '../../shared/localUrl';
import { getStore } from './config';
type CacheCleanupPolicy = 'lru' | 'fifo';
@@ -413,9 +412,7 @@ class DiskCacheManager {
cleanupPolicy
};
// 注意:getCacheConfig 是纯读取,处于播放/下载/歌词等多个热路径。
// 此处不再落盘(electron-store.set 每次整文件写 config.json,会造成写放大与文件争用),
// 持久化交由 updateCacheConfig / setCacheDirectory 等真正的写操作完成。
this.saveConfig(normalizedConfig);
return normalizedConfig;
}
@@ -538,7 +535,8 @@ class DiskCacheManager {
}
private toLocalUrl(filePath: string): string {
return filePathToLocalUrl(path.normalize(filePath));
const normalized = path.normalize(filePath).replace(/\\/g, '/');
return `local:///${encodeURIComponent(normalized)}`;
}
private isRemoteAudioUrl(url: string): boolean {
+24 -54
View File
@@ -38,63 +38,41 @@ interface StoreType {
shortcuts: ShortcutsConfig;
}
// 模块级单例:主进程所有模块共享同一个 config.json Store 实例。
// 多个独立 Store 实例并发读写同一文件,会在 Windows 上与杀毒/云同步的文件锁
// 叠加触发 EBUSY 未捕获异常(#714)
const store = new Store<StoreType>({
name: 'config',
defaults: {
set: set as SetConfig,
shortcuts: createDefaultShortcuts()
}
});
let initialized = false;
let store: Store<StoreType>;
/**
* IPC
*
*/
export function initializeConfig() {
if (initialized) {
return store;
}
initialized = true;
store = new Store<StoreType>({
name: 'config',
defaults: {
set: set as SetConfig,
shortcuts: createDefaultShortcuts()
}
});
try {
store.get('set.downloadPath') || store.set('set.downloadPath', app.getPath('downloads'));
store.get('set.diskCacheDir') ||
store.set('set.diskCacheDir', path.join(app.getPath('userData'), 'cache'));
if (store.get('set.diskCacheMaxSizeMB') === undefined) {
store.set('set.diskCacheMaxSizeMB', 4096);
}
if (!store.get('set.diskCacheCleanupPolicy')) {
store.set('set.diskCacheCleanupPolicy', 'lru');
}
if (store.get('set.enableDiskCache') === undefined) {
store.set('set.enableDiskCache', true);
}
} catch (error) {
console.error('[config] 初始化默认配置失败:', error);
store.get('set.downloadPath') || store.set('set.downloadPath', app.getPath('downloads'));
store.get('set.diskCacheDir') ||
store.set('set.diskCacheDir', path.join(app.getPath('userData'), 'cache'));
if (store.get('set.diskCacheMaxSizeMB') === undefined) {
store.set('set.diskCacheMaxSizeMB', 4096);
}
if (!store.get('set.diskCacheCleanupPolicy')) {
store.set('set.diskCacheCleanupPolicy', 'lru');
}
if (store.get('set.enableDiskCache') === undefined) {
store.set('set.enableDiskCache', true);
}
// 定义ipcRenderer监听事件
ipcMain.on('set-store-value', (_, key, value) => {
try {
store.set(key, value);
} catch (error) {
// config.json 可能被杀毒/云同步短暂锁定,丢一次写入无害,避免主进程崩溃
console.error(`[config] 写入配置失败 key=${key}:`, error);
}
store.set(key, value);
});
ipcMain.on('get-store-value', (event, key) => {
try {
const value = store.get(key);
event.returnValue = value || '';
} catch (error) {
console.error(`[config] 读取配置失败 key=${key}:`, error);
event.returnValue = '';
}
ipcMain.on('get-store-value', (_, key) => {
const value = store.get(key);
_.returnValue = value || '';
});
// GPU加速设置更新处理
@@ -120,11 +98,3 @@ export function initializeConfig() {
export function getStore() {
return store;
}
/**
* config.json Store
* new Store() #714 EBUSY
*/
export function getSharedStore(): Store<Record<string, unknown>> {
return store as unknown as Store<Record<string, unknown>>;
}
+2 -3
View File
@@ -1,10 +1,9 @@
import { app } from 'electron';
import Store from 'electron-store';
import { machineIdSync } from 'node-machine-id';
import os from 'os';
import { getSharedStore } from './config';
const store = getSharedStore();
const store = new Store();
/**
*
+2 -8
View File
@@ -484,17 +484,13 @@ class DownloadManager {
}
// Start download
// 注意:axios 默认只接受 2xx403/410 会直接抛错进入 catch,导致下方"直链过期重新解析"
// 分支永远走不到。这里放行 403/410,让过期直链能触发重新解析(尤其是重启后恢复队列时)。
const response = await axios({
url: task.url,
method: 'GET',
responseType: 'stream',
timeout: 30000,
signal: controller.signal,
headers,
validateStatus: (status) =>
(status >= 200 && status < 300) || status === 403 || status === 410
headers
});
// Handle response status
@@ -502,8 +498,6 @@ class DownloadManager {
if (status === 403 || status === 410) {
// URL expired, request re-resolution from renderer
// 排空未消费的错误响应流,避免连接悬挂
response.data?.destroy?.();
this.sendToRenderer('download:request-url', {
taskId: task.taskId,
songInfo: task.songInfo
@@ -529,7 +523,7 @@ class DownloadManager {
} else {
// Full response (200) - start from beginning
task.loaded = 0;
const contentLength = response.headers['content-length'] as string;
const contentLength = response.headers['content-length'];
task.total = contentLength ? parseInt(contentLength, 10) : 0;
}
+12 -56
View File
@@ -2,7 +2,6 @@ import { app, dialog, ipcMain, protocol, shell } from 'electron';
import Store from 'electron-store';
import * as fs from 'fs';
import * as path from 'path';
import { Readable } from 'stream';
import { getStore } from './config';
@@ -24,79 +23,36 @@ function sanitizeFilename(filename: string): string {
.trim();
}
// Electron net.fetch(file://) 在当前版本不会回 206audio seek 需要主进程自己处理 Range
function buildLocalFileResponse(
filePath: string,
total: number,
rangeHeader: string | null
): Response {
const range416 = () =>
new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${total}` } });
let start = 0;
let end = total - 1;
let partial = false;
if (rangeHeader) {
const m = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
if (!m || (!m[1] && !m[2])) return range416();
if (m[1]) {
start = parseInt(m[1], 10);
if (m[2]) end = Math.min(parseInt(m[2], 10), end);
} else {
start = Math.max(0, total - parseInt(m[2], 10));
}
if (start > end || start >= total) return range416();
partial = true;
}
return new Response(
Readable.toWeb(fs.createReadStream(filePath, { start, end })) as ReadableStream,
{
status: partial ? 206 : 200,
headers: {
'Content-Length': String(end - start + 1),
'Accept-Ranges': 'bytes',
...(partial && { 'Content-Range': `bytes ${start}-${end}/${total}` })
}
}
);
}
/**
* IPC监听
*/
export function initializeFileManager() {
// 注册本地文件协议
// Electron 25+ 起 registerFileProtocol 已弃用,改用 protocol.handle,并配合 main/index.ts
// 中的 registerSchemesAsPrivileged,让 audio 元素能从 http(s) 页面跨协议加载本地文件
protocol.handle('local', async (request) => {
protocol.registerFileProtocol('local', (request, callback) => {
try {
// local:///<absolute-path>
let filePath = decodeURIComponent(request.url.replace(/^local:\/\/\/?/, ''));
const url = request.url;
// local://C:/Users/xxx.mp3
let filePath = decodeURIComponent(url.replace('local:///', ''));
// Windows: 协议解析后可能是 /C:/...,去掉前导斜杠
// 兼容 local:///C:/Users/xxx.mp3 这种情况
if (/^\/[a-zA-Z]:\//.test(filePath)) {
filePath = filePath.slice(1);
}
// macOS/Linux 上去掉前导斜杠后会丢失绝对路径标识,这里补回
if (process.platform !== 'win32' && !filePath.startsWith('/')) {
filePath = '/' + filePath;
}
// 还原为系统路径格式
filePath = path.normalize(filePath);
const stat = await fs.promises.stat(filePath).catch(() => null);
if (!stat?.isFile()) {
// 检查文件是否存在
if (!fs.existsSync(filePath)) {
console.error('File not found:', filePath);
return new Response(null, { status: 404 });
callback({ error: -6 }); // net::ERR_FILE_NOT_FOUND
return;
}
return buildLocalFileResponse(filePath, stat.size, request.headers.get('range'));
callback({ path: filePath });
} catch (error) {
console.error('Error handling local protocol:', error);
return new Response(null, { status: 500 });
callback({ error: -2 }); // net::FAILED
}
});
+13 -51
View File
@@ -1,8 +1,7 @@
// 本地音乐扫描模块
// 负责文件系统递归扫描和音乐文件元数据提取,通过 IPC 暴露给渲染进程
import * as crypto from 'crypto';
import { app, ipcMain } from 'electron';
import { ipcMain } from 'electron';
import * as fs from 'fs';
import * as mm from 'music-metadata';
import * as os from 'os';
@@ -11,30 +10,7 @@ import * as path from 'path';
/** 支持的音频文件格式 */
const SUPPORTED_AUDIO_FORMATS = ['.mp3', '.flac', '.wav', '.ogg', '.m4a', '.aac'] as const;
const METADATA_PARSE_CONCURRENCY = Math.min(8, Math.max(2, os.cpus().length));
const MAX_COVER_BYTES = 8 * 1024 * 1024;
/** 封面缓存目录:userData/AudioCovers/<hash>.<ext> */
const COVER_DIR_NAME = 'AudioCovers';
let cachedCoverDir: string | null = null;
function getCoverDir(): string {
if (cachedCoverDir) return cachedCoverDir;
const dir = path.join(app.getPath('userData'), COVER_DIR_NAME);
try {
fs.mkdirSync(dir, { recursive: true });
} catch (error) {
console.error('创建封面目录失败:', error);
}
cachedCoverDir = dir;
return dir;
}
/** 从 mime 类型推断文件扩展名 */
function extFromMime(mime: string | undefined): string {
const sub = mime?.split('/')[1]?.split(';')[0]?.trim().toLowerCase();
if (!sub) return 'bin';
return sub === 'jpeg' ? 'jpg' : sub;
}
const MAX_COVER_BYTES = 1024 * 1024;
/**
*
@@ -51,8 +27,8 @@ type LocalMusicMeta = {
album: string;
/** 时长(毫秒) */
duration: number;
/** 封面图片缓存文件绝对路径,无封面时为 null */
coverPath: string | null;
/** base64 Data URL 格式的封面图片,无封面时为 null */
cover: string | null;
/** LRC 格式歌词文本,无歌词时为 null */
lyrics: string | null;
/** 文件大小(字节) */
@@ -90,37 +66,23 @@ function extractTitleFromFilename(filePath: string): string {
}
/**
* userData/AudioCovers/
* sourceFilePath sha256 +
* base64 Data URL
* @param picture music-metadata
* @param sourceFilePath
* @returns null
* @returns base64 Data URL null
*/
async function extractCoverToFile(
picture: mm.IPicture | undefined,
sourceFilePath: string
): Promise<string | null> {
function extractCoverAsDataUrl(picture: mm.IPicture | undefined): string | null {
if (!picture) {
return null;
}
try {
if (picture.data.length > MAX_COVER_BYTES) {
console.warn(
`封面超过大小上限被跳过: ${sourceFilePath} (${picture.data.length} bytes > ${MAX_COVER_BYTES})`
);
return null;
}
const ext = extFromMime(picture.format);
const hash = crypto.createHash('sha256').update(sourceFilePath).digest('hex');
const coverFile = path.join(getCoverDir(), `${hash}.${ext}`);
// 直接覆盖写:本函数只在文件 mtime 变更时被调用(见 scanFolders 的 parseTargets),
// 频率本就受守门;按 size 跳过会在"用户替换内嵌封面、新旧字节数恰好相等"时留旧图,
// 单张封面几十~几百 KB,覆盖代价可忽略。
await fs.promises.writeFile(coverFile, Buffer.from(picture.data));
return coverFile;
const mime = picture.format ?? 'image/jpeg';
const base64 = Buffer.from(picture.data).toString('base64');
return `data:${mime};base64,${base64}`;
} catch (error) {
console.error('封面落盘失败:', error);
console.error('封面提取失败:', error);
return null;
}
}
@@ -272,7 +234,7 @@ async function parseMetadata(filePath: string): Promise<LocalMusicMeta> {
artist: '未知艺术家',
album: '未知专辑',
duration: 0,
coverPath: null,
cover: null,
lyrics: null,
fileSize,
modifiedTime
@@ -288,7 +250,7 @@ async function parseMetadata(filePath: string): Promise<LocalMusicMeta> {
artist: common.artist || fallback.artist,
album: common.album || fallback.album,
duration: format.duration ? Math.round(format.duration * 1000) : 0,
coverPath: await extractCoverToFile(common.picture?.[0], filePath),
cover: extractCoverAsDataUrl(common.picture?.[0]),
lyrics: extractLyrics(common.lyrics),
fileSize,
modifiedTime
+2 -2
View File
@@ -6,6 +6,7 @@ import i18n from '../../i18n/main';
let loginWindow: BrowserWindow | null = null;
const loginUrl = 'https://music.163.com/#/login/';
const loginTitle = i18n.global.t('login.qrTitle');
/**
* Cookie
@@ -28,8 +29,7 @@ const openLoginWindow = async (mainWin: BrowserWindow) => {
loginWindow = new BrowserWindow({
parent: mainWin,
// 在打开窗口时求值,确保跟随当前语言(模块加载时 i18n locale 可能尚未设置)
title: i18n.global.t('login.qrTitle'),
title: loginTitle,
width: 1280,
height: 800,
center: true,
+2 -8
View File
@@ -42,8 +42,6 @@ export const initLxMusicHttp = () => {
// 保存取消控制器
abortControllers.set(requestId, controller);
let timeoutId: ReturnType<typeof setTimeout> | null = null;
try {
console.log(`[LxMusicHttp] 请求: ${options.method || 'GET'} ${url}`);
@@ -79,14 +77,13 @@ export const initLxMusicHttp = () => {
// 设置超时
const timeout = options.timeout || 30000;
timeoutId = setTimeout(() => {
const timeoutId = setTimeout(() => {
console.warn(`[LxMusicHttp] 请求超时: ${url}`);
controller.abort();
}, timeout);
const response = await fetch(url, fetchOptions);
clearTimeout(timeoutId);
timeoutId = null;
console.log(`[LxMusicHttp] 响应: ${response.status} ${url}`);
@@ -125,10 +122,7 @@ export const initLxMusicHttp = () => {
console.error(`[LxMusicHttp] 请求失败: ${url}`, error.message);
throw error;
} finally {
// 清理超时定时器(fetch 出错时前面来不及 clear)与取消控制器
if (timeoutId) {
clearTimeout(timeoutId);
}
// 清理取消控制器
abortControllers.delete(requestId);
}
}
-270
View File
@@ -1,270 +0,0 @@
import { app, BrowserWindow, ipcMain } from 'electron';
import Player from 'mpris-service';
let dbusModule: any;
try {
dbusModule = require('@httptoolkit/dbus-native');
} catch {
// dbus-native 不可用(非 Linux 环境)
}
interface SongInfo {
id?: number | string;
name: string;
picUrl?: string;
ar?: Array<{ name: string }>;
artists?: Array<{ name: string }>;
al?: { name: string };
album?: { name: string };
duration?: number;
dt?: number;
song?: {
artists?: Array<{ name: string }>;
album?: { name: string };
duration?: number;
picUrl?: string;
};
[key: string]: any;
}
let mprisPlayer: Player | null = null;
let mainWindow: BrowserWindow | null = null;
let currentPosition = 0;
let trayLyricIface: any = null;
let trayLyricBus: any = null;
// 保存 IPC 处理函数引用,用于清理
let onPositionUpdate: ((event: any, position: number) => void) | null = null;
let onTrayLyricUpdate: ((event: any, lrcObj: string) => void) | null = null;
export function initializeMpris(mainWindowRef: BrowserWindow) {
if (process.platform !== 'linux') return;
if (mprisPlayer) {
return;
}
mainWindow = mainWindowRef;
try {
mprisPlayer = Player({
name: 'AlgerMusicPlayer',
identity: 'Alger Music Player',
supportedUriSchemes: ['file', 'http', 'https'],
supportedMimeTypes: [
'audio/mpeg',
'audio/mp3',
'audio/flac',
'audio/wav',
'audio/ogg',
'audio/aac',
'audio/m4a'
],
supportedInterfaces: ['player']
});
mprisPlayer.on('quit', () => {
app.quit();
});
mprisPlayer.on('raise', () => {
if (mainWindow) {
mainWindow.show();
mainWindow.focus();
}
});
mprisPlayer.on('next', () => {
if (mainWindow) {
mainWindow.webContents.send('global-shortcut', 'nextPlay');
}
});
mprisPlayer.on('previous', () => {
if (mainWindow) {
mainWindow.webContents.send('global-shortcut', 'prevPlay');
}
});
mprisPlayer.on('pause', () => {
if (mainWindow) {
mainWindow.webContents.send('mpris-pause');
}
});
mprisPlayer.on('play', () => {
if (mainWindow) {
mainWindow.webContents.send('mpris-play');
}
});
mprisPlayer.on('playpause', () => {
if (mainWindow) {
mainWindow.webContents.send('global-shortcut', 'togglePlay');
}
});
mprisPlayer.on('stop', () => {
if (mainWindow) {
mainWindow.webContents.send('mpris-pause');
}
});
mprisPlayer.getPosition = (): number => {
return currentPosition;
};
mprisPlayer.on('seek', (offset: number) => {
if (mainWindow) {
const newPosition = Math.max(0, currentPosition + offset / 1000000);
mainWindow.webContents.send('mpris-seek', newPosition);
}
});
mprisPlayer.on('position', (event: { trackId: string; position: number }) => {
if (mainWindow) {
mainWindow.webContents.send('mpris-set-position', event.position / 1000000);
}
});
onPositionUpdate = (_, position: number) => {
currentPosition = position * 1000 * 1000;
if (mprisPlayer) {
mprisPlayer.seeked(position * 1000 * 1000);
mprisPlayer.getPosition = () => position * 1000 * 1000;
mprisPlayer.position = position * 1000 * 1000;
}
};
ipcMain.on('mpris-position-update', onPositionUpdate);
onTrayLyricUpdate = (_, lrcObj: string) => {
sendTrayLyric(lrcObj);
};
ipcMain.on('tray-lyric-update', onTrayLyricUpdate);
initTrayLyric();
console.log('[MPRIS] Service initialized');
} catch (error) {
console.error('[MPRIS] Failed to initialize:', error);
}
}
export function updateMprisPlayState(playing: boolean) {
if (!mprisPlayer || process.platform !== 'linux') return;
mprisPlayer.playbackStatus = playing ? 'Playing' : 'Paused';
}
export function updateMprisCurrentSong(song: SongInfo | null) {
if (!mprisPlayer || process.platform !== 'linux') return;
if (!song) {
mprisPlayer.metadata = {};
mprisPlayer.playbackStatus = 'Stopped';
return;
}
const artists =
song.ar?.map((a) => a.name).join(', ') ||
song.artists?.map((a) => a.name).join(', ') ||
song.song?.artists?.map((a) => a.name).join(', ') ||
'';
const album = song.al?.name || song.album?.name || song.song?.album?.name || '';
const duration = song.duration || song.dt || song.song?.duration || 0;
mprisPlayer.metadata = {
'mpris:trackid': mprisPlayer.objectPath(`track/${song.id || 0}`),
'mpris:length': duration * 1000,
'mpris:artUrl': song.picUrl || '',
'xesam:title': song.name || '',
'xesam:album': album,
'xesam:artist': artists ? [artists] : []
};
}
export function updateMprisPosition(position: number) {
if (!mprisPlayer || process.platform !== 'linux') return;
mprisPlayer.seeked(position * 1000000);
}
export function destroyMpris() {
if (onPositionUpdate) {
ipcMain.removeListener('mpris-position-update', onPositionUpdate);
onPositionUpdate = null;
}
if (onTrayLyricUpdate) {
ipcMain.removeListener('tray-lyric-update', onTrayLyricUpdate);
onTrayLyricUpdate = null;
}
if (mprisPlayer) {
mprisPlayer.quit();
mprisPlayer = null;
}
}
function initTrayLyric() {
if (process.platform !== 'linux' || !dbusModule) return;
const serviceName = 'org.gnome.Shell.TrayLyric';
try {
const sessionBus = dbusModule.sessionBus({});
trayLyricBus = sessionBus;
const dbusPath = '/org/freedesktop/DBus';
const dbusInterface = 'org.freedesktop.DBus';
sessionBus.invoke(
{
path: dbusPath,
interface: dbusInterface,
member: 'GetNameOwner',
destination: 'org.freedesktop.DBus',
signature: 's',
body: [serviceName]
},
(err: any, result: any) => {
if (err || !result) {
console.log('[TrayLyric] Service not running');
} else {
onServiceAvailable();
}
}
);
} catch (err) {
console.error('[TrayLyric] Failed to init:', err);
}
function onServiceAvailable() {
if (!trayLyricBus) return;
const path = '/' + serviceName.replace(/\./g, '/');
trayLyricBus.getService(serviceName).getInterface(path, serviceName, (err: any, iface: any) => {
if (err) {
console.error('[TrayLyric] Failed to get service interface:', err);
return;
}
trayLyricIface = iface;
console.log('[TrayLyric] Service interface ready');
});
}
}
function sendTrayLyric(lrcObj: string) {
if (!trayLyricIface || !trayLyricBus) return;
trayLyricBus.invoke(
{
path: '/org/gnome/Shell/TrayLyric',
interface: 'org.gnome.Shell.TrayLyric',
member: 'UpdateLyric',
destination: 'org.gnome.Shell.TrayLyric',
signature: 's',
body: [lrcObj]
},
(err: any, _result: any) => {
if (err) {
console.error('[TrayLyric] Failed to invoke UpdateLyric:', err);
}
}
);
}
+13 -54
View File
@@ -1,9 +1,7 @@
import { app, BrowserWindow, ipcMain, screen } from 'electron';
import type Store from 'electron-store';
import Store from 'electron-store';
import { getSharedStore } from './config';
const store = getSharedStore();
const store = new Store();
// 默认窗口尺寸
export const DEFAULT_MAIN_WIDTH = 1200;
@@ -40,40 +38,16 @@ export interface WindowState {
*
*/
class WindowSizeManager {
private store: Store<Record<string, unknown>>;
private store: Store;
private mainWindow: BrowserWindow | null = null;
private savedState: WindowState | null = null;
private isInitialized: boolean = false;
private saveStateDebounceTimer: ReturnType<typeof setTimeout> | null = null;
constructor() {
this.store = store;
// 初始化时不做与screen相关的操作,等app ready后再初始化
}
/**
* move/resize
* config.json #714 EBUSY
*/
private scheduleSaveWindowState(win: BrowserWindow): void {
if (this.saveStateDebounceTimer) {
clearTimeout(this.saveStateDebounceTimer);
}
this.saveStateDebounceTimer = setTimeout(() => {
this.saveStateDebounceTimer = null;
if (!win.isDestroyed() && !win.isMinimized()) {
this.saveWindowState(win);
}
}, 500);
}
private flushScheduledSave(): void {
if (this.saveStateDebounceTimer) {
clearTimeout(this.saveStateDebounceTimer);
this.saveStateDebounceTimer = null;
}
}
/**
*
* app ready后调用
@@ -143,17 +117,17 @@ class WindowSizeManager {
*
*/
private setupEventListeners(win: BrowserWindow): void {
// 监听窗口大小调整事件(防抖,拖动结束后统一落盘)
// 监听窗口大小调整事件
win.on('resize', () => {
if (!win.isDestroyed() && !win.isMinimized()) {
this.scheduleSaveWindowState(win);
this.saveWindowState(win);
}
});
// 监听窗口移动事件(防抖,拖动结束后统一落盘)
// 监听窗口移动事件
win.on('move', () => {
if (!win.isDestroyed() && !win.isMinimized()) {
this.scheduleSaveWindowState(win);
this.saveWindowState(win);
}
});
@@ -171,9 +145,8 @@ class WindowSizeManager {
}
});
// 监听窗口关闭事件,确保保存最终状态(取消挂起的防抖,立即落盘)
// 监听窗口关闭事件,确保保存最终状态
win.on('close', () => {
this.flushScheduledSave();
if (!win.isDestroyed()) {
this.saveWindowState(win);
}
@@ -381,12 +354,8 @@ class WindowSizeManager {
}
// 检查是否是mini模式窗口(根据窗口大小判断)
// 注意展开播放列表后的 mini 窗口是 340x400,也不能当普通窗口持久化,
// 否则污染 windowState 导致下次启动主窗口尺寸异常(#242)
const [currentWidth, currentHeight] = win.getSize();
const isMiniMode =
currentWidth === DEFAULT_MINI_WIDTH &&
(currentHeight === DEFAULT_MINI_HEIGHT || currentHeight === DEFAULT_MINI_EXPANDED_HEIGHT);
const isMiniMode = currentWidth === DEFAULT_MINI_WIDTH && currentHeight === DEFAULT_MINI_HEIGHT;
const isMaximized = win.isMaximized();
let state: WindowState;
@@ -440,13 +409,9 @@ class WindowSizeManager {
return state;
}
// 保存状态到存储config.json 可能被外部程序短暂锁定,失败时丢弃本次写入即可)
try {
this.store.set(WINDOW_STATE_KEY, state);
console.log(`已保存窗口状态: ${JSON.stringify(state)}`);
} catch (error) {
console.error('保存窗口状态失败:', error);
}
// 保存状态到存储
this.store.set(WINDOW_STATE_KEY, state);
console.log(`已保存窗口状态: ${JSON.stringify(state)}`);
// 更新内部状态
this.savedState = state;
@@ -459,13 +424,7 @@ class WindowSizeManager {
*
*/
getWindowState(): WindowState | null {
let state: WindowState | undefined;
try {
state = this.store.get(WINDOW_STATE_KEY) as WindowState | undefined;
} catch (error) {
console.error('读取窗口状态失败:', error);
return this.savedState;
}
const state = this.store.get(WINDOW_STATE_KEY) as WindowState | undefined;
if (!state) {
console.log('未找到保存的窗口状态,将使用默认值');
+2 -2
View File
@@ -9,9 +9,9 @@ import {
session,
shell
} from 'electron';
import Store from 'electron-store';
import { join } from 'path';
import { getSharedStore } from './config';
import {
applyContentZoom,
applyInitialState,
@@ -27,7 +27,7 @@ import {
WindowState
} from './window-size';
const store = getSharedStore();
const store = new Store();
// 保存主窗口引用,以便在 activate 事件中使用
let mainWindowInstance: BrowserWindow | null = null;
+2 -2
View File
@@ -1,9 +1,9 @@
import { ipcMain } from 'electron';
import Store from 'electron-store';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { getSharedStore } from './modules/config';
import { type Platform, unblockMusic } from './unblockMusic';
// 必须在 import netease-cloud-music-api-alger 之前创建 anonymous_token 文件
@@ -12,7 +12,7 @@ if (!fs.existsSync(path.resolve(os.tmpdir(), 'anonymous_token'))) {
fs.writeFileSync(path.resolve(os.tmpdir(), 'anonymous_token'), '', 'utf-8');
}
const store = getSharedStore();
const store = new Store();
// 设置音乐解析的处理程序
ipcMain.handle('unblock-music', async (_event, id, songData, enabledSources) => {
-23
View File
@@ -1,23 +0,0 @@
declare module 'mpris-service' {
interface PlayerOptions {
name: string;
identity: string;
supportedUriSchemes?: string[];
supportedMimeTypes?: string[];
supportedInterfaces?: string[];
}
interface Player {
on(event: string, callback: (...args: any[]) => void): void;
playbackStatus: string;
metadata: Record<string, any>;
position: number;
getPosition: () => number;
seeked(position: number): void;
objectPath(path: string): string;
quit(): void;
}
function Player(options: PlayerOptions): Player;
export = Player;
}
-4
View File
@@ -100,10 +100,6 @@ if (isElectron) {
window.api.onLanguageChanged(handleSetLanguage);
window.electron.ipcRenderer.on('mini-mode', (_, value) => {
settingsStore.setMiniMode(value);
// /
// musicFull true ""
// #242
playerStore.setMusicFull(false);
if (value) {
//
localStorage.setItem('currentRoute', router.currentRoute.value.path);
+13 -108
View File
@@ -56,18 +56,17 @@ export const parseFromGDMusic = async (
}
const songName = data.name || '';
let artistList: string[] = [];
let artistNames = '';
// 处理不同的艺术家字段结构
if (data.artists && Array.isArray(data.artists)) {
artistList = data.artists.map((artist) => artist?.name).filter(Boolean);
artistNames = data.artists.map((artist) => artist.name).join(' ');
} else if (data.ar && Array.isArray(data.ar)) {
artistList = data.ar.map((artist) => artist?.name).filter(Boolean);
} else if (data.artist && typeof data.artist === 'string') {
artistList = [data.artist];
artistNames = data.ar.map((artist) => artist.name).join(' ');
} else if (data.artist) {
artistNames = typeof data.artist === 'string' ? data.artist : '';
}
const artistNames = artistList.join(' ');
const searchQuery = `${songName} ${artistNames}`.trim();
if (!searchQuery || searchQuery.length < 2) {
@@ -83,12 +82,7 @@ export const parseFromGDMusic = async (
// 依次尝试所有音源
for (const source of allSources) {
try {
const result = await searchAndGetUrl(
source,
searchQuery,
{ name: songName, artists: artistList },
quality
);
const result = await searchAndGetUrl(source, searchQuery, quality);
if (result) {
console.log(`GD音乐台成功通过 ${result.source} 解析音乐!`);
// 返回符合原API格式的数据
@@ -138,124 +132,35 @@ interface GDMusicUrlResult {
source: string;
}
type GDSearchItem = {
id: string | number;
name?: string;
artist?: unknown;
source?: string;
};
type ExpectedSong = {
name: string;
artists: string[];
};
const baseUrl = 'https://music-api.gdstudio.xyz/api.php';
/**
* Live//
*/
const normalizeText = (text: string): string => {
const stripped = text
.toLowerCase()
.replace(/[(【[].*?[))】\]]/g, '')
.replace(/[\s\-—_·・'"‘’“”!?.,,。&+]/g, '');
// 整个歌名都在括号里时退化为仅去标点,避免归一化成空串
return stripped || text.toLowerCase().replace(/[\s\-—_·・'"‘’“”!?.,,。&+]/g, '');
};
const getCandidateArtistText = (artist: unknown): string => {
if (Array.isArray(artist)) {
return artist
.map((item) => (typeof item === 'string' ? item : (item as any)?.name || ''))
.join(' ');
}
return typeof artist === 'string' ? artist : '';
};
const isNameMatched = (expectedName: string, candidateName: string): boolean => {
const expected = normalizeText(expectedName);
const candidate = normalizeText(candidateName);
if (!expected || !candidate) return false;
return expected === candidate || candidate.includes(expected) || expected.includes(candidate);
};
/**
*
* /
* "货不对版"#704
*
*/
const pickBestCandidate = (
candidates: GDSearchItem[],
expected: ExpectedSong
): GDSearchItem | null => {
let best: GDSearchItem | null = null;
let bestScore = 0;
for (const item of candidates) {
if (!item || !item.id) continue;
if (!isNameMatched(expected.name, item.name || '')) continue;
const candidateArtist = normalizeText(getCandidateArtistText(item.artist));
let score: number;
if (expected.artists.length === 0) {
// 原曲无歌手信息,歌名匹配即可
score = 2;
} else if (!candidateArtist) {
// 候选缺少歌手信息:保留为低优先级候选
score = 1;
} else {
const artistMatched = expected.artists.some((name) => {
const normalized = normalizeText(name);
return (
!!normalized &&
(candidateArtist.includes(normalized) || normalized.includes(candidateArtist))
);
});
// 有歌手信息但对不上 → 拒绝,这正是"货不对版"的来源
if (!artistMatched) continue;
score = 3;
}
if (score > bestScore) {
best = item;
bestScore = score;
}
}
return best;
};
/**
* URL
* @param source
* @param searchQuery
* @param expected
* @param quality
* @returns URL结果
*/
async function searchAndGetUrl(
source: MusicSourceType,
searchQuery: string,
expected: ExpectedSong,
quality: string
): Promise<GDMusicUrlResult | null> {
// 1. 搜索歌曲(取前5条做校验,而不是盲取第一条)
const searchUrl = `${baseUrl}?types=search&source=${source}&name=${encodeURIComponent(searchQuery)}&count=5&pages=1`;
// 1. 搜索歌曲
const searchUrl = `${baseUrl}?types=search&source=${source}&name=${encodeURIComponent(searchQuery)}&count=1&pages=1`;
console.log(`GD音乐台尝试音源 ${source} 搜索:`, searchUrl);
const searchResponse = await axios.get(searchUrl, { timeout: 5000 });
if (searchResponse.data && Array.isArray(searchResponse.data) && searchResponse.data.length > 0) {
const matchedResult = pickBestCandidate(searchResponse.data as GDSearchItem[], expected);
if (!matchedResult) {
console.log(`GD音乐台 ${source} 搜索结果与原曲不匹配,已拒绝(避免货不对版)`);
const firstResult = searchResponse.data[0];
if (!firstResult || !firstResult.id) {
console.log(`GD音乐台 ${source} 搜索结果无效`);
return null;
}
const trackId = matchedResult.id;
const trackSource = matchedResult.source || source;
const trackId = firstResult.id;
const trackSource = firstResult.source || source;
// 2. 获取歌曲URL
const songUrl = `${baseUrl}?types=url&source=${trackSource}&id=${trackId}&br=${quality}`;
+49 -53
View File
@@ -16,72 +16,68 @@ import { CacheManager } from './musicParser';
/**
* API URL URL
* API URL
*
* CORS null
* URL
* URL audio Format error
* unblockMusic
*/
const resolveAudioUrl = async (url: string): Promise<string | null> => {
// 检查是否看起来像 API 端点(包含 /api/ 且有查询参数)
const isApiEndpoint = url.includes('/api/') || (url.includes('?') && url.includes('type=url'));
if (!isApiEndpoint) {
// 看起来像直接的音频 URL,直接返回
return url;
}
console.log('[LxMusicStrategy] 检测到 API 端点,尝试解析真实 URL:', url);
// 非 Electron 环境无法绕过 CORS 验证,保持乐观返回
if (typeof window.api?.lxMusicHttpRequest !== 'function') {
return url;
}
const resolveAudioUrl = async (url: string): Promise<string> => {
try {
const requestId = `lx_resolve_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
const response = await window.api.lxMusicHttpRequest({
url,
options: {
method: 'GET',
// 端点若直接返回音频流,用 Range 避免整段下载;返回 JSON 时 8KB 也足够
headers: { Range: 'bytes=0-8191' },
timeout: 15000
},
requestId
});
// 检查是否看起来像 API 端点(包含 /api/ 且有查询参数)
const isApiEndpoint = url.includes('/api/') || (url.includes('?') && url.includes('type=url'));
const status = response?.statusCode ?? 0;
const contentType = String(response?.headers?.['content-type'] || '');
if (status < 200 || status >= 400) {
console.warn(`[LxMusicStrategy] API 端点返回 ${status},判定解析失败`);
return null;
}
// 端点直接返回音频流(或重定向到音频,主进程已自动跟随),
// audio 元素可以直接播放原始 URL
if (contentType.includes('audio/') || contentType.includes('application/octet-stream')) {
console.log('[LxMusicStrategy] API 端点为音频流,直接使用原始 URL');
if (!isApiEndpoint) {
// 看起来像直接的音频 URL,直接返回
return url;
}
// JSON 响应:尝试提取常见字段中的音频 URL
const body = response?.body;
if (body && typeof body === 'object') {
const audioUrl = body.url || body.data?.url || body.audio_url || body.link || body.src;
console.log('[LxMusicStrategy] 检测到 API 端点,尝试解析真实 URL:', url);
// 尝试获取真实 URL
const response = await fetch(url, {
method: 'HEAD',
redirect: 'manual' // 不自动跟随重定向
});
// 检查是否是重定向
if (response.status >= 300 && response.status < 400) {
const location = response.headers.get('Location');
if (location) {
console.log('[LxMusicStrategy] API 返回重定向 URL:', location);
return location;
}
}
// 如果 HEAD 请求没有重定向,尝试 GET 请求
const getResponse = await fetch(url, {
redirect: 'follow'
});
// 检查 Content-Type
const contentType = getResponse.headers.get('Content-Type') || '';
// 如果是音频类型,返回最终 URL
if (contentType.includes('audio/') || contentType.includes('application/octet-stream')) {
console.log('[LxMusicStrategy] 解析到音频 URL:', getResponse.url);
return getResponse.url;
}
// 如果是 JSON,尝试解析
if (contentType.includes('application/json') || contentType.includes('text/json')) {
const json = await getResponse.json();
console.log('[LxMusicStrategy] API 返回 JSON:', json);
// 尝试从 JSON 中提取 URL(常见字段)
const audioUrl = json.url || json.data?.url || json.audio_url || json.link || json.src;
if (audioUrl && typeof audioUrl === 'string') {
console.log('[LxMusicStrategy] 从 JSON 中提取音频 URL:', audioUrl);
return audioUrl;
}
}
// 2xx 但既不是音频也提取不到 URL(如 HTML 错误页),视为不可播放
console.warn('[LxMusicStrategy] API 端点响应无法解析为音频,判定解析失败');
return null;
// 如果都不是,返回原始 URL(可能直接可用)
console.warn('[LxMusicStrategy] 无法解析 API 端点,返回原始 URL');
return url;
} catch (error) {
console.error('[LxMusicStrategy] URL 解析请求失败:', error);
return null;
console.error('[LxMusicStrategy] URL 解析失败:', error);
// 解析失败时返回原始 URL
return url;
}
};
+50 -42
View File
@@ -5,6 +5,7 @@ import { SongSourceConfigManager } from '@/services/SongSourceConfigManager';
import { useSettingsStore } from '@/store';
import type { SongResult } from '@/types/music';
import { isElectron } from '@/utils';
import requestMusic from '@/utils/request_music';
import type { ParsedMusicResult } from './gdmusic';
import { parseFromGDMusic } from './gdmusic';
@@ -160,11 +161,21 @@ export class CacheManager {
// 清除URL缓存
await deleteData('music_url_cache', id);
console.log(`清除歌曲 ${id} 的URL缓存`);
// 清除失败缓存 - 需要遍历所有策略
const strategies = ['custom', 'gdmusic', 'unblockMusic'];
for (const strategy of strategies) {
const cacheKey = `${id}_${strategy}`;
try {
await deleteData('music_failed_cache', cacheKey);
} catch {
// 忽略删除不存在缓存的错误
}
}
console.log(`清除歌曲 ${id} 的失败缓存`);
} catch (error) {
console.error('清除URL缓存失败:', error);
console.error('清除缓存失败:', error);
}
// 清除内存失败缓存(覆盖所有策略,含 lxMusic)
CacheManager.clearFailedCache(id);
}
}
@@ -227,19 +238,7 @@ const getGDMusicAudio = async (id: number, data: SongResult): Promise<ParsedMusi
const getUnblockMusicAudio = (id: number, data: SongResult, sources: any[]) => {
const filteredSources = sources.filter((source) => source !== 'gdmusic');
console.log(`使用unblockMusic解析,音源:`, filteredSources);
// 整体超时兜底:unblock 全链路(IPC → match())本身无超时,底层请求挂起时会
// 导致渲染进程无限等待、起播/切歌长时间无响应。超时解析为 null 以走降级,
// 且不抛异常(避免触发 RetryHelper 的多次重试放大等待时间)。
const UNBLOCK_TIMEOUT = 15000;
return Promise.race([
window.api.unblockMusic(id, cloneDeep(data), cloneDeep(filteredSources)),
new Promise((resolve) => {
setTimeout(() => {
console.warn(`unblockMusic 解析超时(${UNBLOCK_TIMEOUT}ms),放弃等待`);
resolve(null);
}, UNBLOCK_TIMEOUT);
})
]);
return window.api.unblockMusic(id, cloneDeep(data), cloneDeep(filteredSources));
};
/**
@@ -487,18 +486,6 @@ const getMusicConfig = (id: number, settingsStore?: any) => {
return { musicSources, quality };
};
/**
*
* music_proxy 退
*/
const buildFailedResult = (message: string, code = 404): MusicParseResult => ({
data: {
code,
message,
data: undefined
}
});
/**
*
*/
@@ -513,10 +500,10 @@ export class MusicParser {
const startTime = performance.now();
try {
// 非Electron环境不支持本地解析
// 非Electron环境直接使用API请求
if (!isElectron) {
console.log('非Electron环境,不支持音乐解析');
return buildFailedResult('当前环境不支持音乐解析');
console.log('非Electron环境,使用API请求');
return await requestMusic.get<any>('/music', { params: { id } });
}
// 获取设置存储
@@ -524,8 +511,8 @@ export class MusicParser {
try {
settingsStore = useSettingsStore();
} catch (error) {
console.error('无法获取设置存储:', error);
return buildFailedResult('无法读取设置,音乐解析不可用');
console.error('无法获取设置存储,使用后备方案:', error);
return await requestMusic.get<any>('/music', { params: { id } });
}
// 获取音源配置
@@ -554,8 +541,8 @@ export class MusicParser {
}
if (musicSources.length === 0) {
console.warn('没有配置可用的音源');
return buildFailedResult('没有配置可用的音源');
console.warn('没有配置可用的音源,使用后备方案');
return await requestMusic.get<any>('/music', { params: { id } });
}
// 获取可用的解析策略
@@ -565,8 +552,8 @@ export class MusicParser {
);
if (availableStrategies.length === 0) {
console.warn('没有可用的解析策略');
return buildFailedResult('没有可用的解析策略');
console.warn('没有可用的解析策略,使用后备方案');
return await requestMusic.get<any>('/music', { params: { id } });
}
console.log(
@@ -596,13 +583,34 @@ export class MusicParser {
}
}
console.warn('所有解析策略都失败了');
console.warn('所有解析策略都失败了,使用后备方案');
} catch (error) {
console.error('MusicParser.parseMusic 执行异常:', error);
console.error('MusicParser.parseMusic 执行异常,使用后备方案:', error);
}
const endTime = performance.now();
console.log(`总耗时: ${(endTime - startTime).toFixed(2)}ms`);
return buildFailedResult('所有解析方式都失败了', 500);
// 后备方案:使用API请求
try {
console.log('使用后备方案:API请求');
const result = await requestMusic.get<any>('/music', { params: { id } });
// 如果后备方案成功,也进行缓存
if (result?.data?.data?.url) {
console.log('后备方案成功,缓存结果');
await CacheManager.setCachedMusicUrl(id, result, []);
}
return result;
} catch (apiError) {
console.error('API请求也失败了:', apiError);
const endTime = performance.now();
console.log(`总耗时: ${(endTime - startTime).toFixed(2)}ms`);
return {
data: {
code: 500,
message: '所有解析方式都失败了',
data: undefined
}
};
}
}
}
+2 -13
View File
@@ -72,9 +72,7 @@ export const parseFromCustomApi = async (
response = await axios.post(plugin.apiUrl, finalParams, { timeout });
} else {
// 默认为 GET
// apiUrl 本身可能已带查询串(如 xxx/api.php?type=url),需按情况选择 ? 或 &
const separator = plugin.apiUrl.includes('?') ? '&' : '?';
const finalUrl = `${plugin.apiUrl}${separator}${new URLSearchParams(finalParams).toString()}`;
const finalUrl = `${plugin.apiUrl}?${new URLSearchParams(finalParams).toString()}`;
console.log('自定义API:发送 GET 请求到:', finalUrl);
response = await axios.get(finalUrl, { timeout });
}
@@ -85,20 +83,11 @@ export const parseFromCustomApi = async (
if (musicUrl && typeof musicUrl === 'string') {
console.log('自定义API:成功获取URL');
// 5. 组装成应用所需的标准格式并返回
// quality 是 'standard'/'higher'/'exhigh'/'lossless'/'hires' 等字符串,
// 直接 parseInt 会得到 NaN,这里映射为对应码率(bps)
const QUALITY_BITRATE: Record<string, number> = {
standard: 128000,
higher: 192000,
exhigh: 320000,
lossless: 999000,
hires: 1900000
};
return {
data: {
data: {
url: musicUrl,
br: QUALITY_BITRATE[quality] ?? 320000,
br: parseInt(quality) * 1000,
size: 0,
md5: '',
platform: plugin.name.toLowerCase().replace(/\s/g, ''),
@@ -235,8 +235,6 @@ const handleAddToPlaylist = async (playlist: any) => {
if (res.status === 200) {
message.success(t('comp.playlistDrawer.addSuccess'));
emit('update:modelValue', false);
// /(trackCount)#508
store.initializePlaylist().catch(() => {});
} else {
throw new Error(res.data?.msg || t('comp.playlistDrawer.addFailed'));
}
@@ -4,9 +4,7 @@
<div class="w-full pb-32">
<!-- Page Header (scrolls away) -->
<div ref="headerRef" class="page-padding pt-6 pb-2">
<h1
class="mb-2 text-2xl font-bold tracking-tight text-neutral-900 md:text-3xl dark:text-white"
>
<h1 class="mb-2 text-2xl font-bold tracking-tight text-neutral-900 md:text-3xl dark:text-white">
{{ title }}
</h1>
<p v-if="description" class="text-neutral-500 dark:text-neutral-400">
@@ -4,7 +4,7 @@
@contextmenu.prevent="handleContextMenu"
@mouseenter="handleMouseEnter"
@mouseleave="handleMouseLeave"
@dblclick.stop="handlePlay(item)"
@dblclick.stop="playMusicEvent(item)"
>
<slot name="index"></slot>
<slot name="select" v-if="selectable"></slot>
@@ -22,7 +22,7 @@
:is-dislike="isDislike"
:can-remove="canRemove"
@update:show="showDropdown = $event"
@play="handlePlay(item)"
@play="playMusicEvent(item)"
@play-next="handlePlayNext"
@download="downloadMusic(item)"
@download-lyric="downloadLyric(item)"
@@ -83,12 +83,6 @@ const imageLoad = async (event: Event) => {
await handleImageLoad(target);
};
// ""
const handlePlay = (song: SongResult) => {
emits('play', song);
playMusicEvent(song);
};
//
const toggleSelect = () => {
emits('select', props.item.id, !props.selected);
@@ -41,11 +41,6 @@
:class="{ 'text-green-500': isPlaying }"
>
{{ item.name }}
<span
v-if="item.tns?.length || item.alia?.length"
class="text-neutral-400 dark:text-neutral-500"
>{{ item.tns?.[0] || item.alia?.[0] }}</span
>
</n-ellipsis>
</div>
<div class="song-item-content-compact-artist">
@@ -33,11 +33,6 @@
:class="{ 'text-green-500': isPlaying }"
>
{{ item.name }}
<span
v-if="item.tns?.length || item.alia?.length"
class="text-neutral-400 dark:text-neutral-500 font-normal"
>{{ item.tns?.[0] || item.alia?.[0] }}</span
>
</n-ellipsis>
<n-ellipsis
class="artist-name text-xs md:text-sm text-neutral-500 dark:text-neutral-400 mt-0.5"
@@ -43,11 +43,6 @@
:class="{ 'text-green-500': isPlaying }"
>
{{ item.name }}
<span
v-if="item.tns?.length || item.alia?.length"
class="text-neutral-400 dark:text-neutral-500"
>{{ item.tns?.[0] || item.alia?.[0] }}</span
>
</n-ellipsis>
<div class="song-item-content-divider">-</div>
<n-ellipsis class="song-item-content-name text-ellipsis" line-clamp="1">
@@ -39,11 +39,6 @@
<div class="song-item-content-title">
<n-ellipsis class="text-ellipsis" line-clamp="1" :class="{ 'text-green-500': isPlaying }">
{{ item.name }}
<span
v-if="item.tns?.length || item.alia?.length"
class="text-neutral-400 dark:text-neutral-500"
>{{ item.tns?.[0] || item.alia?.[0] }}</span
>
</n-ellipsis>
</div>
<div class="song-item-content-name">
@@ -15,15 +15,13 @@
<script lang="ts" setup>
import type { MenuOption } from 'naive-ui';
import { createDiscreteApi, NDropdown, NEllipsis, NImage } from 'naive-ui';
import { NDropdown, NEllipsis, NImage } from 'naive-ui';
import { computed, h, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { useUserStore } from '@/store';
import type { SongResult } from '@/types/music';
import { getImgUrl, isElectron } from '@/utils';
const { message } = createDiscreteApi(['message']);
import { hasPermission } from '@/utils/auth';
const { t } = useI18n();
@@ -52,19 +50,6 @@ const emits = defineEmits([
const openPlaylistDrawer = inject<(songId: number | string) => void>('openPlaylistDrawer');
const userStore = useUserStore();
// Cookie/
// userStore localStorage
// /#706
const hasRealAuth = computed(() => !!userStore.user && userStore.loginType !== 'uid');
// """"#713
const isLocalSong = computed(
() =>
typeof props.item.playMusicUrl === 'string' && props.item.playMusicUrl.startsWith('local://')
);
//
const renderSongPreview = () => {
return h(
@@ -138,6 +123,8 @@ const renderSongPreview = () => {
//
const dropdownOptions = computed<MenuOption[]>(() => {
const hasRealAuth = hasPermission(true);
const options: MenuOption[] = [
{
key: 'header',
@@ -173,10 +160,10 @@ const dropdownOptions = computed<MenuOption[]>(() => {
icon: () => h('i', { class: 'iconfont ri-file-text-line' })
},
{
// ""#706
label: t('songItem.menu.addToPlaylist'),
key: 'addToPlaylist',
icon: () => h('i', { class: 'iconfont ri-folder-add-line' })
icon: () => h('i', { class: 'iconfont ri-folder-add-line' }),
disabled: !hasRealAuth
},
{
label: props.isFavorite ? t('songItem.menu.unfavorite') : t('songItem.menu.favorite'),
@@ -204,9 +191,7 @@ const dropdownOptions = computed<MenuOption[]>(() => {
key: 'd2'
},
{
label: isLocalSong.value
? t('localMusic.removeFromLibrary')
: t('songItem.menu.removeFromPlaylist'),
label: t('songItem.menu.removeFromPlaylist'),
key: 'remove',
icon: () => h('i', { class: 'iconfont ri-delete-bin-line' })
}
@@ -231,10 +216,6 @@ const handleSelect = (key: string | number) => {
emits('play-next');
break;
case 'addToPlaylist':
if (!hasRealAuth.value) {
message.warning(t('songItem.message.addToPlaylistNeedLogin'));
break;
}
openPlaylistDrawer?.(props.item.id);
break;
case 'favorite':
@@ -37,13 +37,11 @@
<template #content>
<div class="song-item-content">
<div class="song-item-content-title">
<n-ellipsis class="text-ellipsis" line-clamp="1" :class="{ 'text-green-500': isPlaying }"
>{{ item.name }}
<span
v-if="item.tns?.length || item.alia?.length"
class="text-neutral-400 dark:text-neutral-500"
>{{ item.tns?.[0] || item.alia?.[0] }}</span
></n-ellipsis
<n-ellipsis
class="text-ellipsis"
line-clamp="1"
:class="{ 'text-green-500': isPlaying }"
>{{ item.name }}</n-ellipsis
>
</div>
<div class="song-item-content-name">
@@ -48,8 +48,7 @@ const { t } = useI18n();
<style scoped lang="scss">
.lyric-correction {
/* bottom 需越过全屏态下钉底的 PlayBarh-20=80px, z-index:9999),否则被遮挡无法点击(#592) */
@apply absolute right-0 bottom-24 flex flex-col items-center space-y-1 z-50 select-none transition-opacity duration-200 opacity-0 pointer-events-none;
@apply absolute right-0 bottom-4 flex flex-col items-center space-y-1 z-50 select-none transition-opacity duration-200 opacity-0 pointer-events-none;
}
.lyric-correction-btn {
+51 -4
View File
@@ -202,18 +202,19 @@ import {
useLyricProgress
} from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import { useLyricBackground } from '@/hooks/useLyricBackground';
import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { DEFAULT_LYRIC_CONFIG, LyricConfig } from '@/types/lyric';
import { getImgUrl, isMobile } from '@/utils';
import { getTextColors } from '@/utils/linearColor';
import { animateGradient, getHoverBackgroundColor, getTextColors } from '@/utils/linearColor';
const { t } = useI18n();
// refs
const lrcSider = ref<any>(null);
const isMouse = ref(false);
const { currentBackground, applyBackground } = useLyricBackground();
const currentBackground = ref('');
const animationFrame = ref<number | null>(null);
const isDark = ref(false);
//
const customBackgroundStyle = computed(() => {
@@ -380,6 +381,42 @@ 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;
}
};
const targetBackground = computed(() => {
if (config.value.useCustomBackground && customBackgroundStyle.value) {
if (typeof customBackgroundStyle.value === 'string') {
@@ -397,7 +434,7 @@ watch(
targetBackground,
(newBg) => {
if (newBg) {
applyBackground(newBg);
setTextColors(newBg);
}
},
{ immediate: true }
@@ -486,6 +523,13 @@ const getWordStyle = (lineIndex: number, _wordIndex: number, word: any) => {
}
};
//
onBeforeUnmount(() => {
if (animationFrame.value) {
cancelAnimationFrame(animationFrame.value);
}
});
const settingsStore = useSettingsStore();
const { navigateToArtist } = useArtist();
@@ -582,6 +626,9 @@ onMounted(() => {
//
onBeforeUnmount(() => {
if (animationFrame.value) {
cancelAnimationFrame(animationFrame.value);
}
if (lrcSider.value?.$el) {
lrcSider.value.$el.removeEventListener('scroll', handleScroll);
}
@@ -408,13 +408,12 @@ import {
useLyricProgress
} from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import { useLyricBackground } from '@/hooks/useLyricBackground';
import { usePlayMode } from '@/hooks/usePlayMode';
import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player';
import { DEFAULT_LYRIC_CONFIG, LyricConfig } from '@/types/lyric';
import { getImgUrl, secondToMinute } from '@/utils';
import { getTextColors } from '@/utils/linearColor';
import { animateGradient, getHoverBackgroundColor, getTextColors } from '@/utils/linearColor';
import { showBottomToast } from '@/utils/shortcutToast';
const { t } = useI18n();
@@ -877,10 +876,10 @@ const handleThumbTouchEnd = (e: TouchEvent) => {
isThumbDragging.value = false;
};
// composable
const { isDark, applyBackground } = useLyricBackground({
writeBgColor: () => playerStore.playMusic.primaryColor || undefined
});
//
const currentBackground = ref('');
const animationFrame = ref<number | null>(null);
const isDark = ref(false);
const config = ref<LyricConfig>({ ...DEFAULT_LYRIC_CONFIG });
//
@@ -938,6 +937,49 @@ const isVisible = computed({
set: (value) => emit('update:modelValue', value)
});
//
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);
document.documentElement.style.setProperty('--bg-color', 'rgba(25, 25, 25, 1)');
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);
//
let bgColor = playerStore.playMusic.primaryColor || 'rgba(25, 25, 25, 1)';
document.documentElement.style.setProperty('--bg-color', bgColor);
//
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;
}
};
const targetBackground = computed(() => {
if (config.value.theme !== 'default') {
return themeMusic[config.value.theme] || props.background;
@@ -950,24 +992,21 @@ watch(
targetBackground,
(newBg) => {
if (newBg) {
applyBackground(newBg);
setTextColors(newBg);
}
},
{ immediate: true }
);
//
//
onBeforeUnmount(() => {
if (animationFrame.value) {
cancelAnimationFrame(animationFrame.value);
}
if (autoScrollTimer.value) {
clearTimeout(autoScrollTimer.value);
}
// interval store
if (sleepTimerInterval) {
clearInterval(sleepTimerInterval);
sleepTimerInterval = null;
}
//
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
@@ -1074,7 +1113,7 @@ watch(isVisible, (newVal) => {
if (newVal) {
//
if (targetBackground.value) {
applyBackground(targetBackground.value);
setTextColors(targetBackground.value);
}
} else {
showFullLyrics.value = false;
@@ -1090,7 +1129,7 @@ const { getLrcStyle: originalLrcStyle } = useLyricProgress();
// getLrcStyle
const getLrcStyle = (index: number) => {
const colors = textColors.value || getTextColors();
const colors = textColors.value || getTextColors;
const originalStyle = originalLrcStyle(index);
if (index === nowIndex.value) {
@@ -7,14 +7,8 @@
>
<div class="panel-header">
<span class="panel-title">{{ t('settings.themeColor.title') }}</span>
<div class="header-actions">
<div class="reset-button" :title="t('settings.themeColor.reset')" @click="handleReset">
<i class="ri-arrow-go-back-line"></i>
<span>{{ t('settings.themeColor.reset') }}</span>
</div>
<div class="close-button" @click="handleClose">
<i class="ri-close-line"></i>
</div>
<div class="close-button" @click="handleClose">
<i class="ri-close-line"></i>
</div>
</div>
@@ -117,7 +111,6 @@ interface Props {
interface Emits {
(e: 'colorChange', _color: string): void;
(e: 'close'): void;
(e: 'reset'): void;
}
const props = withDefaults(defineProps<Props>(), {
@@ -167,12 +160,6 @@ const handleClose = () => {
emit('close');
};
// #591
const handleReset = () => {
showColorPicker.value = false;
emit('reset');
};
const handlePresetColorSelect = (color: LyricThemeColor) => {
const colorValue = getColorValue(color);
const optimizedColor = optimizeColorForTheme(colorValue, props.theme);
@@ -314,35 +301,6 @@ watch(
opacity: 0.9;
}
.header-actions {
display: flex;
align-items: center;
gap: 6px;
}
.reset-button {
display: flex;
align-items: center;
gap: 4px;
height: 24px;
padding: 0 8px;
cursor: pointer;
border-radius: 6px;
color: var(--text-color);
font-size: 11px;
opacity: 0.8;
transition: all 0.2s ease;
&:hover {
background: rgba(255, 255, 255, 0.15);
opacity: 1;
}
i {
font-size: 12px;
}
}
.close-button {
width: 24px;
height: 24px;
+3 -12
View File
@@ -69,7 +69,6 @@
v-model:value="volumeSlider"
:step="0.01"
:tooltip="false"
:disabled="isMuted"
vertical
@wheel.prevent="handleVolumeWheel"
></n-slider>
@@ -146,13 +145,7 @@ const { navigateToArtist } = useArtist();
const { isPlaying: play, playMusicEvent, handleNext, handlePrev } = usePlaybackControl();
// playerStore
const {
isMuted,
volumeSlider,
volumeIcon: getVolumeIcon,
mute,
handleVolumeWheel
} = useVolumeControl();
const { volumeSlider, volumeIcon: getVolumeIcon, mute, handleVolumeWheel } = useVolumeControl();
//
const { isFavorite, toggleFavorite } = useFavorite();
@@ -182,11 +175,9 @@ const palyListRef = useTemplateRef('palyListRef') as any;
const isPlaylistOpen = ref(false);
// openPlaylistDrawer
// Mini 340px 420px
// AppLayout #504
provide('openPlaylistDrawer', (songId: number) => {
localStorage.setItem('pendingAddToPlaylistSongId', String(songId));
window.api.restore();
console.log('打开歌单抽屉', songId);
//
});
// /
+3 -39
View File
@@ -99,16 +99,8 @@
<i class="iconfont" :class="getVolumeIcon"></i>
</div>
<div class="volume-slider">
<div class="volume-percentage" :class="{ 'volume-percentage-disabled': isMuted }">
{{ Math.round(volumeSlider) }}%
</div>
<n-slider
v-model:value="volumeSlider"
:step="0.01"
:tooltip="false"
:disabled="isMuted"
vertical
></n-slider>
<div class="volume-percentage">{{ Math.round(volumeSlider) }}%</div>
<n-slider v-model:value="volumeSlider" :step="0.01" :tooltip="false" vertical></n-slider>
</div>
</div>
<n-tooltip v-if="!isMobile" trigger="hover" :z-index="9999999">
@@ -151,16 +143,6 @@
</template>
{{ t('player.playBar.reparse') }}
</n-tooltip>
<n-tooltip v-if="playMusic?.id && isElectron" trigger="hover" :z-index="9999999">
<template #trigger>
<i
class="iconfont ri-download-line"
:class="{ 'disabled-icon': isDownloading }"
@click="playMusic?.id && handleDownload()"
/>
</template>
{{ isDownloading ? t('songItem.message.downloading') : t('player.playBar.download') }}
</n-tooltip>
<!-- 高级控制菜单按钮整合了 EQ定时关闭播放速度 -->
<advanced-controls-popover />
@@ -199,7 +181,6 @@ import {
textColors
} from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import { useDownload } from '@/hooks/useDownload';
import { useFavorite } from '@/hooks/useFavorite';
import { usePlaybackControl } from '@/hooks/usePlaybackControl';
import { usePlayMode } from '@/hooks/usePlayMode';
@@ -217,24 +198,11 @@ const { t } = useI18n();
const { isPlaying: play, playMusicEvent, handleNext, handlePrev } = usePlaybackControl();
//
const {
isMuted,
volumeSlider,
volumeIcon: getVolumeIcon,
mute,
handleVolumeWheel
} = useVolumeControl();
const { volumeSlider, volumeIcon: getVolumeIcon, mute, handleVolumeWheel } = useVolumeControl();
//
const { isFavorite, toggleFavorite } = useFavorite();
//
const { downloadMusic, isDownloading } = useDownload();
const handleDownload = () => {
if (!playMusic.value || isDownloading.value) return;
downloadMusic(playMusic.value);
};
//
const { playMode, playModeIcon, playModeText, togglePlayMode } = usePlayMode();
@@ -414,10 +382,6 @@ const openPlayListDrawer = () => {
@apply border border-gray-200 dark:border-gray-700;
@apply text-gray-800 dark:text-white;
white-space: nowrap;
&.volume-percentage-disabled {
@apply text-gray-400 dark:text-gray-500;
}
}
}
}
@@ -68,7 +68,6 @@
v-model:value="volumeSlider"
:step="1"
:tooltip="false"
:disabled="isMuted"
@wheel.prevent="handleVolumeWheel"
></n-slider>
</div>
@@ -108,13 +107,7 @@ const { isPlaying: play, playMusicEvent, handleNext, handlePrev } = usePlaybackC
const { playMode, playModeIcon, togglePlayMode } = usePlayMode();
// playerStore
const {
isMuted,
volumeSlider,
volumeIcon: getVolumeIcon,
mute,
handleVolumeWheel
} = useVolumeControl();
const { volumeSlider, volumeIcon: getVolumeIcon, mute, handleVolumeWheel } = useVolumeControl();
//
const isDragging = ref(false);
@@ -23,7 +23,11 @@ const goToDetail = () => {
</script>
<template>
<div class="group cursor-pointer animate-item" :style="{ animationDelay }" @click="goToDetail">
<div
class="group cursor-pointer animate-item"
:style="{ animationDelay }"
@click="goToDetail"
>
<!-- Cover -->
<div
class="relative aspect-square overflow-hidden rounded-2xl shadow-md group-hover:shadow-xl transition-all duration-500"
+27 -34
View File
@@ -2,46 +2,39 @@ import { createVNode, render, VNode } from 'vue';
import Loading from './index.vue';
// 每个使用 v-loading 的元素独立持有一个 Loading 实例,
// 避免此前"模块级单例 vnode"导致的多个 v-loading 争用同一实例、
// spinner 只出现在最后挂载元素上的问题。
const instanceMap = new WeakMap<HTMLElement, VNode>();
const vnode: VNode = createVNode(Loading) as VNode;
const setLoading = (el: HTMLElement, visible: boolean) => {
const vnode = instanceMap.get(el);
if (visible) {
vnode?.component?.exposed?.show();
} else {
export const vLoading = {
// 在绑定元素的父组件 及他自己的所有子节点都挂载完成后调用
mounted: (el: HTMLElement) => {
render(vnode, el);
},
// 在绑定元素的父组件 及他自己的所有子节点都更新后调用
updated: (el: HTMLElement, binding: any) => {
if (binding.value) {
vnode?.component?.exposed?.show();
} else {
vnode?.component?.exposed?.hide();
}
// 动态添加删除自定义class: loading-parent
formatterClass(el, binding);
},
// 绑定元素的父组件卸载后调用
unmounted: () => {
vnode?.component?.exposed?.hide();
}
};
export const vLoading = {
// 在绑定元素的父组件及他自己的所有子节点都挂载完成后调用
mounted: (el: HTMLElement, binding: any) => {
const vnode = createVNode(Loading);
render(vnode, el);
instanceMap.set(el, vnode);
setLoading(el, !!binding.value);
formatterClass(el, binding);
},
// 在绑定元素的父组件及他自己的所有子节点都更新后调用
updated: (el: HTMLElement, binding: any) => {
setLoading(el, !!binding.value);
// 动态添加删除自定义class: loading-parent
formatterClass(el, binding);
},
// 绑定元素的父组件卸载后调用:真正卸载组件实例,释放资源
unmounted: (el: HTMLElement) => {
render(null, el);
instanceMap.delete(el);
}
};
function formatterClass(el: HTMLElement, binding: any) {
const classStr = el.getAttribute('class');
const tagetClass: number = classStr?.indexOf('loading-parent') as number;
if (binding.value) {
el.classList.add('loading-parent');
} else {
el.classList.remove('loading-parent');
if (tagetClass === -1) {
el.setAttribute('class', `${classStr} loading-parent`);
}
} else if (tagetClass > -1) {
const classArray: Array<string> = classStr?.split('') as string[];
classArray.splice(tagetClass - 1, tagetClass + 15);
el.setAttribute('class', classArray?.join(''));
}
}
+163 -190
View File
@@ -52,11 +52,6 @@ export const textColors = ref<any>(getTextColors());
export let playMusic: ComputedRef<SongResult>;
export let artistList: ComputedRef<Artist[]>;
let lastIndex = -1;
// 缓存平台信息,避免每次歌词变化时同步 IPC 调用
const cachedPlatform = isElectron ? window.electron.ipcRenderer.sendSync('get-platform') : 'web';
export const musicDB = await useIndexedDB(
'musicDB',
[
@@ -140,10 +135,7 @@ const parseLyricsString = async (
duration: line.duration
});
// yrcParser 的 startTime 是毫秒;lrcTimeArray 全链路(nowTime 对比、
// setAudioTime seek)以秒为单位,必须换算,否则点击歌词会 seek 到
// 远超时长的位置被钳到末尾、直接触发切歌
lrcTimeArray.push(line.startTime / 1000);
lrcTimeArray.push(line.startTime);
}
return { lrcArray, lrcTimeArray, hasWordByWord };
} catch (error) {
@@ -152,130 +144,124 @@ const parseLyricsString = async (
}
};
// 解析当前 playMusic.lyric 写入 lrcArray, 供 watcher / openLyric / onLyricWindowReady 共用
const ensureLyricsLoaded = async (force = false) => {
const songId = playMusic.value?.id;
if (!songId) {
lrcArray.value = [];
lrcTimeArray.value = [];
nowIndex.value = 0;
return;
}
if (!force && lrcArray.value.length > 0) return;
await nextTick();
const lyricData = playMusic.value.lyric;
if (lyricData && typeof lyricData === 'string') {
const {
lrcArray: parsedLrcArray,
lrcTimeArray: parsedTimeArray,
hasWordByWord
} = await parseLyricsString(lyricData);
lrcArray.value = parsedLrcArray;
lrcTimeArray.value = parsedTimeArray;
if (playMusic.value.lyric && typeof playMusic.value.lyric === 'object') {
playMusic.value.lyric.hasWordByWord = hasWordByWord;
}
} else if (lyricData && typeof lyricData === 'object' && lyricData.lrcArray?.length > 0) {
const rawLrc = lyricData.lrcArray || [];
lrcTimeArray.value = lyricData.lrcTimeArray || [];
try {
const { translateLyrics } = await import('@/services/lyricTranslation');
lrcArray.value = await translateLyrics(rawLrc as any);
} catch (e) {
console.error('翻译歌词失败,使用原始歌词:', e);
lrcArray.value = rawLrc as any;
}
} else if (isElectron && playMusic.value.playMusicUrl?.startsWith('local:///')) {
try {
let filePath = decodeURIComponent(playMusic.value.playMusicUrl.replace('local:///', ''));
// 处理 Windows 路径:/C:/... → C:/...
if (/^\/[a-zA-Z]:\//.test(filePath)) {
filePath = filePath.slice(1);
}
const embeddedLyrics = await window.api.getEmbeddedLyrics(filePath);
if (embeddedLyrics) {
const {
lrcArray: parsedLrcArray,
lrcTimeArray: parsedTimeArray,
hasWordByWord
} = await parseLyricsString(embeddedLyrics);
lrcArray.value = parsedLrcArray;
lrcTimeArray.value = parsedTimeArray;
if (playMusic.value.lyric && typeof playMusic.value.lyric === 'object') {
(playMusic.value.lyric as any).hasWordByWord = hasWordByWord;
}
} else if (typeof songId === 'number') {
try {
const { getMusicLrc } = await import('@/api/music');
const res = await getMusicLrc(songId);
if (res?.data?.lrc?.lyric) {
const { lrcArray: apiLrcArray, lrcTimeArray: apiTimeArray } = await parseLyricsString(
res.data.lrc.lyric
);
lrcArray.value = apiLrcArray;
lrcTimeArray.value = apiTimeArray;
}
} catch (apiErr) {
console.error('API lyrics fallback failed:', apiErr);
}
}
} catch (err) {
console.error('Failed to extract embedded lyrics:', err);
}
} else if (typeof songId === 'number') {
// 在线歌曲但 lyric 字段尚未加载, 主动调 API 兜底
try {
const { getMusicLrc } = await import('@/api/music');
const res = await getMusicLrc(songId);
if (res?.data?.lrc?.lyric) {
const { lrcArray: apiLrcArray, lrcTimeArray: apiTimeArray } = await parseLyricsString(
res.data.lrc.lyric
);
lrcArray.value = apiLrcArray;
lrcTimeArray.value = apiTimeArray;
}
} catch (apiErr) {
console.error('API lyrics fallback failed:', apiErr);
}
}
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
setTimeout(() => sendLyricToWin(), 500);
}
};
// 设置音乐相关的监听器
const setupMusicWatchers = () => {
const store = getPlayerStore();
// 切歌时 id 变化, 强制重新解析
// 监听 playerStore.playMusic 的变化以更新歌词数据
watch(
() => store.playMusic.id,
async (newId, oldId) => {
if (newId !== oldId) nowIndex.value = 0;
await ensureLyricsLoaded(true);
// 如果没有歌曲ID,清空歌词
if (!newId) {
lrcArray.value = [];
lrcTimeArray.value = [];
nowIndex.value = 0;
return;
}
// 避免相同ID的重复执行(但允许初始化时执行)
if (newId === oldId && lrcArray.value.length > 0) return;
// 歌曲切换时重置歌词索引
if (newId !== oldId) {
nowIndex.value = 0;
}
await nextTick(async () => {
console.log('歌曲切换,更新歌词数据');
// 检查是否有原始歌词字符串需要解析
const lyricData = playMusic.value.lyric;
if (lyricData && typeof lyricData === 'string') {
// 如果歌词是字符串格式,使用新的解析器
const {
lrcArray: parsedLrcArray,
lrcTimeArray: parsedTimeArray,
hasWordByWord
} = await parseLyricsString(lyricData);
lrcArray.value = parsedLrcArray;
lrcTimeArray.value = parsedTimeArray;
// 更新歌曲的歌词数据结构
if (playMusic.value.lyric && typeof playMusic.value.lyric === 'object') {
playMusic.value.lyric.hasWordByWord = hasWordByWord;
}
} else if (lyricData && typeof lyricData === 'object' && lyricData.lrcArray?.length > 0) {
// 使用现有的歌词数据结构
const rawLrc = lyricData.lrcArray || [];
lrcTimeArray.value = lyricData.lrcTimeArray || [];
try {
const { translateLyrics } = await import('@/services/lyricTranslation');
lrcArray.value = await translateLyrics(rawLrc as any);
} catch (e) {
console.error('翻译歌词失败,使用原始歌词:', e);
lrcArray.value = rawLrc as any;
}
} else if (isElectron && playMusic.value.playMusicUrl?.startsWith('local:///')) {
// 从下载/本地文件的 ID3/FLAC 元数据中提取嵌入歌词
try {
let filePath = decodeURIComponent(
playMusic.value.playMusicUrl.replace('local:///', '')
);
// 处理 Windows 路径:/C:/... → C:/...
if (/^\/[a-zA-Z]:\//.test(filePath)) {
filePath = filePath.slice(1);
}
const embeddedLyrics = await window.api.getEmbeddedLyrics(filePath);
if (embeddedLyrics) {
const {
lrcArray: parsedLrcArray,
lrcTimeArray: parsedTimeArray,
hasWordByWord
} = await parseLyricsString(embeddedLyrics);
lrcArray.value = parsedLrcArray;
lrcTimeArray.value = parsedTimeArray;
if (playMusic.value.lyric && typeof playMusic.value.lyric === 'object') {
(playMusic.value.lyric as any).hasWordByWord = hasWordByWord;
}
} else {
// 无嵌入歌词 — 若有数字 ID,尝试 API 兜底
const songId = playMusic.value.id;
if (songId && typeof songId === 'number') {
try {
const { getMusicLrc } = await import('@/api/music');
const res = await getMusicLrc(songId);
if (res?.data?.lrc?.lyric) {
const { lrcArray: apiLrcArray, lrcTimeArray: apiTimeArray } =
await parseLyricsString(res.data.lrc.lyric);
lrcArray.value = apiLrcArray;
lrcTimeArray.value = apiTimeArray;
}
} catch (apiErr) {
console.error('API lyrics fallback failed:', apiErr);
}
}
}
} catch (err) {
console.error('Failed to extract embedded lyrics:', err);
}
} else {
// 无歌词数据
lrcArray.value = [];
lrcTimeArray.value = [];
}
// 当歌词数据更新时,如果歌词窗口打开,则发送数据
if (isElectron && isLyricWindowOpen.value) {
console.log('歌词窗口已打开,同步最新歌词数据');
// 不管歌词数组是否为空,都发送最新数据
sendLyricToWin();
// 再次延迟发送,确保歌词窗口已完全加载
setTimeout(() => {
sendLyricToWin();
}, 500);
}
});
},
{ immediate: true }
);
// 同一首歌但 lyric 字段后到 (播放后异步加载元数据 / 重启 + autoPlay 关闭场景)
watch(
() => playMusic.value?.lyric,
(newLyric) => {
if (!playMusic.value?.id) return;
// 完整歌词对象(含 yrc 逐字/翻译,时间单位为秒)后到时强制重新解析,
// 替换掉先行的 API 兜底纯 lrc 歌词
const isRichLyric =
!!newLyric && typeof newLyric === 'object' && (newLyric.lrcArray?.length ?? 0) > 0;
if (lrcArray.value.length === 0 || isRichLyric) {
ensureLyricsLoaded(isRichLyric);
}
}
);
};
const setupAudioListeners = () => {
@@ -343,12 +329,6 @@ const setupAudioListeners = () => {
sendLyricToWin();
}
}
if (isElectron && lrcArray.value[nowIndex.value]) {
if (lastIndex !== nowIndex.value) {
sendTrayLyric(nowIndex.value);
lastIndex = nowIndex.value;
}
}
// === 逐字歌词行内进度 ===
const { start, end } = currentLrcTiming.value;
@@ -392,15 +372,6 @@ const setupAudioListeners = () => {
);
}
}
// === MPRIS 进度更新(每 ~1 秒)===
if (isElectron && lyricThrottleCounter % 20 === 0) {
try {
window.electron.ipcRenderer.send('mpris-position-update', currentTime);
} catch {
// 忽略发送失败
}
}
} catch (error) {
console.error('进度更新 interval 出错:', error);
// 出错时不清除 interval,让下一次 tick 继续尝试
@@ -449,11 +420,6 @@ const setupAudioListeners = () => {
if (typeof currentTime === 'number' && !Number.isNaN(currentTime)) {
nowTime.value = currentTime;
// === MPRIS seek 时同步进度 ===
if (isElectron) {
window.electron.ipcRenderer.send('mpris-position-update', currentTime);
}
// 检查是否需要更新歌词
const newIndex = getLrcIndex(nowTime.value);
if (newIndex !== nowIndex.value) {
@@ -495,10 +461,7 @@ const setupAudioListeners = () => {
if (isElectron) {
window.api.sendSong(cloneDeep(getPlayerStore().playMusic));
}
// 兜底: 重启后首次点播放时 lrcArray 仍为空则主动加载
if (lrcArray.value.length === 0 && playMusic.value?.id) {
ensureLyricsLoaded();
}
// 启动进度更新
startProgressInterval();
});
@@ -543,12 +506,43 @@ const setupAudioListeners = () => {
if (getPlayerStore().playMode === 1) {
// 单曲循环模式
replayMusic();
return;
} else if (getPlayerStore().isFmPlaying) {
// 私人FM模式:自动获取下一首
try {
const { getPersonalFM } = await import('@/api/home');
const res = await getPersonalFM();
const songs = res.data?.data;
if (Array.isArray(songs) && songs.length > 0) {
const song = songs[0];
const fmSong = {
id: song.id,
name: song.name,
picUrl: song.al?.picUrl || song.album?.picUrl,
ar: song.artists || song.ar,
al: song.al || song.album,
source: 'netease' as const,
song,
...song,
playLoading: false
} as any;
const { usePlaylistStore } = await import('@/store/modules/playlist');
const playlistStore = usePlaylistStore();
playlistStore.setPlayList([fmSong], false, false);
getPlayerStore().isFmPlaying = true; // setPlayList 会清除,需重设
const { playTrack } = await import('@/services/playbackController');
await playTrack(fmSong, true);
} else {
getPlayerStore().setIsPlay(false);
}
} catch (error) {
console.error('FM自动播放下一首失败:', error);
getPlayerStore().setIsPlay(false);
}
} else {
// 顺序播放、列表循环、随机播放模式:歌曲自然结束
const { usePlaylistStore } = await import('@/store/modules/playlist');
usePlaylistStore().nextPlayOnEnd();
}
// 其他模式(FM/顺序/列表循环/随机):交给 playlist store 路由
const { usePlaylistStore } = await import('@/store/modules/playlist');
usePlaylistStore().nextPlayOnEnd();
});
audioService.on('previoustrack', () => {
@@ -813,30 +807,6 @@ export const sendLyricToWin = () => {
}
};
// 发送歌词到系统托盘歌词(TrayLyric)
const sendTrayLyric = (index: number) => {
if (!isElectron || cachedPlatform !== 'linux') return;
try {
const lyric = lrcArray.value[index];
if (!lyric) return;
const currentTime = lrcTimeArray.value[index] || 0;
const nextTime = lrcTimeArray.value[index + 1] || currentTime + 3;
const duration = nextTime - currentTime;
const lrcObj = JSON.stringify({
content: lyric.text || '',
time: duration.toFixed(1),
sender: 'AlgerMusicPlayer'
});
window.electron.ipcRenderer.send('tray-lyric-update', lrcObj);
} catch (error) {
console.error('[TrayLyric] Failed to send:', error);
}
};
// 歌词同步定时器
let lyricSyncInterval: any = null;
@@ -874,20 +844,28 @@ const stopLyricSync = () => {
}
};
export const openLyric = async () => {
// 修改openLyric函数,添加定时同步
export const openLyric = () => {
if (!isElectron) return;
// 检查是否有播放中的歌曲
if (!playMusic.value || !playMusic.value.id) {
console.log('没有正在播放的歌曲,无法打开歌词窗口');
return;
}
console.log('Opening lyric window with current song:', playMusic.value?.name);
isLyricWindowOpen.value = !isLyricWindowOpen.value;
if (isLyricWindowOpen.value) {
// 立即打开窗口
window.api.openLyric();
// 先发"加载中"占位, 防止窗口启动期间显示"无歌词"
// 确保有歌词数据,如果没有,则使用默认的"无歌词"提示
if (!lrcArray.value || lrcArray.value.length === 0) {
// 如果当前播放的歌曲有ID但没有歌词,则尝试加载歌词
console.log('尝试加载歌词数据...');
// 发送默认的"无歌词"数据
const emptyLyricData = {
type: 'empty',
nowIndex: 0,
@@ -901,15 +879,12 @@ export const openLyric = async () => {
playMusic: playMusic.value
};
window.api.sendLyric(JSON.stringify(emptyLyricData));
// 关键: 主动加载歌词, 不依赖 watcher
// (重启场景下 playerCore.playMusic 整体替换可能未触发 lyric watcher)
await ensureLyricsLoaded(true);
} else {
// 发送完整歌词数据
sendLyricToWin();
}
// 延迟重发, 防窗口加载慢丢消息
// 延迟重发一次,以防窗口加载
setTimeout(() => {
if (isLyricWindowOpen.value) {
sendLyricToWin();
@@ -1031,13 +1006,11 @@ export const initAudioListeners = async () => {
window.api.onLyricWindowClosed(() => {
isLyricWindowOpen.value = false;
});
window.api.onLyricWindowReady(async () => {
if (!isLyricWindowOpen.value) return;
// 窗口加载完成时再兜底加载一次, 防止 openLyric 阶段 lyric 字段尚未到位
if (lrcArray.value.length === 0 && playMusic.value?.id) {
await ensureLyricsLoaded(true);
// 歌词窗口 Vue 加载完成后,发送完整歌词数据
window.api.onLyricWindowReady(() => {
if (isLyricWindowOpen.value) {
sendLyricToWin();
}
sendLyricToWin();
});
}
+4 -12
View File
@@ -147,18 +147,10 @@ export const useDownload = () => {
lrcContent = mergeLrcWithTranslation(lyricData.lrc.lyric, lyricData.tlyric.lyric);
}
// 与歌曲下载一致:使用设置中的文件名格式模板拼接歌词文件名(#655)
const nameFormat =
(ipcRenderer?.sendSync('get-store-value', 'set.downloadNameFormat') as string) ||
'{songName} - {artistName}';
const artistNames =
(song.ar || song.song?.artists)?.map((a: { name: string }) => a.name).join('、') ||
'未知艺术家';
const albumName = song.al?.name || '未知专辑';
const filename = nameFormat
.replace(/\{songName\}/g, song.name || '')
.replace(/\{artistName\}/g, artistNames)
.replace(/\{albumName\}/g, albumName);
const artistNames = (song.ar || song.song?.artists)
?.map((a: { name: string }) => a.name)
.join(',');
const filename = `${song.name} - ${artistNames}`;
const result = await ipcRenderer?.invoke('save-lyric-file', { filename, lrcContent });
-76
View File
@@ -1,76 +0,0 @@
import { onBeforeUnmount, ref } from 'vue';
import { textColors } from '@/hooks/MusicHook';
import { animateGradient, getHoverBackgroundColor, getTextColors } from '@/utils/linearColor';
type UseLyricBackgroundOptions = {
/**
* --bg-color CSS
* - --bg-color
* - undefined DEFAULT_BG_COLOR
* DEFAULT_BG_COLOR
*/
writeBgColor?: () => string | undefined;
};
const DEFAULT_BG_COLOR = 'rgba(25, 25, 25, 1)';
export function useLyricBackground(options: UseLyricBackgroundOptions = {}) {
const currentBackground = ref('');
const animationFrame = ref<number | null>(null);
const isDark = ref(false);
const { writeBgColor } = options;
const root = document.documentElement;
const applyBackground = (background: string) => {
if (!background) {
textColors.value = getTextColors();
root.style.setProperty('--hover-bg-color', getHoverBackgroundColor(false));
root.style.setProperty('--text-color-primary', textColors.value.primary);
root.style.setProperty('--text-color-active', textColors.value.active);
if (writeBgColor) {
root.style.setProperty('--bg-color', DEFAULT_BG_COLOR);
}
return;
}
textColors.value = getTextColors(background);
isDark.value = textColors.value.active === '#000000';
root.style.setProperty('--hover-bg-color', getHoverBackgroundColor(isDark.value));
root.style.setProperty('--text-color-primary', textColors.value.primary);
root.style.setProperty('--text-color-active', textColors.value.active);
if (writeBgColor) {
const bg = writeBgColor();
root.style.setProperty('--bg-color', bg || DEFAULT_BG_COLOR);
}
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;
}
};
onBeforeUnmount(() => {
if (animationFrame.value) {
cancelAnimationFrame(animationFrame.value);
}
});
return {
isDark,
currentBackground,
applyBackground
};
}
+16 -4
View File
@@ -6,7 +6,8 @@ import { getMusicLrc, getMusicUrl, getParsingMusicUrl } from '@/api/music';
import { playbackRequestManager } from '@/services/playbackRequestManager';
import { SongSourceConfigManager } from '@/services/SongSourceConfigManager';
import type { ILyric, ILyricText, IWordData, SongResult } from '@/types/music';
import { isElectron } from '@/utils';
import { getImgUrl, isElectron } from '@/utils';
import { getImageLinearBackground } from '@/utils/linearColor';
import { parseLyrics as parseYrcLyrics } from '@/utils/yrcParser';
const { message } = createDiscreteApi(['message']);
@@ -371,9 +372,11 @@ export const useLyrics = () => {
};
/**
* - URL
*
*/
export const useSongDetail = () => {
const { getSongUrl } = useSongUrl();
const getSongDetail = async (playMusic: SongResult, requestId?: string) => {
// 验证请求
if (requestId && !playbackRequestManager.isRequestValid(requestId)) {
@@ -402,10 +405,19 @@ export const useSongDetail = () => {
playMusic.createdAt = Date.now();
// 半小时后过期
playMusic.expiredAt = playMusic.createdAt + 1800000;
const { backgroundColor, primaryColor } =
playMusic.backgroundColor && playMusic.primaryColor
? playMusic
: await getImageLinearBackground(getImgUrl(playMusic?.picUrl, '30y30'));
// 验证请求
if (requestId && !playbackRequestManager.isRequestValid(requestId)) {
console.log(`[getSongDetail] 背景色获取后请求已失效: ${requestId}`);
throw new Error('Request cancelled');
}
playMusic.playLoading = false;
// 返回歌曲信息,背景色和歌词将在播放后异步加载
return { ...playMusic, playMusicUrl } as SongResult;
return { ...playMusic, playMusicUrl, backgroundColor, primaryColor } as SongResult;
} catch (error) {
if ((error as Error).message === 'Request cancelled') {
throw error;
@@ -1,96 +0,0 @@
import { computed, type ComputedRef, type Ref,ref } from 'vue';
import { usePlayerStore } from '@/store';
import { isMobile } from '@/utils';
type ProgressiveRenderOptions = {
/** 全量数据列表 */
items: ComputedRef<any[]> | Ref<any[]>;
/** 每项估算高度(px */
itemHeight: ComputedRef<number> | number;
/** 列表区域的 CSS 选择器,用于计算偏移 */
listSelector: string;
/** 初始渲染数量 */
initialCount?: number;
/** 滚动到底部时的回调(用于加载更多数据) */
onReachEnd?: () => void;
};
export const useProgressiveRender = (options: ProgressiveRenderOptions) => {
const { items, itemHeight, listSelector, initialCount = 40, onReachEnd } = options;
const playerStore = usePlayerStore();
const renderLimit = ref(initialCount);
const getItemHeight = () => (typeof itemHeight === 'number' ? itemHeight : itemHeight.value);
/** 截取到 renderLimit 的可渲染列表 */
const renderedItems = computed(() => {
const all = items.value;
return all.slice(0, renderLimit.value);
});
/** 未渲染项的占位高度,让滚动条反映真实总高度 */
const placeholderHeight = computed(() => {
const unrendered = items.value.length - renderedItems.value.length;
return Math.max(0, unrendered) * getItemHeight();
});
/** 是否正在播放(用于动态底部间距) */
const isPlaying = computed(() => !!playerStore.playMusicUrl);
/** 内容区底部 padding,播放时留出播放栏空间 */
const contentPaddingBottom = computed(() =>
isPlaying.value && !isMobile.value ? '220px' : '80px'
);
/** 重置渲染限制 */
const resetRenderLimit = () => {
renderLimit.value = initialCount;
};
/** 扩展渲染限制到指定索引 */
const expandTo = (index: number) => {
renderLimit.value = Math.max(renderLimit.value, index);
};
/**
* n-scrollbar @scroll
* renderLimit
*/
const handleScroll = (e: Event) => {
const target = e.target as HTMLElement;
const { scrollTop, clientHeight } = target;
const listSection = document.querySelector(listSelector) as HTMLElement;
const listStart = listSection?.offsetTop || 0;
const visibleBottom = scrollTop + clientHeight - listStart;
if (visibleBottom <= 0) return;
// 多渲染一屏作为缓冲
const bufferHeight = clientHeight;
const neededIndex = Math.ceil((visibleBottom + bufferHeight) / getItemHeight());
const allCount = items.value.length;
if (neededIndex > renderLimit.value) {
renderLimit.value = Math.min(neededIndex, allCount);
}
// 所有项都已渲染,通知外部加载更多数据
if (renderLimit.value >= allCount && onReachEnd) {
onReachEnd();
}
};
return {
renderLimit,
renderedItems,
placeholderHeight,
isPlaying,
contentPaddingBottom,
resetRenderLimit,
expandTo,
handleScroll
};
};
+9 -9
View File
@@ -9,10 +9,7 @@ import { usePlayerStore } from '@/store/modules/player';
export function useVolumeControl() {
const playerStore = usePlayerStore();
/** 是否静音 */
const isMuted = computed(() => playerStore.isMuted);
/** 音量滑块值 (0-100),静音时仍展示原始音量 */
/** 音量滑块值 (0-100) */
const volumeSlider = computed({
get: () => playerStore.volume * 100,
set: (value: number) => {
@@ -22,17 +19,21 @@ export function useVolumeControl() {
/** 音量图标 class */
const volumeIcon = computed(() => {
if (playerStore.isMuted || playerStore.volume === 0) return 'ri-volume-mute-line';
if (playerStore.volume === 0) return 'ri-volume-mute-line';
if (playerStore.volume <= 0.5) return 'ri-volume-down-line';
return 'ri-volume-up-line';
});
/** 切换静音(保留静音前的音量) */
/** 静音切换 (0 ↔ 30%) */
const mute = () => {
playerStore.toggleMute();
if (volumeSlider.value === 0) {
volumeSlider.value = 30;
} else {
volumeSlider.value = 0;
}
};
/** 鼠标滚轮调整音量 ±5%;静音时向上滚轮会自动解除静音 */
/** 鼠标滚轮调整音量 ±5% */
const handleVolumeWheel = (e: WheelEvent) => {
const delta = e.deltaY < 0 ? 5 : -5;
const newValue = Math.min(Math.max(volumeSlider.value + delta, 0), 100);
@@ -40,7 +41,6 @@ export function useVolumeControl() {
};
return {
isMuted,
volumeSlider,
volumeIcon,
mute,

Some files were not shown because too many files have changed in this diff Show More