mirror of
https://github.com/timeshiftsauce/CeruMusic.git
synced 2025-11-26 03:45:03 +08:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5fe6d93d5e | ||
|
|
30fd2ebb9f | ||
|
|
0f78f117d0 | ||
|
|
c79b6951d6 | ||
|
|
5118874712 | ||
|
|
7e5baba969 | ||
|
|
a7af89e35d | ||
|
|
d511efdfce | ||
|
|
9b6050be7a | ||
|
|
57736e60f3 | ||
|
|
6165a2619e | ||
|
|
c933b6e0b4 | ||
|
|
e0e01cbdca | ||
|
|
9b34ecbed9 | ||
|
|
1dda213013 | ||
|
|
94c2dc740f | ||
|
|
61f062455e | ||
|
|
79827f14f7 | ||
|
|
394bdd573c | ||
|
|
d03d62c8d4 | ||
|
|
be0b0b0390 | ||
|
|
c1d2f3dc8d | ||
|
|
e590c33c66 | ||
|
|
604ac7b553 | ||
|
|
18e233ae10 | ||
|
|
61699c4853 | ||
|
|
6e69920a5d | ||
|
|
a767b008a0 | ||
|
|
41b104e96d | ||
|
|
8562b7c954 | ||
|
|
b61e88b7d9 | ||
|
|
cc1dbcaf3f | ||
|
|
941af10830 | ||
|
|
576f9697d4 |
158
.github/workflows/auto-sync-release.yml
vendored
Normal file
158
.github/workflows/auto-sync-release.yml
vendored
Normal file
@@ -0,0 +1,158 @@
|
||||
name: Auto Sync New Release to WebDAV
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
auto-sync-to-webdav:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl jq
|
||||
|
||||
- name: Get release info
|
||||
id: release-info
|
||||
run: |
|
||||
echo "tag_name=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
|
||||
echo "release_id=${{ github.event.release.id }}" >> $GITHUB_OUTPUT
|
||||
echo "release_name=${{ github.event.release.name }}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Sync new release to WebDAV
|
||||
run: |
|
||||
TAG_NAME="${{ steps.release-info.outputs.tag_name }}"
|
||||
RELEASE_ID="${{ steps.release-info.outputs.release_id }}"
|
||||
RELEASE_NAME="${{ steps.release-info.outputs.release_name }}"
|
||||
|
||||
echo "🚀 开始同步新发布的版本到 WebDAV..."
|
||||
echo "版本标签: $TAG_NAME"
|
||||
echo "版本名称: $RELEASE_NAME"
|
||||
echo "Release ID: $RELEASE_ID"
|
||||
echo "WebDAV 根路径: ${{ secrets.WEBDAV_BASE_URL }}/yd/ceru"
|
||||
|
||||
# 获取该release的所有资源文件
|
||||
assets_json=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID/assets")
|
||||
|
||||
assets_count=$(echo "$assets_json" | jq '. | length')
|
||||
echo "找到 $assets_count 个资源文件"
|
||||
|
||||
if [ "$assets_count" -eq 0 ]; then
|
||||
echo "⚠️ 该版本没有资源文件,跳过同步"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 先创建版本目录
|
||||
dir_path="/yd/ceru/$TAG_NAME"
|
||||
dir_url="${{ secrets.WEBDAV_BASE_URL }}$dir_path"
|
||||
|
||||
echo "创建版本目录: $dir_path"
|
||||
if curl -s -f -X MKCOL \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
"$dir_url"; then
|
||||
echo "✅ 目录创建成功"
|
||||
else
|
||||
echo "ℹ️ 目录可能已存在或创建失败,继续执行"
|
||||
fi
|
||||
|
||||
# 处理每个asset
|
||||
success_count=0
|
||||
failed_count=0
|
||||
|
||||
for i in $(seq 0 $(($assets_count - 1))); do
|
||||
asset=$(echo "$assets_json" | jq -c ".[$i]")
|
||||
asset_name=$(echo "$asset" | jq -r '.name')
|
||||
asset_url=$(echo "$asset" | jq -r '.url')
|
||||
asset_size=$(echo "$asset" | jq -r '.size')
|
||||
|
||||
echo "📦 处理资源: $asset_name (大小: $asset_size bytes)"
|
||||
|
||||
# 下载资源文件
|
||||
safe_filename="./temp_${TAG_NAME}_$(date +%s)_$i"
|
||||
|
||||
if ! curl -sL -o "$safe_filename" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/octet-stream" \
|
||||
"$asset_url"; then
|
||||
echo "❌ 下载失败: $asset_name"
|
||||
failed_count=$((failed_count + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ -f "$safe_filename" ]; then
|
||||
actual_size=$(wc -c < "$safe_filename")
|
||||
if [ "$actual_size" -ne "$asset_size" ]; then
|
||||
echo "❌ 文件大小不匹配: $asset_name (期望: $asset_size, 实际: $actual_size)"
|
||||
rm -f "$safe_filename"
|
||||
failed_count=$((failed_count + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "⬆️ 上传到 WebDAV: $asset_name"
|
||||
|
||||
# 构建远程路径
|
||||
remote_path="/yd/ceru/$TAG_NAME/$asset_name"
|
||||
full_url="${{ secrets.WEBDAV_BASE_URL }}$remote_path"
|
||||
|
||||
# 使用 WebDAV PUT 方法上传文件
|
||||
if curl -s -f -X PUT \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-T "$safe_filename" \
|
||||
"$full_url"; then
|
||||
|
||||
echo "✅ 上传成功: $asset_name"
|
||||
success_count=$((success_count + 1))
|
||||
|
||||
# 验证文件是否存在
|
||||
sleep 1
|
||||
if curl -s -f -u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-X PROPFIND \
|
||||
-H "Depth: 0" \
|
||||
"$full_url" > /dev/null 2>&1; then
|
||||
echo "✅ 文件验证成功: $asset_name"
|
||||
else
|
||||
echo "⚠️ 文件验证失败,但上传可能成功: $asset_name"
|
||||
fi
|
||||
|
||||
else
|
||||
echo "❌ 上传失败: $asset_name"
|
||||
failed_count=$((failed_count + 1))
|
||||
fi
|
||||
|
||||
# 清理临时文件
|
||||
rm -f "$safe_filename"
|
||||
echo "----------------------------------------"
|
||||
else
|
||||
echo "❌ 临时文件不存在: $safe_filename"
|
||||
failed_count=$((failed_count + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
echo "========================================"
|
||||
echo "🎉 同步完成!"
|
||||
echo "成功: $success_count 个文件"
|
||||
echo "失败: $failed_count 个文件"
|
||||
echo "总计: $assets_count 个文件"
|
||||
|
||||
if [ "$failed_count" -gt 0 ]; then
|
||||
echo "⚠️ 有文件同步失败,请检查日志"
|
||||
exit 1
|
||||
else
|
||||
echo "✅ 所有文件同步成功!"
|
||||
fi
|
||||
|
||||
- name: Notify completion
|
||||
if: always()
|
||||
run: |
|
||||
if [ "${{ job.status }}" == "success" ]; then
|
||||
echo "✅ 版本 ${{ steps.release-info.outputs.tag_name }} 已成功同步到 alist"
|
||||
else
|
||||
echo "❌ 版本 ${{ steps.release-info.outputs.tag_name }} 同步失败"
|
||||
fi
|
||||
143
.github/workflows/main.yml
vendored
143
.github/workflows/main.yml
vendored
@@ -70,3 +70,146 @@ jobs:
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
files: 'dist/**' # 将dist目录下所有文件添加到release
|
||||
|
||||
# 新增:自动同步到 WebDAV
|
||||
sync-to-webdav:
|
||||
name: Sync to WebDAV
|
||||
needs: release # 等待 release 任务完成
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/v') # 只在标签推送时执行
|
||||
steps:
|
||||
- name: Wait for release to be ready
|
||||
run: |
|
||||
echo "等待 Release 准备就绪..."
|
||||
sleep 30 # 等待30秒确保 release 完全创建
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl jq
|
||||
|
||||
- name: Get latest release info
|
||||
id: get-release
|
||||
run: |
|
||||
# 获取当前标签对应的 release 信息
|
||||
TAG_NAME=${GITHUB_REF#refs/tags/}
|
||||
echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT
|
||||
|
||||
# 获取 release 详细信息
|
||||
response=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/tags/$TAG_NAME")
|
||||
|
||||
release_id=$(echo "$response" | jq -r '.id')
|
||||
echo "release_id=$release_id" >> $GITHUB_OUTPUT
|
||||
echo "找到 Release ID: $release_id"
|
||||
|
||||
- name: Sync release to WebDAV
|
||||
run: |
|
||||
TAG_NAME="${{ steps.get-release.outputs.tag_name }}"
|
||||
RELEASE_ID="${{ steps.get-release.outputs.release_id }}"
|
||||
|
||||
echo "🚀 开始同步版本 $TAG_NAME 到 WebDAV..."
|
||||
echo "Release ID: $RELEASE_ID"
|
||||
echo "WebDAV 根路径: ${{ secrets.WEBDAV_BASE_URL }}/yd/ceru"
|
||||
|
||||
# 获取该release的所有资源文件
|
||||
assets_json=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/$RELEASE_ID/assets")
|
||||
|
||||
assets_count=$(echo "$assets_json" | jq '. | length')
|
||||
echo "找到 $assets_count 个资源文件"
|
||||
|
||||
if [ "$assets_count" -eq 0 ]; then
|
||||
echo "⚠️ 该版本没有资源文件,跳过同步"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# 先创建版本目录
|
||||
dir_path="/yd/ceru/$TAG_NAME"
|
||||
dir_url="${{ secrets.WEBDAV_BASE_URL }}$dir_path"
|
||||
|
||||
echo "创建版本目录: $dir_path"
|
||||
curl -s -X MKCOL \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
"$dir_url" || echo "目录可能已存在"
|
||||
|
||||
# 处理每个asset
|
||||
success_count=0
|
||||
failed_count=0
|
||||
|
||||
for i in $(seq 0 $(($assets_count - 1))); do
|
||||
asset=$(echo "$assets_json" | jq -c ".[$i]")
|
||||
asset_name=$(echo "$asset" | jq -r '.name')
|
||||
asset_url=$(echo "$asset" | jq -r '.url')
|
||||
asset_size=$(echo "$asset" | jq -r '.size')
|
||||
|
||||
echo "📦 处理资源: $asset_name (大小: $asset_size bytes)"
|
||||
|
||||
# 下载资源文件
|
||||
safe_filename="./temp_${TAG_NAME}_$(date +%s)_$i"
|
||||
|
||||
if ! curl -sL -o "$safe_filename" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/octet-stream" \
|
||||
"$asset_url"; then
|
||||
echo "❌ 下载失败: $asset_name"
|
||||
failed_count=$((failed_count + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ -f "$safe_filename" ]; then
|
||||
actual_size=$(wc -c < "$safe_filename")
|
||||
if [ "$actual_size" -ne "$asset_size" ]; then
|
||||
echo "❌ 文件大小不匹配: $asset_name (期望: $asset_size, 实际: $actual_size)"
|
||||
rm -f "$safe_filename"
|
||||
failed_count=$((failed_count + 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "⬆️ 上传到 WebDAV: $asset_name"
|
||||
|
||||
# 构建远程路径
|
||||
remote_path="/yd/ceru/$TAG_NAME/$asset_name"
|
||||
full_url="${{ secrets.WEBDAV_BASE_URL }}$remote_path"
|
||||
|
||||
# 使用 WebDAV PUT 方法上传文件
|
||||
if curl -s -f -X PUT \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-T "$safe_filename" \
|
||||
"$full_url"; then
|
||||
|
||||
echo "✅ 上传成功: $asset_name"
|
||||
success_count=$((success_count + 1))
|
||||
|
||||
else
|
||||
echo "❌ 上传失败: $asset_name"
|
||||
failed_count=$((failed_count + 1))
|
||||
fi
|
||||
|
||||
# 清理临时文件
|
||||
rm -f "$safe_filename"
|
||||
echo "----------------------------------------"
|
||||
else
|
||||
echo "❌ 临时文件不存在: $safe_filename"
|
||||
failed_count=$((failed_count + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
echo "========================================"
|
||||
echo "🎉 同步完成!"
|
||||
echo "成功: $success_count 个文件"
|
||||
echo "失败: $failed_count 个文件"
|
||||
echo "总计: $assets_count 个文件"
|
||||
|
||||
- name: Notify completion
|
||||
if: always()
|
||||
run: |
|
||||
if [ "${{ job.status }}" == "success" ]; then
|
||||
echo "✅ 版本 ${{ steps.get-release.outputs.tag_name }} 已成功同步到 alist"
|
||||
else
|
||||
echo "❌ 版本 ${{ steps.get-release.outputs.tag_name }} 同步失败"
|
||||
fi
|
||||
|
||||
154
.github/workflows/sync-releases-to-webdav.yml
vendored
Normal file
154
.github/workflows/sync-releases-to-webdav.yml
vendored
Normal file
@@ -0,0 +1,154 @@
|
||||
name: Sync Existing Releases to Alist
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: '要同步的特定标签(如 v1.0.0),留空则同步所有版本'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync-releases-to-alist:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl jq
|
||||
|
||||
- name: Get all releases
|
||||
id: get-releases
|
||||
run: |
|
||||
response=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases")
|
||||
echo "releases_json=$(echo "$response" | jq -c '.')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Sync releases to Alist(自动登录 & 上传)
|
||||
run: |
|
||||
# ========== 1. 读取输入参数 ==========
|
||||
SPECIFIC_TAG="${{ github.event.inputs.tag_name }}"
|
||||
RELEASES_JSON='${{ steps.get-releases.outputs.releases_json }}'
|
||||
|
||||
# ========== 2. Alist 连接信息 ==========
|
||||
ALIST_URL="https://alist.shiqianjiang.cn" # https://pan.example.com
|
||||
ALIST_USER="${{ secrets.WEBDAV_USERNAME }}" # Alist 登录账号
|
||||
ALIST_PASS="${{ secrets.WEBDAV_PASSWORD }}" # Alist 登录密码
|
||||
ALIST_DIR="/yd/ceru" # 目标根目录
|
||||
|
||||
# ========== 3. 登录拿 token ==========
|
||||
echo "正在登录 Alist ..."
|
||||
login_resp=$(curl -s -X POST "$ALIST_URL/api/auth/login" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"username\": \"$ALIST_USER\",
|
||||
\"password\": \"$ALIST_PASS\"
|
||||
}")
|
||||
echo "$login_resp"
|
||||
token=$(echo "$login_resp" | jq -r '.data.token // empty')
|
||||
|
||||
if [ -z "$token" ]; then
|
||||
echo "❌ 登录失败,返回:$login_resp"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ 登录成功,token 已获取"
|
||||
|
||||
# ========== 4. 循环处理 release ==========
|
||||
releases_count=$(echo "$RELEASES_JSON" | jq '. | length')
|
||||
echo "找到 $releases_count 个 releases"
|
||||
for i in $(seq 0 $(($releases_count - 1))); do
|
||||
release=$(echo "$RELEASES_JSON" | jq -c ".[$i]")
|
||||
tag_name=$(echo "$release" | jq -r '.tag_name')
|
||||
release_id=$(echo "$release" | jq -r '.id')
|
||||
|
||||
[ -n "$SPECIFIC_TAG" ] && [ "$tag_name" != "$SPECIFIC_TAG" ] && {
|
||||
echo "跳过 $tag_name,不是指定标签"
|
||||
continue
|
||||
}
|
||||
|
||||
echo "处理版本: $tag_name (ID: $release_id)"
|
||||
assets_json=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/$release_id/assets")
|
||||
assets_count=$(echo "$assets_json" | jq '. | length')
|
||||
echo "找到 $assets_count 个资源文件"
|
||||
|
||||
for j in $(seq 0 $(($assets_count - 1))); do
|
||||
asset=$(echo "$assets_json" | jq -c ".[$j]")
|
||||
asset_name=$(echo "$asset" | jq -r '.name')
|
||||
asset_url=$(echo "$asset" | jq -r '.url')
|
||||
asset_size=$(echo "$asset" | jq -r '.size')
|
||||
|
||||
echo "下载资源: $asset_name (大小: $asset_size bytes)"
|
||||
safe_filename="./temp_download_$(date +%s)_$j"
|
||||
|
||||
# 下载
|
||||
curl -sL -o "$safe_filename" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/octet-stream" \
|
||||
"$asset_url" || {
|
||||
echo "❌ 下载失败: $asset_name"
|
||||
continue
|
||||
}
|
||||
|
||||
# 大小校验
|
||||
actual_size=$(wc -c < "$safe_filename")
|
||||
[ "$actual_size" -ne "$asset_size" ] && {
|
||||
echo "❌ 文件大小不匹配: $asset_name"
|
||||
rm -f "$safe_filename"
|
||||
continue
|
||||
}
|
||||
|
||||
# 组装远程路径(URL 编码)
|
||||
remote_path="$ALIST_DIR/$tag_name/$asset_name"
|
||||
file_path_encoded=$(printf %s "$remote_path" | jq -sRr @uri)
|
||||
echo "上传到 Alist: $remote_path"
|
||||
|
||||
# 调用 /api/fs/put 上传(带 As-Task 异步)
|
||||
response=$(
|
||||
curl -s -X PUT "$ALIST_URL/api/fs/put" \
|
||||
-H "Authorization: $token" \
|
||||
-H "File-Path: $file_path_encoded" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
-H "Content-Length: $actual_size" \
|
||||
-H "As-Task: true" \
|
||||
--data-binary @"$safe_filename"
|
||||
)
|
||||
echo "==== 上传接口原始返回 ===="
|
||||
echo "$response"
|
||||
code=$(echo "$response" | jq -r '.code // empty')
|
||||
if [ "$code" = "200" ]; then
|
||||
echo "✅ Alist 上传任务创建成功: $asset_name"
|
||||
else
|
||||
echo "❌ Alist 上传失败: $asset_name"
|
||||
fi
|
||||
|
||||
rm -f "$safe_filename"
|
||||
echo "----------------------------------------"
|
||||
done
|
||||
echo "版本 $tag_name 处理完成"
|
||||
echo "========================================"
|
||||
done
|
||||
|
||||
# ========== 5. 退出登录 ==========
|
||||
echo "退出登录 ..."
|
||||
curl -s -X POST "$ALIST_URL/api/auth/logout" \
|
||||
-H "Authorization: $token" > /dev/null || true
|
||||
|
||||
echo "🎉 Alist 同步完成"
|
||||
|
||||
- name: Summary
|
||||
run: |
|
||||
echo "同步任务已完成!"
|
||||
echo "请检查 Alist 中的文件是否正确上传。"
|
||||
echo "如果遇到问题,请检查以下配置:"
|
||||
echo "1. ALIST_URL - Alist 服务器地址"
|
||||
echo "2. ALIST_USERNAME - Alist 登录账号"
|
||||
echo "3. ALIST_PASSWORD - Alist 登录密码"
|
||||
echo "4. GITHUB_TOKEN - GitHub 访问令牌"
|
||||
160
.github/workflows/uploadpan.yml
vendored
Normal file
160
.github/workflows/uploadpan.yml
vendored
Normal file
@@ -0,0 +1,160 @@
|
||||
name: Sync Existing Releases to WebDAV
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: '要同步的特定标签(如 v1.0.0),留空则同步所有版本'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
sync-releases-to-webdav:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl
|
||||
|
||||
- name: Get all releases
|
||||
id: get-releases
|
||||
run: |
|
||||
response=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases")
|
||||
echo "releases_json=$(echo "$response" | jq -c '.')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Sync releases to WebDAV
|
||||
run: |
|
||||
# 读取输入参数
|
||||
SPECIFIC_TAG="${{ github.event.inputs.tag_name }}"
|
||||
RELEASES_JSON='${{ steps.get-releases.outputs.releases_json }}'
|
||||
|
||||
echo "开始同步 releases..."
|
||||
echo "特定标签: ${SPECIFIC_TAG:-所有版本}"
|
||||
echo "WebDAV 根路径: ${{ secrets.WEBDAV_BASE_URL }}/yd/ceru"
|
||||
|
||||
# 处理每个 release
|
||||
releases_count=$(echo "$RELEASES_JSON" | jq '. | length')
|
||||
echo "找到 $releases_count 个 releases"
|
||||
|
||||
for i in $(seq 0 $(($releases_count - 1))); do
|
||||
release=$(echo "$RELEASES_JSON" | jq -c ".[$i]")
|
||||
tag_name=$(echo "$release" | jq -r '.tag_name')
|
||||
release_id=$(echo "$release" | jq -r '.id')
|
||||
|
||||
if [ -n "$SPECIFIC_TAG" ] && [ "$tag_name" != "$SPECIFIC_TAG" ]; then
|
||||
echo "跳过 $tag_name,不是指定的标签 $SPECIFIC_TAG"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "正在处理版本: $tag_name (ID: $release_id)"
|
||||
|
||||
# 获取该release的所有资源文件
|
||||
assets_json=$(curl -s \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/releases/$release_id/assets")
|
||||
|
||||
assets_count=$(echo "$assets_json" | jq '. | length')
|
||||
echo "找到 $assets_count 个资源文件"
|
||||
|
||||
# 处理每个asset
|
||||
for j in $(seq 0 $(($assets_count - 1))); do
|
||||
asset=$(echo "$assets_json" | jq -c ".[$j]")
|
||||
asset_name=$(echo "$asset" | jq -r '.name')
|
||||
asset_url=$(echo "$asset" | jq -r '.url')
|
||||
asset_size=$(echo "$asset" | jq -r '.size')
|
||||
|
||||
echo "下载资源: $asset_name (大小: $asset_size bytes)"
|
||||
|
||||
# 下载资源文件
|
||||
safe_filename="./temp_download"
|
||||
|
||||
if ! curl -sL -o "$safe_filename" \
|
||||
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||
-H "Accept: application/octet-stream" \
|
||||
"$asset_url"; then
|
||||
echo "❌ 下载失败: $asset_name"
|
||||
continue
|
||||
fi
|
||||
|
||||
if [ -f "$safe_filename" ]; then
|
||||
actual_size=$(wc -c < "$safe_filename")
|
||||
if [ "$actual_size" -ne "$asset_size" ]; then
|
||||
echo "❌ 文件大小不匹配: $asset_name (期望: $asset_size, 实际: $actual_size)"
|
||||
rm -f "$safe_filename"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "上传到 WebDAV: $asset_name"
|
||||
|
||||
# 构建远程路径
|
||||
remote_path="/yd/ceru/$tag_name/$asset_name"
|
||||
full_url="${{ secrets.WEBDAV_BASE_URL }}$remote_path"
|
||||
|
||||
echo "完整路径: $full_url"
|
||||
|
||||
# 使用 WebDAV PUT 方法上传文件
|
||||
if curl -s -f -X PUT \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-T "$safe_filename" \
|
||||
"$full_url"; then
|
||||
|
||||
echo "✅ WebDAV 上传成功: $asset_name"
|
||||
|
||||
# 验证文件是否存在
|
||||
echo "验证文件是否存在..."
|
||||
sleep 2
|
||||
|
||||
if curl -s -f -u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-X PROPFIND \
|
||||
-H "Depth: 0" \
|
||||
"$full_url" > /dev/null 2>&1; then
|
||||
echo "✅ 文件确认存在: $asset_name"
|
||||
else
|
||||
echo "⚠️ 文件验证失败,但上传可能成功"
|
||||
fi
|
||||
|
||||
else
|
||||
echo "❌ WebDAV 上传失败: $asset_name"
|
||||
echo "尝试创建目录后重新上传..."
|
||||
|
||||
# 尝试先创建目录
|
||||
dir_path="/yd/ceru/$tag_name"
|
||||
dir_url="${{ secrets.WEBDAV_BASE_URL }}$dir_path"
|
||||
|
||||
if curl -s -f -X MKCOL \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
"$dir_url"; then
|
||||
echo "✅ 目录创建成功: $dir_path"
|
||||
|
||||
# 重新尝试上传文件
|
||||
if curl -s -f -X PUT \
|
||||
-u "${{ secrets.WEBDAV_USERNAME }}:${{ secrets.WEBDAV_PASSWORD }}" \
|
||||
-T "$safe_filename" \
|
||||
"$full_url"; then
|
||||
echo "✅ 重新上传成功: $asset_name"
|
||||
else
|
||||
echo "❌ 重新上传失败: $asset_name"
|
||||
fi
|
||||
else
|
||||
echo "❌ 目录创建失败: $dir_path"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 安全删除临时文件
|
||||
rm -f "$safe_filename"
|
||||
echo "----------------------------------------"
|
||||
else
|
||||
echo "❌ 文件不存在: $safe_filename"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo "🎉 WebDAV 同步完成"
|
||||
128
docs/alist-config.md
Normal file
128
docs/alist-config.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# Alist 下载配置说明
|
||||
|
||||
## 概述
|
||||
|
||||
项目已从 GitHub 下载方式切换到 Alist API 下载方式,包括:
|
||||
- 桌面应用的自动更新功能 (`src/main/autoUpdate.ts`)
|
||||
- 官方网站的下载功能 (`website/script.js`)
|
||||
|
||||
## 配置步骤
|
||||
|
||||
### 1. 修改 Alist 域名
|
||||
|
||||
#### 桌面应用配置
|
||||
在 `src/main/autoUpdate.ts` 文件中,Alist 域名已配置为:
|
||||
|
||||
```typescript
|
||||
const ALIST_BASE_URL = 'http://47.96.72.224:5244';
|
||||
```
|
||||
|
||||
#### 网站配置
|
||||
在 `website/script.js` 文件中,Alist 域名已配置为:
|
||||
|
||||
```javascript
|
||||
const ALIST_BASE_URL = 'http://47.96.72.224:5244';
|
||||
```
|
||||
|
||||
如需修改域名,请同时更新这两个文件中的 `ALIST_BASE_URL` 配置。
|
||||
|
||||
### 2. 认证信息
|
||||
|
||||
已配置的认证信息:
|
||||
- 用户名: `ceruupdata`
|
||||
- 密码: `123456`
|
||||
|
||||
### 3. 文件路径格式
|
||||
|
||||
文件在 Alist 中的路径格式为:`/{version}/{文件名}`
|
||||
|
||||
例如:
|
||||
- 版本 `v1.0.0` 的安装包 `app-setup.exe` 路径为:`/v1.0.0/app-setup.exe`
|
||||
|
||||
## 工作原理
|
||||
|
||||
### 桌面应用自动更新
|
||||
1. **认证**: 使用配置的用户名和密码向 Alist API 获取认证 token
|
||||
2. **获取文件信息**: 使用 token 调用 `/api/fs/get` 接口获取文件信息和签名
|
||||
3. **下载**: 使用带签名的直接下载链接下载文件
|
||||
4. **备用方案**: 如果 Alist 失败,自动回退到原始 URL 下载
|
||||
|
||||
### 网站下载功能
|
||||
1. **获取版本列表**: 调用 `/api/fs/list` 获取根目录下的版本文件夹
|
||||
2. **获取文件列表**: 获取最新版本文件夹中的所有文件
|
||||
3. **平台匹配**: 根据用户平台自动匹配对应的安装包文件
|
||||
4. **生成下载链接**: 获取文件的直接下载链接
|
||||
5. **备用方案**: 如果 Alist 失败,自动回退到 GitHub API
|
||||
|
||||
## API 接口
|
||||
|
||||
### 认证接口
|
||||
```
|
||||
POST /api/auth/login
|
||||
{
|
||||
"username": "ceruupdata",
|
||||
"password": "123456"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取文件信息接口
|
||||
```
|
||||
POST /api/fs/get
|
||||
Headers: Authorization: {token} # 注意:直接使用 token,不需要 "Bearer " 前缀
|
||||
{
|
||||
"path": "/{version}/{fileName}"
|
||||
}
|
||||
```
|
||||
|
||||
### 获取文件列表接口
|
||||
```
|
||||
POST /api/fs/list
|
||||
Headers: Authorization: {token} # 注意:直接使用 token,不需要 "Bearer " 前缀
|
||||
{
|
||||
"path": "/",
|
||||
"password": "",
|
||||
"page": 1,
|
||||
"per_page": 100,
|
||||
"refresh": false
|
||||
}
|
||||
```
|
||||
|
||||
### 下载链接格式
|
||||
```
|
||||
{ALIST_BASE_URL}/d/{filePath}?sign={sign}
|
||||
```
|
||||
|
||||
## 测试方法
|
||||
|
||||
项目包含了一个测试脚本来验证 Alist 连接:
|
||||
|
||||
```bash
|
||||
node scripts/test-alist.js
|
||||
```
|
||||
|
||||
该脚本会:
|
||||
1. 测试服务器连通性
|
||||
2. 测试用户认证
|
||||
3. 测试文件列表获取
|
||||
4. 测试文件信息获取
|
||||
|
||||
## 备用机制
|
||||
|
||||
两个组件都实现了备用机制:
|
||||
|
||||
### 桌面应用
|
||||
- 主要:使用 Alist API 下载
|
||||
- 备用:如果 Alist 失败,使用原始 URL 下载
|
||||
|
||||
### 网站
|
||||
- 主要:使用 Alist API 获取版本和文件信息
|
||||
- 备用:如果 Alist 失败,回退到 GitHub API
|
||||
- 最终备用:跳转到 GitHub releases 页面
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 确保 Alist 服务器可以正常访问
|
||||
2. 确保配置的用户名和密码有权限访问相应的文件路径
|
||||
3. 文件必须按照指定的路径格式存放在 Alist 中
|
||||
4. 网站会自动检测用户操作系统并推荐对应的下载版本
|
||||
5. 所有下载都会显示文件大小信息
|
||||
88
docs/alist-migration-summary.md
Normal file
88
docs/alist-migration-summary.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Alist 迁移完成总结
|
||||
|
||||
## 修改概述
|
||||
|
||||
项目已成功从 GitHub 下载方式迁移到 Alist API 下载方式。
|
||||
|
||||
## 修改的文件
|
||||
|
||||
### 1. 桌面应用自动更新 (`src/main/autoUpdate.ts`)
|
||||
- ✅ 添加了 Alist API 配置
|
||||
- ✅ 实现了 Alist 认证功能
|
||||
- ✅ 实现了 Alist 文件下载功能
|
||||
- ✅ 添加了备用机制(Alist 失败时回退到原始 URL)
|
||||
- ✅ 修复了 Authorization 头格式(使用直接 token 而非 Bearer 格式)
|
||||
|
||||
### 2. 官方网站下载功能 (`website/script.js`)
|
||||
- ✅ 添加了 Alist API 配置
|
||||
- ✅ 实现了 Alist 认证功能
|
||||
- ✅ 实现了版本列表获取功能
|
||||
- ✅ 实现了文件列表获取功能
|
||||
- ✅ 实现了平台文件匹配功能
|
||||
- ✅ 添加了多层备用机制(Alist → GitHub API → GitHub 页面)
|
||||
- ✅ 修复了 Authorization 头格式
|
||||
|
||||
### 3. 配置文档
|
||||
- ✅ 创建了详细的配置说明 (`docs/alist-config.md`)
|
||||
- ✅ 创建了迁移总结文档 (`docs/alist-migration-summary.md`)
|
||||
|
||||
### 4. 测试脚本
|
||||
- ✅ 创建了 Alist 连接测试脚本 (`scripts/test-alist.js`)
|
||||
- ✅ 创建了认证格式测试脚本 (`scripts/auth-test.js`)
|
||||
|
||||
## 配置信息
|
||||
|
||||
### Alist 服务器配置
|
||||
- **服务器地址**: `http://47.96.72.224:5244`
|
||||
- **用户名**: `ceruupdate`
|
||||
- **密码**: `123456`
|
||||
- **文件路径格式**: `/{version}/{文件名}`
|
||||
|
||||
### Authorization 头格式
|
||||
经过测试确认,正确的格式是:
|
||||
```
|
||||
Authorization: {token}
|
||||
```
|
||||
**注意**: 不需要 "Bearer " 前缀
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 桌面应用
|
||||
1. **智能下载**: 优先使用 Alist API,失败时自动回退
|
||||
2. **进度显示**: 支持下载进度显示和节流
|
||||
3. **错误处理**: 完善的错误处理和日志记录
|
||||
|
||||
### 网站
|
||||
1. **自动检测**: 自动检测用户操作系统并推荐对应版本
|
||||
2. **版本信息**: 自动获取最新版本信息和文件大小
|
||||
3. **多层备用**: Alist → GitHub API → GitHub 页面的三层备用机制
|
||||
4. **用户体验**: 加载状态、成功通知、错误提示
|
||||
|
||||
## 测试结果
|
||||
|
||||
✅ **Alist 连接测试**: 通过
|
||||
✅ **认证测试**: 通过
|
||||
✅ **文件列表获取**: 通过
|
||||
✅ **Authorization 头格式**: 已修复并验证
|
||||
|
||||
## 可用文件
|
||||
|
||||
测试显示 Alist 服务器当前包含以下文件:
|
||||
- `v1.2.1/` (版本目录)
|
||||
- `1111`
|
||||
- `L3YxLjIuMS8tMS4yLjEtYXJtNjQtbWFjLnppcA==`
|
||||
- `file2.msi`
|
||||
- `file.msi`
|
||||
|
||||
## 后续维护
|
||||
|
||||
1. **添加新版本**: 在 Alist 中创建新的版本目录(如 `v1.2.2/`)
|
||||
2. **上传文件**: 将对应平台的安装包上传到版本目录中
|
||||
3. **文件命名**: 确保文件名包含平台标识(如 `windows`, `mac`, `linux` 等)
|
||||
|
||||
## 备注
|
||||
|
||||
- 所有修改都保持了向后兼容性
|
||||
- 实现了完善的错误处理和备用机制
|
||||
- 用户体验不会因为迁移而受到影响
|
||||
- 可以随时回退到 GitHub 下载方式
|
||||
422
docs/songlist-api.md
Normal file
422
docs/songlist-api.md
Normal file
@@ -0,0 +1,422 @@
|
||||
# 歌单管理 API 文档
|
||||
|
||||
本文档介绍了 CeruMusic 中歌单管理功能的使用方法,包括后端服务类和前端 API 接口。
|
||||
|
||||
## 概述
|
||||
|
||||
歌单管理系统提供了完整的歌单和歌曲管理功能,包括:
|
||||
|
||||
- 📁 **歌单管理**:创建、删除、编辑、搜索歌单
|
||||
- 🎵 **歌曲管理**:添加、移除、搜索歌单中的歌曲
|
||||
- 📊 **统计分析**:获取歌单和歌曲的统计信息
|
||||
- 🔧 **数据维护**:验证和修复歌单数据完整性
|
||||
- ⚡ **批量操作**:支持批量删除和批量移除操作
|
||||
|
||||
## 架构设计
|
||||
|
||||
```
|
||||
前端 (Renderer Process)
|
||||
├── src/renderer/src/api/songList.ts # 前端 API 封装
|
||||
├── src/renderer/src/examples/songListUsage.ts # 使用示例
|
||||
└── src/types/songList.ts # TypeScript 类型定义
|
||||
|
||||
主进程 (Main Process)
|
||||
├── src/main/events/songList.ts # IPC 事件处理
|
||||
├── src/main/services/songList/ManageSongList.ts # 歌单管理服务
|
||||
└── src/main/services/songList/PlayListSongs.ts # 歌曲管理基类
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 前端使用
|
||||
|
||||
```typescript
|
||||
import songListAPI from '@/api/songList'
|
||||
|
||||
// 创建歌单
|
||||
const result = await songListAPI.create('我的收藏', '我最喜欢的歌曲')
|
||||
if (result.success) {
|
||||
console.log('歌单创建成功,ID:', result.data?.id)
|
||||
}
|
||||
|
||||
// 获取所有歌单
|
||||
const playlists = await songListAPI.getAll()
|
||||
if (playlists.success) {
|
||||
console.log('歌单列表:', playlists.data)
|
||||
}
|
||||
|
||||
// 添加歌曲到歌单
|
||||
const songs = [/* 歌曲数据 */]
|
||||
await songListAPI.addSongs(playlistId, songs)
|
||||
```
|
||||
|
||||
### 2. 类型安全
|
||||
|
||||
所有 API 都提供了完整的 TypeScript 类型支持:
|
||||
|
||||
```typescript
|
||||
import type { IPCResponse, SongListStatistics } from '@/types/songList'
|
||||
|
||||
const stats: IPCResponse<SongListStatistics> = await songListAPI.getStatistics()
|
||||
```
|
||||
|
||||
## API 参考
|
||||
|
||||
### 歌单管理
|
||||
|
||||
#### `create(name, description?, source?)`
|
||||
创建新歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.create('我的收藏', '描述', 'local')
|
||||
// 返回: { success: boolean, data?: { id: string }, error?: string }
|
||||
```
|
||||
|
||||
#### `getAll()`
|
||||
获取所有歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getAll()
|
||||
// 返回: { success: boolean, data?: SongList[], error?: string }
|
||||
```
|
||||
|
||||
#### `getById(hashId)`
|
||||
根据ID获取歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getById('playlist-id')
|
||||
// 返回: { success: boolean, data?: SongList | null, error?: string }
|
||||
```
|
||||
|
||||
#### `delete(hashId)`
|
||||
删除歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.delete('playlist-id')
|
||||
// 返回: { success: boolean, error?: string }
|
||||
```
|
||||
|
||||
#### `batchDelete(hashIds)`
|
||||
批量删除歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.batchDelete(['id1', 'id2'])
|
||||
// 返回: { success: boolean, data?: { success: string[], failed: string[] } }
|
||||
```
|
||||
|
||||
#### `edit(hashId, updates)`
|
||||
编辑歌单信息
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.edit('playlist-id', {
|
||||
name: '新名称',
|
||||
description: '新描述'
|
||||
})
|
||||
```
|
||||
|
||||
#### `search(keyword, source?)`
|
||||
搜索歌单
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.search('关键词', 'local')
|
||||
// 返回: { success: boolean, data?: SongList[], error?: string }
|
||||
```
|
||||
|
||||
### 歌曲管理
|
||||
|
||||
#### `addSongs(hashId, songs)`
|
||||
添加歌曲到歌单
|
||||
|
||||
```typescript
|
||||
const songs: Songs[] = [/* 歌曲数据 */]
|
||||
const result = await songListAPI.addSongs('playlist-id', songs)
|
||||
```
|
||||
|
||||
#### `removeSong(hashId, songmid)`
|
||||
移除单首歌曲
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.removeSong('playlist-id', 'song-id')
|
||||
// 返回: { success: boolean, data?: boolean, error?: string }
|
||||
```
|
||||
|
||||
#### `removeSongs(hashId, songmids)`
|
||||
批量移除歌曲
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.removeSongs('playlist-id', ['song1', 'song2'])
|
||||
// 返回: { success: boolean, data?: { removed: number, notFound: number } }
|
||||
```
|
||||
|
||||
#### `getSongs(hashId)`
|
||||
获取歌单中的歌曲
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getSongs('playlist-id')
|
||||
// 返回: { success: boolean, data?: readonly Songs[], error?: string }
|
||||
```
|
||||
|
||||
#### `searchSongs(hashId, keyword)`
|
||||
搜索歌单中的歌曲
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.searchSongs('playlist-id', '关键词')
|
||||
// 返回: { success: boolean, data?: Songs[], error?: string }
|
||||
```
|
||||
|
||||
### 统计信息
|
||||
|
||||
#### `getStatistics()`
|
||||
获取歌单统计信息
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getStatistics()
|
||||
// 返回: {
|
||||
// success: boolean,
|
||||
// data?: {
|
||||
// total: number,
|
||||
// bySource: Record<string, number>,
|
||||
// lastUpdated: string
|
||||
// }
|
||||
// }
|
||||
```
|
||||
|
||||
#### `getSongStatistics(hashId)`
|
||||
获取歌单歌曲统计信息
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getSongStatistics('playlist-id')
|
||||
// 返回: {
|
||||
// success: boolean,
|
||||
// data?: {
|
||||
// total: number,
|
||||
// bySinger: Record<string, number>,
|
||||
// byAlbum: Record<string, number>,
|
||||
// lastModified: string
|
||||
// }
|
||||
// }
|
||||
```
|
||||
|
||||
### 数据维护
|
||||
|
||||
#### `validateIntegrity(hashId)`
|
||||
验证歌单数据完整性
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.validateIntegrity('playlist-id')
|
||||
// 返回: { success: boolean, data?: { isValid: boolean, issues: string[] } }
|
||||
```
|
||||
|
||||
#### `repairData(hashId)`
|
||||
修复歌单数据
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.repairData('playlist-id')
|
||||
// 返回: { success: boolean, data?: { fixed: boolean, changes: string[] } }
|
||||
```
|
||||
|
||||
### 便捷方法
|
||||
|
||||
#### `getPlaylistDetail(hashId)`
|
||||
获取歌单详细信息(包含歌曲列表)
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.getPlaylistDetail('playlist-id')
|
||||
// 返回: {
|
||||
// playlist: SongList | null,
|
||||
// songs: readonly Songs[],
|
||||
// success: boolean,
|
||||
// error?: string
|
||||
// }
|
||||
```
|
||||
|
||||
#### `checkAndRepair(hashId)`
|
||||
检查并修复歌单数据
|
||||
|
||||
```typescript
|
||||
const result = await songListAPI.checkAndRepair('playlist-id')
|
||||
// 返回: {
|
||||
// needsRepair: boolean,
|
||||
// repairResult?: RepairResult,
|
||||
// success: boolean,
|
||||
// error?: string
|
||||
// }
|
||||
```
|
||||
|
||||
## 错误处理
|
||||
|
||||
所有 API 都返回统一的响应格式:
|
||||
|
||||
```typescript
|
||||
interface IPCResponse<T = any> {
|
||||
success: boolean // 操作是否成功
|
||||
data?: T // 返回的数据
|
||||
error?: string // 错误信息
|
||||
message?: string // 附加消息
|
||||
code?: string // 错误码
|
||||
}
|
||||
```
|
||||
|
||||
### 错误码说明
|
||||
|
||||
| 错误码 | 说明 |
|
||||
|--------|------|
|
||||
| `INVALID_HASH_ID` | 无效的歌单ID |
|
||||
| `PLAYLIST_NOT_FOUND` | 歌单不存在 |
|
||||
| `EMPTY_NAME` | 歌单名称为空 |
|
||||
| `CREATE_FAILED` | 创建失败 |
|
||||
| `DELETE_FAILED` | 删除失败 |
|
||||
| `EDIT_FAILED` | 编辑失败 |
|
||||
| `READ_FAILED` | 读取失败 |
|
||||
| `WRITE_FAILED` | 写入失败 |
|
||||
|
||||
## 使用示例
|
||||
|
||||
### 完整的歌单管理流程
|
||||
|
||||
```typescript
|
||||
import songListAPI from '@/api/songList'
|
||||
|
||||
async function managePlaylist() {
|
||||
try {
|
||||
// 1. 创建歌单
|
||||
const createResult = await songListAPI.create('我的收藏', '我最喜欢的歌曲')
|
||||
if (!createResult.success) {
|
||||
throw new Error(createResult.error)
|
||||
}
|
||||
|
||||
const playlistId = createResult.data!.id
|
||||
|
||||
// 2. 添加歌曲
|
||||
const songs = [
|
||||
{
|
||||
songmid: 'song1',
|
||||
name: '歌曲1',
|
||||
singer: '歌手1',
|
||||
albumName: '专辑1',
|
||||
albumId: 'album1',
|
||||
duration: 240,
|
||||
source: 'local'
|
||||
}
|
||||
]
|
||||
|
||||
await songListAPI.addSongs(playlistId, songs)
|
||||
|
||||
// 3. 获取歌单详情
|
||||
const detail = await songListAPI.getPlaylistDetail(playlistId)
|
||||
console.log('歌单信息:', detail.playlist)
|
||||
console.log('歌曲列表:', detail.songs)
|
||||
|
||||
// 4. 搜索歌曲
|
||||
const searchResult = await songListAPI.searchSongs(playlistId, '歌曲')
|
||||
console.log('搜索结果:', searchResult.data)
|
||||
|
||||
// 5. 获取统计信息
|
||||
const stats = await songListAPI.getSongStatistics(playlistId)
|
||||
console.log('统计信息:', stats.data)
|
||||
|
||||
} catch (error) {
|
||||
console.error('操作失败:', error)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### React 组件中的使用
|
||||
|
||||
```typescript
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import songListAPI from '@/api/songList'
|
||||
import type { SongList } from '@common/types/songList'
|
||||
|
||||
const PlaylistManager: React.FC = () => {
|
||||
const [playlists, setPlaylists] = useState<SongList[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
// 加载歌单列表
|
||||
const loadPlaylists = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await songListAPI.getAll()
|
||||
if (result.success) {
|
||||
setPlaylists(result.data || [])
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载歌单失败:', error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新歌单
|
||||
const createPlaylist = async (name: string) => {
|
||||
const result = await songListAPI.create(name)
|
||||
if (result.success) {
|
||||
await loadPlaylists() // 重新加载列表
|
||||
}
|
||||
}
|
||||
|
||||
// 删除歌单
|
||||
const deletePlaylist = async (id: string) => {
|
||||
const result = await songListAPI.safeDelete(id, async () => {
|
||||
return confirm('确定要删除这个歌单吗?')
|
||||
})
|
||||
|
||||
if (result.success) {
|
||||
await loadPlaylists() // 重新加载列表
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadPlaylists()
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
{loading ? (
|
||||
<div>加载中...</div>
|
||||
) : (
|
||||
<div>
|
||||
{playlists.map(playlist => (
|
||||
<div key={playlist.id}>
|
||||
<h3>{playlist.name}</h3>
|
||||
<p>{playlist.description}</p>
|
||||
<button onClick={() => deletePlaylist(playlist.id)}>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## 性能优化建议
|
||||
|
||||
1. **批量操作**:使用 `batchDelete` 和 `removeSongs` 进行批量操作
|
||||
2. **数据缓存**:在前端适当缓存歌单列表,避免频繁请求
|
||||
3. **懒加载**:歌曲列表可以按需加载,不必一次性加载所有数据
|
||||
4. **错误恢复**:使用 `checkAndRepair` 定期检查数据完整性
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 所有 API 都是异步的,需要使用 `await` 或 `.then()`
|
||||
2. 歌单 ID (`hashId`) 是唯一标识符,不要与数组索引混淆
|
||||
3. 歌曲 ID (`songmid`) 可能是字符串或数字类型
|
||||
4. 删除操作是不可逆的,建议使用 `safeDelete` 方法
|
||||
5. 大量数据操作时注意性能影响
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.0.0 (2024-01-10)
|
||||
- ✨ 初始版本发布
|
||||
- ✨ 完整的歌单管理功能
|
||||
- ✨ 批量操作支持
|
||||
- ✨ 数据完整性检查
|
||||
- ✨ TypeScript 类型支持
|
||||
- ✨ 详细的使用文档和示例
|
||||
|
||||
---
|
||||
|
||||
如有问题或建议,请提交 Issue 或 Pull Request。
|
||||
147
docs/webdav-sync-setup.md
Normal file
147
docs/webdav-sync-setup.md
Normal file
@@ -0,0 +1,147 @@
|
||||
# WebDAV 同步配置指南
|
||||
|
||||
本项目包含两个 GitHub Actions 工作流,用于自动将 GitHub Releases 同步到 alist(WebDAV 服务器)。
|
||||
|
||||
## 工作流说明
|
||||
|
||||
### 1. 手动同步工作流 (`sync-releases-to-webdav.yml`)
|
||||
- **触发方式**: 手动触发 (workflow_dispatch)
|
||||
- **功能**: 同步现有的所有版本或指定版本到 WebDAV
|
||||
- **参数**:
|
||||
- `tag_name`: 可选,指定要同步的版本标签(如 v1.0.0),留空则同步所有版本
|
||||
|
||||
### 2. 自动同步工作流 (集成在 `main.yml` 中)
|
||||
- **触发方式**: 在 AutoBuild 完成后自动触发
|
||||
- **功能**: 自动将新构建的版本同步到 WebDAV
|
||||
- **参数**: 无需手动设置,自动获取发布信息
|
||||
|
||||
### 3. 独立自动同步工作流 (`auto-sync-release.yml`)
|
||||
- **触发方式**: 当新版本发布时自动触发 (on release published)
|
||||
- **功能**: 备用的自动同步机制
|
||||
- **参数**: 无需手动设置,自动获取发布信息
|
||||
|
||||
## 配置要求
|
||||
|
||||
在 GitHub 仓库的 Settings > Secrets and variables > Actions 中添加以下密钥:
|
||||
|
||||
### 必需的 Secrets
|
||||
|
||||
1. **WEBDAV_BASE_URL**
|
||||
- 描述: WebDAV 服务器的基础 URL
|
||||
- 示例: `https://your-alist-domain.com/dav`
|
||||
- 注意: 不要在末尾添加斜杠
|
||||
|
||||
2. **WEBDAV_USERNAME**
|
||||
- 描述: WebDAV 服务器的用户名
|
||||
- 示例: `admin`
|
||||
|
||||
3. **WEBDAV_PASSWORD**
|
||||
- 描述: WebDAV 服务器的密码
|
||||
- 示例: `your-password`
|
||||
|
||||
4. **GITHUB_TOKEN**
|
||||
- 描述: GitHub 访问令牌(通常自动提供)
|
||||
- 注意: 如果默认的 `GITHUB_TOKEN` 权限不足,可能需要创建个人访问令牌
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 手动同步现有版本
|
||||
|
||||
1. 进入 GitHub 仓库的 Actions 页面
|
||||
2. 选择 "Sync Existing Releases to WebDAV" 工作流
|
||||
3. 点击 "Run workflow"
|
||||
4. 可选择指定版本标签或留空同步所有版本
|
||||
5. 点击 "Run workflow" 开始执行
|
||||
|
||||
### 自动同步新版本
|
||||
|
||||
现在有两种自动同步方式:
|
||||
|
||||
1. **集成同步** (推荐): 在主构建工作流 (`main.yml`) 中集成了 WebDAV 同步,当您推送 `v*` 标签时,会自动执行:
|
||||
- 构建应用 → 创建 Release → 同步到 WebDAV
|
||||
|
||||
2. **独立同步**: 当您手动发布 Release 时,`auto-sync-release.yml` 工作流会自动触发
|
||||
|
||||
推荐使用集成同步方式,因为它确保了构建和同步的一致性。
|
||||
|
||||
## 文件结构
|
||||
|
||||
同步后的文件将按以下结构存储在 alist 中:
|
||||
|
||||
```
|
||||
/yd/ceru/
|
||||
├── v1.0.0/
|
||||
│ ├── app-setup.exe
|
||||
│ ├── app.dmg
|
||||
│ └── app.AppImage
|
||||
├── v1.1.0/
|
||||
│ ├── app-setup.exe
|
||||
│ ├── app.dmg
|
||||
│ └── app.AppImage
|
||||
└── ...
|
||||
```
|
||||
|
||||
## 故障排除
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. **上传失败**
|
||||
- 检查 WebDAV 服务器是否正常运行
|
||||
- 验证用户名和密码是否正确
|
||||
- 确认 WebDAV URL 格式正确
|
||||
|
||||
2. **权限错误**
|
||||
- 确保 WebDAV 用户有写入权限
|
||||
- 检查目标目录是否存在且可写
|
||||
|
||||
3. **文件大小不匹配**
|
||||
- 网络问题导致下载不完整
|
||||
- GitHub API 限制或临时故障
|
||||
|
||||
4. **目录创建失败**
|
||||
- WebDAV 服务器不支持 MKCOL 方法
|
||||
- 权限不足或路径错误
|
||||
|
||||
### 调试步骤
|
||||
|
||||
1. 查看 Actions 运行日志
|
||||
2. 检查 WebDAV 服务器日志
|
||||
3. 验证所有 Secrets 配置正确
|
||||
4. 测试 WebDAV 连接是否正常
|
||||
|
||||
## 安全注意事项
|
||||
|
||||
1. **密钥管理**
|
||||
- 不要在代码中硬编码密码
|
||||
- 定期更换 WebDAV 密码
|
||||
- 使用强密码
|
||||
|
||||
2. **权限控制**
|
||||
- 为 WebDAV 用户设置最小必要权限
|
||||
- 考虑使用专用的同步账户
|
||||
|
||||
3. **网络安全**
|
||||
- 建议使用 HTTPS 连接
|
||||
- 考虑 IP 白名单限制
|
||||
|
||||
## 自定义配置
|
||||
|
||||
如需修改同步路径或其他配置,请编辑对应的工作流文件:
|
||||
|
||||
- 修改存储路径: 更改 `remote_path` 变量
|
||||
- 调整重试逻辑: 修改错误处理部分
|
||||
- 添加通知: 集成 Slack、邮件等通知服务
|
||||
|
||||
## 支持的文件类型
|
||||
|
||||
工作流支持同步所有类型的 Release 资源文件,包括但不限于:
|
||||
- 可执行文件 (.exe, .dmg, .AppImage)
|
||||
- 压缩包 (.zip, .tar.gz, .7z)
|
||||
- 安装包 (.msi, .deb, .rpm)
|
||||
- 其他二进制文件
|
||||
|
||||
## 版本兼容性
|
||||
|
||||
- GitHub Actions: 支持最新版本
|
||||
- alist: 支持 WebDAV 协议的版本
|
||||
- 操作系统: Ubuntu Latest (工作流运行环境)
|
||||
@@ -19,6 +19,7 @@ win:
|
||||
- target: nsis
|
||||
arch:
|
||||
- x64
|
||||
- ia32
|
||||
# 简化版本信息设置,避免rcedit错误
|
||||
fileAssociations:
|
||||
- ext: cerumusic
|
||||
@@ -30,7 +31,7 @@ win:
|
||||
# 或者使用证书存储
|
||||
# certificateSubjectName: "Your Company Name"
|
||||
nsis:
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
artifactName: ${name}-${version}-${arch}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
createDesktopShortcut: always
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ceru-music",
|
||||
"version": "1.1.9",
|
||||
"version": "1.2.6",
|
||||
"description": "一款简洁优雅的音乐播放器",
|
||||
"main": "./out/main/index.js",
|
||||
"author": "sqj,wldss,star",
|
||||
@@ -18,7 +18,8 @@
|
||||
"onlybuild": "electron-vite build && electron-builder --win --x64",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"build:unpack": "yarn run build && electron-builder --dir",
|
||||
"build:win": "yarn run build && electron-builder --win --x64 --config --publish never",
|
||||
"build:win": "yarn run build && electron-builder --win --config --publish never",
|
||||
"build:win32": "yarn run build && electron-builder --win --ia32 --config --publish never",
|
||||
"build:mac": "yarn run build && electron-builder --mac --config --publish never",
|
||||
"build:linux": "yarn run build && electron-builder --linux --config --publish never",
|
||||
"build:deps": "electron-builder install-app-deps && yarn run build && electron-builder --win --x64 --config",
|
||||
|
||||
BIN
resources/default-cover.png
Normal file
BIN
resources/default-cover.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 824 KiB |
55
scripts/auth-test.js
Normal file
55
scripts/auth-test.js
Normal file
@@ -0,0 +1,55 @@
|
||||
const axios = require('axios');
|
||||
|
||||
const ALIST_BASE_URL = 'http://47.96.72.224:5244';
|
||||
const ALIST_USERNAME = 'ceruupdate';
|
||||
const ALIST_PASSWORD = '123456';
|
||||
|
||||
async function test() {
|
||||
// 认证
|
||||
const auth = await axios.post(`${ALIST_BASE_URL}/api/auth/login`, {
|
||||
username: ALIST_USERNAME,
|
||||
password: ALIST_PASSWORD
|
||||
});
|
||||
|
||||
const token = auth.data.data.token;
|
||||
console.log('Token received');
|
||||
|
||||
// 测试直接 token 格式
|
||||
try {
|
||||
const list = await axios.post(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
path: '/',
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 30,
|
||||
refresh: false
|
||||
}, {
|
||||
headers: { 'Authorization': token }
|
||||
});
|
||||
|
||||
console.log('Direct token works:', list.data.code === 200);
|
||||
if (list.data.code === 200) {
|
||||
console.log('Files:', list.data.data.content.map(f => f.name));
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('Direct token failed');
|
||||
}
|
||||
|
||||
// 测试 Bearer 格式
|
||||
try {
|
||||
const list2 = await axios.post(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
path: '/',
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 30,
|
||||
refresh: false
|
||||
}, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
console.log('Bearer format works:', list2.data.code === 200);
|
||||
} catch (e) {
|
||||
console.log('Bearer format failed');
|
||||
}
|
||||
}
|
||||
|
||||
test().catch(console.error);
|
||||
131
scripts/test-alist.js
Normal file
131
scripts/test-alist.js
Normal file
@@ -0,0 +1,131 @@
|
||||
const axios = require('axios');
|
||||
|
||||
// Alist API 配置
|
||||
const ALIST_BASE_URL = 'http://47.96.72.224:5244';
|
||||
const ALIST_USERNAME = 'ceruupdate';
|
||||
const ALIST_PASSWORD = '123456';
|
||||
|
||||
async function testAlistConnection() {
|
||||
console.log('Testing Alist connection...');
|
||||
|
||||
try {
|
||||
// 0. 首先测试服务器是否可访问
|
||||
console.log('0. Testing server accessibility...');
|
||||
const pingResponse = await axios.get(`${ALIST_BASE_URL}/ping`, {
|
||||
timeout: 5000
|
||||
});
|
||||
console.log('Server ping successful:', pingResponse.status);
|
||||
|
||||
// 1. 测试认证
|
||||
console.log('1. Testing authentication...');
|
||||
console.log(`Trying to authenticate with username: ${ALIST_USERNAME}`);
|
||||
|
||||
const authResponse = await axios.post(`${ALIST_BASE_URL}/api/auth/login`, {
|
||||
username: ALIST_USERNAME,
|
||||
password: ALIST_PASSWORD
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Auth response:', authResponse.data);
|
||||
|
||||
if (authResponse.data.code !== 200) {
|
||||
// 尝试获取公共访问权限
|
||||
console.log('Authentication failed, trying public access...');
|
||||
|
||||
// 尝试不使用认证直接访问文件列表
|
||||
const publicListResponse = await axios.post(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
path: '/',
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 30,
|
||||
refresh: false
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Public access response:', publicListResponse.data);
|
||||
|
||||
if (publicListResponse.data.code === 200) {
|
||||
console.log('✓ Public access successful');
|
||||
return; // 如果公共访问成功,就不需要认证
|
||||
}
|
||||
|
||||
throw new Error(`Authentication failed: ${authResponse.data.message}`);
|
||||
}
|
||||
|
||||
const token = authResponse.data.data.token;
|
||||
console.log('✓ Authentication successful');
|
||||
|
||||
// 2. 测试文件列表
|
||||
console.log('2. Testing file listing...');
|
||||
const listResponse = await axios.post(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
path: '/',
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 30,
|
||||
refresh: false
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('List response:', listResponse.data);
|
||||
|
||||
if (listResponse.data.code === 200) {
|
||||
console.log('✓ File listing successful');
|
||||
console.log('Available directories/files:');
|
||||
listResponse.data.data.content.forEach(item => {
|
||||
console.log(` - ${item.name} (${item.is_dir ? 'directory' : 'file'})`);
|
||||
});
|
||||
}
|
||||
|
||||
// 3. 测试获取特定文件信息(如果存在版本目录)
|
||||
console.log('3. Testing file info retrieval...');
|
||||
try {
|
||||
const fileInfoResponse = await axios.post(`${ALIST_BASE_URL}/api/fs/get`, {
|
||||
path: '/v1.0.0' // 测试版本目录
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('File info response:', fileInfoResponse.data);
|
||||
|
||||
if (fileInfoResponse.data.code === 200) {
|
||||
console.log('✓ File info retrieval successful');
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('ℹ Version directory /v1.0.0 not found (this is expected if no updates are available)');
|
||||
}
|
||||
|
||||
console.log('\n✅ Alist connection test completed successfully!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Alist connection test failed:', error.message);
|
||||
|
||||
if (error.response) {
|
||||
console.error('Response status:', error.response.status);
|
||||
console.error('Response data:', error.response.data);
|
||||
} else if (error.request) {
|
||||
console.error('No response received. Check if the Alist server is running and accessible.');
|
||||
}
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testAlistConnection();
|
||||
15
src/common/types/playList.ts
Normal file
15
src/common/types/playList.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export default interface PlayList {
|
||||
songmid: string|number
|
||||
hash?: string
|
||||
singer: string
|
||||
name: string
|
||||
albumName: string
|
||||
albumId: string|number
|
||||
source: string
|
||||
interval: string
|
||||
img: string
|
||||
lrc: null | string
|
||||
types: string[]
|
||||
_types: Record<string, any>
|
||||
typeUrl: Record<string, any>
|
||||
}
|
||||
12
src/common/types/songList.ts
Normal file
12
src/common/types/songList.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import PlayList from "./playList";
|
||||
export type Songs = PlayList;
|
||||
|
||||
export type SongList = {
|
||||
id: string //hashId 对应歌单文件名.json
|
||||
name: string; // 歌单名
|
||||
createTime: string;
|
||||
updateTime: string;
|
||||
description: string; // 歌单描述
|
||||
coverImgUrl: string; //歌单封面 默认第一首歌的图片
|
||||
source: 'local'|'wy'|'tx'|'mg'|'kg'|'kw'; // 来源
|
||||
};
|
||||
@@ -20,6 +20,101 @@ interface UpdateInfo {
|
||||
const UPDATE_SERVER = 'https://update.ceru.shiqianjiang.cn';
|
||||
const UPDATE_API_URL = `${UPDATE_SERVER}/update/${process.platform}/${app.getVersion()}`;
|
||||
|
||||
// Alist API 配置
|
||||
const ALIST_BASE_URL = 'https://alist.shiqianjiang.cn'; // 请替换为实际的 alist 域名
|
||||
const ALIST_USERNAME = 'ceruupdate';
|
||||
const ALIST_PASSWORD = '123456';
|
||||
|
||||
// Alist 认证 token
|
||||
let alistToken: string | null = null;
|
||||
|
||||
// 获取 Alist 认证 token
|
||||
async function getAlistToken(): Promise<string> {
|
||||
if (alistToken) {
|
||||
return alistToken;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('Authenticating with Alist...');
|
||||
const response = await axios.post(`${ALIST_BASE_URL}/api/auth/login`, {
|
||||
username: ALIST_USERNAME,
|
||||
password: ALIST_PASSWORD
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Alist auth response:', response.data);
|
||||
|
||||
if (response.data.code === 200) {
|
||||
alistToken = response.data.data.token;
|
||||
console.log('Alist authentication successful');
|
||||
return alistToken!; // 我们已经确认 token 存在
|
||||
} else {
|
||||
throw new Error(`Alist authentication failed: ${response.data.message || 'Unknown error'}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Alist authentication error:', error);
|
||||
if (error.response) {
|
||||
throw new Error(`Failed to authenticate with Alist: HTTP ${error.response.status} - ${error.response.data?.message || error.response.statusText}`);
|
||||
} else {
|
||||
throw new Error(`Failed to authenticate with Alist: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取 Alist 文件下载链接
|
||||
async function getAlistDownloadUrl(version: string, fileName: string): Promise<string> {
|
||||
const token = await getAlistToken();
|
||||
const filePath = `/${version}/${fileName}`;
|
||||
|
||||
try {
|
||||
console.log(`Getting file info for: ${filePath}`);
|
||||
const response = await axios.post(`${ALIST_BASE_URL}/api/fs/get`, {
|
||||
path: filePath
|
||||
}, {
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Alist file info response:', response.data);
|
||||
|
||||
if (response.data.code === 200) {
|
||||
const fileInfo = response.data.data;
|
||||
|
||||
// 检查文件是否存在且有下载链接
|
||||
if (fileInfo && fileInfo.raw_url) {
|
||||
console.log('Using raw_url for download:', fileInfo.raw_url);
|
||||
return fileInfo.raw_url;
|
||||
} else if (fileInfo && fileInfo.sign) {
|
||||
// 使用签名构建下载链接
|
||||
const downloadUrl = `${ALIST_BASE_URL}/d${filePath}?sign=${fileInfo.sign}`;
|
||||
console.log('Using signed download URL:', downloadUrl);
|
||||
return downloadUrl;
|
||||
} else {
|
||||
// 尝试直接下载链接(无签名)
|
||||
const directUrl = `${ALIST_BASE_URL}/d${filePath}`;
|
||||
console.log('Using direct download URL:', directUrl);
|
||||
return directUrl;
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Failed to get file info: ${response.data.message || 'Unknown error'}`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Alist file info error:', error);
|
||||
if (error.response) {
|
||||
throw new Error(`Failed to get download URL from Alist: HTTP ${error.response.status} - ${error.response.data?.message || error.response.statusText}`);
|
||||
} else {
|
||||
throw new Error(`Failed to get download URL from Alist: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化自动更新器
|
||||
export function initAutoUpdater(window: BrowserWindow) {
|
||||
mainWindow = window;
|
||||
@@ -128,8 +223,8 @@ export async function downloadUpdate() {
|
||||
}
|
||||
|
||||
// 下载文件
|
||||
async function downloadFile(url: string): Promise<string> {
|
||||
const fileName = path.basename(url);
|
||||
async function downloadFile(originalUrl: string): Promise<string> {
|
||||
const fileName = path.basename(originalUrl);
|
||||
const downloadPath = path.join(app.getPath('temp'), fileName);
|
||||
|
||||
// 进度节流变量
|
||||
@@ -139,9 +234,24 @@ async function downloadFile(url: string): Promise<string> {
|
||||
const PROGRESS_THRESHOLD = 1; // 进度变化超过1%才发送
|
||||
|
||||
try {
|
||||
let downloadUrl = originalUrl;
|
||||
|
||||
try {
|
||||
// 从当前更新信息中提取版本号
|
||||
const version = currentUpdateInfo?.name || app.getVersion();
|
||||
|
||||
// 尝试使用 alist API 获取下载链接
|
||||
downloadUrl = await getAlistDownloadUrl(version, fileName);
|
||||
console.log('Using Alist download URL:', downloadUrl);
|
||||
} catch (alistError) {
|
||||
console.warn('Alist download failed, falling back to original URL:', alistError);
|
||||
console.log('Using original download URL:', originalUrl);
|
||||
downloadUrl = originalUrl;
|
||||
}
|
||||
|
||||
const response = await axios({
|
||||
method: 'GET',
|
||||
url: url,
|
||||
url: downloadUrl,
|
||||
responseType: 'stream',
|
||||
timeout: 30000, // 30秒超时
|
||||
onDownloadProgress: (progressEvent) => {
|
||||
|
||||
300
src/main/events/songList.ts
Normal file
300
src/main/events/songList.ts
Normal file
@@ -0,0 +1,300 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import ManageSongList, { SongListError } from '../services/songList/ManageSongList'
|
||||
import type { SongList, Songs } from '@common/types/songList'
|
||||
|
||||
// 创建新歌单
|
||||
ipcMain.handle('songlist:create', async (_, name: string, description: string = '', source: SongList['source']) => {
|
||||
try {
|
||||
const result = ManageSongList.createPlaylist(name, description, source)
|
||||
return { success: true, data: result, message: '歌单创建成功' }
|
||||
} catch (error) {
|
||||
console.error('创建歌单失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '创建歌单失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 获取所有歌单
|
||||
ipcMain.handle('songlist:get-all', async () => {
|
||||
try {
|
||||
const songLists = ManageSongList.Read()
|
||||
return { success: true, data: songLists }
|
||||
} catch (error) {
|
||||
console.error('获取歌单列表失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '获取歌单列表失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 根据ID获取歌单信息
|
||||
ipcMain.handle('songlist:get-by-id', async (_, hashId: string) => {
|
||||
try {
|
||||
const songList = ManageSongList.getById(hashId)
|
||||
return { success: true, data: songList }
|
||||
} catch (error) {
|
||||
console.error('获取歌单信息失败:', error)
|
||||
return { success: false, error: '获取歌单信息失败' }
|
||||
}
|
||||
})
|
||||
|
||||
// 删除歌单
|
||||
ipcMain.handle('songlist:delete', async (_, hashId: string) => {
|
||||
try {
|
||||
ManageSongList.deleteById(hashId)
|
||||
return { success: true, message: '歌单删除成功' }
|
||||
} catch (error) {
|
||||
console.error('删除歌单失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '删除歌单失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 批量删除歌单
|
||||
ipcMain.handle('songlist:batch-delete', async (_, hashIds: string[]) => {
|
||||
try {
|
||||
const result = ManageSongList.batchDelete(hashIds)
|
||||
return {
|
||||
success: true,
|
||||
data: result,
|
||||
message: `成功删除 ${result.success.length} 个歌单,失败 ${result.failed.length} 个`
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量删除歌单失败:', error)
|
||||
return { success: false, error: '批量删除歌单失败' }
|
||||
}
|
||||
})
|
||||
|
||||
// 编辑歌单信息
|
||||
ipcMain.handle('songlist:edit', async (_, hashId: string, updates: Partial<Omit<SongList, 'id' | 'createTime'>>) => {
|
||||
try {
|
||||
ManageSongList.editById(hashId, updates)
|
||||
return { success: true, message: '歌单信息更新成功' }
|
||||
} catch (error) {
|
||||
console.error('编辑歌单失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '编辑歌单失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 更新歌单封面
|
||||
ipcMain.handle('songlist:update-cover', async (_, hashId: string, coverImgUrl: string) => {
|
||||
try {
|
||||
ManageSongList.updateCoverImgById(hashId, coverImgUrl)
|
||||
return { success: true, message: '封面更新成功' }
|
||||
} catch (error) {
|
||||
console.error('更新封面失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '更新封面失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 搜索歌单
|
||||
ipcMain.handle('songlist:search', async (_, keyword: string, source?: SongList['source']) => {
|
||||
try {
|
||||
const results = ManageSongList.search(keyword, source)
|
||||
return { success: true, data: results }
|
||||
} catch (error) {
|
||||
console.error('搜索歌单失败:', error)
|
||||
return { success: false, error: '搜索歌单失败', data: [] }
|
||||
}
|
||||
})
|
||||
|
||||
// 获取歌单统计信息
|
||||
ipcMain.handle('songlist:get-statistics', async () => {
|
||||
try {
|
||||
const statistics = ManageSongList.getStatistics()
|
||||
return { success: true, data: statistics }
|
||||
} catch (error) {
|
||||
console.error('获取统计信息失败:', error)
|
||||
return { success: false, error: '获取统计信息失败' }
|
||||
}
|
||||
})
|
||||
|
||||
// 检查歌单是否存在
|
||||
ipcMain.handle('songlist:exists', async (_, hashId: string) => {
|
||||
try {
|
||||
const exists = ManageSongList.exists(hashId)
|
||||
return { success: true, data: exists }
|
||||
} catch (error) {
|
||||
console.error('检查歌单存在性失败:', error)
|
||||
return { success: false, error: '检查歌单存在性失败', data: false }
|
||||
}
|
||||
})
|
||||
|
||||
// === 歌曲管理相关 IPC 事件 ===
|
||||
|
||||
// 添加歌曲到歌单
|
||||
ipcMain.handle('songlist:add-songs', async (_, hashId: string, songs: Songs[]) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
instance.addSongs(songs)
|
||||
return { success: true, message: `成功添加 ${songs.length} 首歌曲` }
|
||||
} catch (error) {
|
||||
console.error('添加歌曲失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '添加歌曲失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 从歌单移除歌曲
|
||||
ipcMain.handle('songlist:remove-song', async (_, hashId: string, songmid: string | number) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const removed = instance.removeSong(songmid)
|
||||
return {
|
||||
success: true,
|
||||
data: removed,
|
||||
message: removed ? '歌曲移除成功' : '歌曲不存在'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('移除歌曲失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '移除歌曲失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 批量移除歌曲
|
||||
ipcMain.handle('songlist:remove-songs', async (_, hashId: string, songmids: (string | number)[]) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const result = instance.removeSongs(songmids)
|
||||
return {
|
||||
success: true,
|
||||
data: result,
|
||||
message: `成功移除 ${result.removed} 首歌曲,${result.notFound} 首未找到`
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量移除歌曲失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '批量移除歌曲失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 清空歌单
|
||||
ipcMain.handle('songlist:clear-songs', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
instance.clearSongs()
|
||||
return { success: true, message: '歌单已清空' }
|
||||
} catch (error) {
|
||||
console.error('清空歌单失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '清空歌单失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 获取歌单中的歌曲列表
|
||||
ipcMain.handle('songlist:get-songs', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const songs = instance.getSongs()
|
||||
return { success: true, data: songs }
|
||||
} catch (error) {
|
||||
console.error('获取歌曲列表失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '获取歌曲列表失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 获取歌单歌曲数量
|
||||
ipcMain.handle('songlist:get-song-count', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const count = instance.getCount()
|
||||
return { success: true, data: count }
|
||||
} catch (error) {
|
||||
console.error('获取歌曲数量失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '获取歌曲数量失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 检查歌曲是否在歌单中
|
||||
ipcMain.handle('songlist:has-song', async (_, hashId: string, songmid: string | number) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const hasSong = instance.hasSong(songmid)
|
||||
return { success: true, data: hasSong }
|
||||
} catch (error) {
|
||||
console.error('检查歌曲存在性失败:', error)
|
||||
return { success: false, error: '检查歌曲存在性失败', data: false }
|
||||
}
|
||||
})
|
||||
|
||||
// 根据ID获取歌曲
|
||||
ipcMain.handle('songlist:get-song', async (_, hashId: string, songmid: string | number) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const song = instance.getSong(songmid)
|
||||
return { success: true, data: song }
|
||||
} catch (error) {
|
||||
console.error('获取歌曲失败:', error)
|
||||
return { success: false, error: '获取歌曲失败', data: null }
|
||||
}
|
||||
})
|
||||
|
||||
// 搜索歌单中的歌曲
|
||||
ipcMain.handle('songlist:search-songs', async (_, hashId: string, keyword: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const results = instance.searchSongs(keyword)
|
||||
return { success: true, data: results }
|
||||
} catch (error) {
|
||||
console.error('搜索歌曲失败:', error)
|
||||
return { success: false, error: '搜索歌曲失败', data: [] }
|
||||
}
|
||||
})
|
||||
|
||||
// 获取歌单歌曲统计信息
|
||||
ipcMain.handle('songlist:get-song-statistics', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const statistics = instance.getStatistics()
|
||||
return { success: true, data: statistics }
|
||||
} catch (error) {
|
||||
console.error('获取歌曲统计信息失败:', error)
|
||||
return { success: false, error: '获取歌曲统计信息失败' }
|
||||
}
|
||||
})
|
||||
|
||||
// 验证歌单完整性
|
||||
ipcMain.handle('songlist:validate-integrity', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const result = instance.validateIntegrity()
|
||||
return { success: true, data: result }
|
||||
} catch (error) {
|
||||
console.error('验证歌单完整性失败:', error)
|
||||
return { success: false, error: '验证歌单完整性失败' }
|
||||
}
|
||||
})
|
||||
|
||||
// 修复歌单数据
|
||||
ipcMain.handle('songlist:repair-data', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
const result = instance.repairData()
|
||||
return {
|
||||
success: true,
|
||||
data: result,
|
||||
message: result.fixed ? `数据修复完成: ${result.changes.join(', ')}` : '数据无需修复'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('修复歌单数据失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '修复歌单数据失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
|
||||
// 强制保存歌单
|
||||
ipcMain.handle('songlist:force-save', async (_, hashId: string) => {
|
||||
try {
|
||||
const instance = new ManageSongList(hashId)
|
||||
instance.forceSave()
|
||||
return { success: true, message: '歌单保存成功' }
|
||||
} catch (error) {
|
||||
console.error('强制保存歌单失败:', error)
|
||||
const message = error instanceof SongListError ? error.message : '强制保存歌单失败'
|
||||
return { success: false, error: message, code: error instanceof SongListError ? error.code : 'UNKNOWN_ERROR' }
|
||||
}
|
||||
})
|
||||
@@ -8,6 +8,24 @@ import pluginService from './services/plugin'
|
||||
import aiEvents from './events/ai'
|
||||
import './services/musicSdk/index'
|
||||
|
||||
// 获取单实例锁
|
||||
const gotTheLock = app.requestSingleInstanceLock()
|
||||
|
||||
if (!gotTheLock) {
|
||||
// 如果没有获得锁,说明已经有实例在运行,退出当前实例
|
||||
app.quit()
|
||||
} else {
|
||||
// 当第二个实例尝试启动时,聚焦到第一个实例的窗口
|
||||
app.on('second-instance', () => {
|
||||
// 如果有窗口存在,聚焦到该窗口
|
||||
if (mainWindow) {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
if (!mainWindow.isVisible()) mainWindow.show()
|
||||
mainWindow.focus()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// import wy from './utils/musicSdk/wy/index'
|
||||
// import kg from './utils/musicSdk/kg/index'
|
||||
// wy.hotSearch.getList().then((res) => {
|
||||
@@ -40,6 +58,7 @@ function createTray(): void {
|
||||
label: '播放/暂停',
|
||||
click: () => {
|
||||
// 这里可以添加播放控制逻辑
|
||||
console.log('music-control')
|
||||
mainWindow?.webContents.send('music-control')
|
||||
}
|
||||
},
|
||||
@@ -75,7 +94,7 @@ function createWindow(): void {
|
||||
mainWindow = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 750,
|
||||
minWidth: 970,
|
||||
minWidth: 1100,
|
||||
minHeight: 670,
|
||||
show: false,
|
||||
center: true,
|
||||
@@ -199,6 +218,7 @@ ipcMain.handle('get-app-version', () => {
|
||||
|
||||
aiEvents(mainWindow)
|
||||
import './events/musicCache'
|
||||
import './events/songList'
|
||||
import { registerAutoUpdateEvents, initAutoUpdateForWindow } from './events/autoUpdate'
|
||||
|
||||
// This method will be called when Electron has finished
|
||||
|
||||
@@ -161,6 +161,26 @@ function main(source: string) {
|
||||
message: '下载成功',
|
||||
path: songPath
|
||||
}
|
||||
},
|
||||
|
||||
async parsePlaylistId({url}: {url: string}) {
|
||||
try {
|
||||
return await Api.songList.handleParseId(url)
|
||||
} catch (e: any) {
|
||||
return {
|
||||
error: '解析歌单链接失败 ' + (e.error || e.message || e)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async getPlaylistDetailById(id: string, page: number = 1) {
|
||||
try {
|
||||
return await Api.songList.getListDetail(id, page)
|
||||
} catch (e: any) {
|
||||
return {
|
||||
error: '获取歌单详情失败 ' + (e.error || e.message || e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
730
src/main/services/songList/ManageSongList.ts
Normal file
730
src/main/services/songList/ManageSongList.ts
Normal file
@@ -0,0 +1,730 @@
|
||||
import type { SongList, Songs } from "@common/types/songList";
|
||||
import PlayListSongs from "./PlayListSongs";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import crypto from "crypto";
|
||||
import { getAppDirPath } from "../../utils/path";
|
||||
|
||||
// 常量定义
|
||||
const DEFAULT_COVER_IDENTIFIER = 'default-cover';
|
||||
const SONGLIST_DIR = 'songList';
|
||||
const INDEX_FILE = 'index.json';
|
||||
|
||||
// 错误类型定义
|
||||
class SongListError extends Error {
|
||||
constructor(message: string, public code?: string) {
|
||||
super(message);
|
||||
this.name = 'SongListError';
|
||||
}
|
||||
}
|
||||
|
||||
// 工具函数类
|
||||
class SongListUtils {
|
||||
/**
|
||||
* 获取默认封面标识符
|
||||
*/
|
||||
static getDefaultCoverUrl(): string {
|
||||
return DEFAULT_COVER_IDENTIFIER;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单管理入口文件路径
|
||||
*/
|
||||
static getSongListIndexPath(): string {
|
||||
return path.join(getAppDirPath('userData'), SONGLIST_DIR, INDEX_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单文件路径
|
||||
*/
|
||||
static getSongListFilePath(hashId: string): string {
|
||||
return path.join(getAppDirPath('userData'), SONGLIST_DIR, `${hashId}.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保目录存在
|
||||
*/
|
||||
static ensureDirectoryExists(dirPath: string): void {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成唯一hashId
|
||||
*/
|
||||
static generateUniqueId(name: string): string {
|
||||
return crypto.createHash('md5')
|
||||
.update(`${name}_${Date.now()}_${Math.random()}`)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证歌曲封面URL是否有效
|
||||
*/
|
||||
static isValidCoverUrl(url: string | undefined | null): boolean {
|
||||
return Boolean(url && url.trim() !== '' && url !== DEFAULT_COVER_IDENTIFIER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证hashId格式
|
||||
*/
|
||||
static isValidHashId(hashId: string): boolean {
|
||||
return Boolean(hashId && typeof hashId === 'string' && hashId.trim().length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的JSON解析
|
||||
*/
|
||||
static safeJsonParse<T>(content: string, defaultValue: T): T {
|
||||
try {
|
||||
return JSON.parse(content) as T;
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default class ManageSongList extends PlayListSongs {
|
||||
private readonly hashId: string;
|
||||
|
||||
constructor(hashId: string) {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
throw new SongListError('无效的歌单ID', 'INVALID_HASH_ID');
|
||||
}
|
||||
|
||||
super(hashId);
|
||||
this.hashId = hashId.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态方法:创建新歌单
|
||||
* @param name 歌单名称
|
||||
* @param description 歌单描述
|
||||
* @param source 歌单来源
|
||||
* @returns 包含hashId的对象 (id字段就是hashId)
|
||||
*/
|
||||
static createPlaylist(
|
||||
name: string,
|
||||
description: string = '',
|
||||
source: SongList['source']
|
||||
): { id: string } {
|
||||
// 参数验证
|
||||
if (!name?.trim()) {
|
||||
throw new SongListError('歌单名称不能为空', 'EMPTY_NAME');
|
||||
}
|
||||
|
||||
if (!source) {
|
||||
throw new SongListError('歌单来源不能为空', 'EMPTY_SOURCE');
|
||||
}
|
||||
|
||||
try {
|
||||
const id = SongListUtils.generateUniqueId(name);
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const songListInfo: SongList = {
|
||||
id,
|
||||
name: name.trim(),
|
||||
createTime: now,
|
||||
updateTime: now,
|
||||
description: description?.trim() || '',
|
||||
coverImgUrl: SongListUtils.getDefaultCoverUrl(),
|
||||
source
|
||||
};
|
||||
|
||||
// 创建歌单文件
|
||||
ManageSongList.createSongListFile(id);
|
||||
|
||||
// 更新入口文件
|
||||
ManageSongList.updateIndexFile(songListInfo, 'add');
|
||||
|
||||
// 验证歌单可以正常实例化
|
||||
try {
|
||||
new ManageSongList(id);
|
||||
// 如果能成功创建实例,说明文件创建成功
|
||||
} catch (verifyError) {
|
||||
console.error('歌单创建验证失败:', verifyError);
|
||||
// 清理已创建的文件
|
||||
try {
|
||||
const filePath = SongListUtils.getSongListFilePath(id);
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
console.error('清理失败的歌单文件时出错:', cleanupError);
|
||||
}
|
||||
throw new SongListError('歌单创建后验证失败', 'CREATION_VERIFICATION_FAILED');
|
||||
}
|
||||
|
||||
return { id };
|
||||
} catch (error) {
|
||||
console.error('创建歌单失败:', error);
|
||||
if (error instanceof SongListError) {
|
||||
throw error;
|
||||
}
|
||||
throw new SongListError(`创建歌单失败: ${error instanceof Error ? error.message : '未知错误'}`, 'CREATE_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建歌单文件
|
||||
* @param hashId 歌单hashId
|
||||
*/
|
||||
private static createSongListFile(hashId: string): void {
|
||||
const songListFilePath = SongListUtils.getSongListFilePath(hashId);
|
||||
const dir = path.dirname(songListFilePath);
|
||||
|
||||
SongListUtils.ensureDirectoryExists(dir);
|
||||
|
||||
try {
|
||||
// 使用原子性写入确保文件完整性
|
||||
const tempPath = `${songListFilePath}.tmp`;
|
||||
const content = JSON.stringify([], null, 2);
|
||||
|
||||
fs.writeFileSync(tempPath, content);
|
||||
fs.renameSync(tempPath, songListFilePath);
|
||||
|
||||
// 确保文件确实存在且可读
|
||||
if (!fs.existsSync(songListFilePath)) {
|
||||
throw new Error('文件创建后验证失败');
|
||||
}
|
||||
|
||||
// 验证文件内容
|
||||
const verifyContent = fs.readFileSync(songListFilePath, 'utf-8');
|
||||
JSON.parse(verifyContent); // 确保内容是有效的JSON
|
||||
|
||||
} catch (error) {
|
||||
throw new SongListError(`创建歌单文件失败: ${error instanceof Error ? error.message : '未知错误'}`, 'FILE_CREATE_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除当前歌单
|
||||
*/
|
||||
delete(): void {
|
||||
const hashId = this.getHashId();
|
||||
|
||||
try {
|
||||
// 检查歌单是否存在
|
||||
if (!ManageSongList.exists(hashId)) {
|
||||
throw new SongListError('歌单不存在', 'PLAYLIST_NOT_FOUND');
|
||||
}
|
||||
|
||||
// 删除歌单文件
|
||||
const filePath = SongListUtils.getSongListFilePath(hashId);
|
||||
if (fs.existsSync(filePath)) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
|
||||
// 从入口文件中移除
|
||||
ManageSongList.updateIndexFile({ id: hashId } as SongList, 'remove');
|
||||
} catch (error) {
|
||||
console.error('删除歌单失败:', error);
|
||||
if (error instanceof SongListError) {
|
||||
throw error;
|
||||
}
|
||||
throw new SongListError(`删除歌单失败: ${error instanceof Error ? error.message : '未知错误'}`, 'DELETE_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改当前歌单信息
|
||||
* @param updates 要更新的字段
|
||||
*/
|
||||
edit(updates: Partial<Omit<SongList, 'id' | 'createTime'>>): void {
|
||||
if (!updates || Object.keys(updates).length === 0) {
|
||||
throw new SongListError('更新内容不能为空', 'EMPTY_UPDATES');
|
||||
}
|
||||
|
||||
const hashId = this.getHashId();
|
||||
|
||||
try {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
const index = songLists.findIndex(item => item.id === hashId);
|
||||
|
||||
if (index === -1) {
|
||||
throw new SongListError('歌单不存在', 'PLAYLIST_NOT_FOUND');
|
||||
}
|
||||
|
||||
// 验证和清理更新数据
|
||||
const cleanUpdates = ManageSongList.validateAndCleanUpdates(updates);
|
||||
|
||||
// 更新歌单信息
|
||||
songLists[index] = {
|
||||
...songLists[index],
|
||||
...cleanUpdates,
|
||||
updateTime: new Date().toISOString()
|
||||
};
|
||||
|
||||
// 保存到入口文件
|
||||
ManageSongList.writeIndexFile(songLists);
|
||||
} catch (error) {
|
||||
console.error('修改歌单失败:', error);
|
||||
if (error instanceof SongListError) {
|
||||
throw error;
|
||||
}
|
||||
throw new SongListError(`修改歌单失败: ${error instanceof Error ? error.message : '未知错误'}`, 'EDIT_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前歌单的hashId
|
||||
* @returns hashId
|
||||
*/
|
||||
private getHashId(): string {
|
||||
return this.hashId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证和清理更新数据
|
||||
* @param updates 原始更新数据
|
||||
* @returns 清理后的更新数据
|
||||
*/
|
||||
private static validateAndCleanUpdates(
|
||||
updates: Partial<Omit<SongList, 'id' | 'createTime'>>
|
||||
): Partial<Omit<SongList, 'id' | 'createTime'>> {
|
||||
const cleanUpdates: Partial<Omit<SongList, 'id' | 'createTime'>> = {};
|
||||
|
||||
// 验证歌单名称
|
||||
if (updates.name !== undefined) {
|
||||
const trimmedName = updates.name.trim();
|
||||
if (!trimmedName) {
|
||||
throw new SongListError('歌单名称不能为空', 'EMPTY_NAME');
|
||||
}
|
||||
cleanUpdates.name = trimmedName;
|
||||
}
|
||||
|
||||
// 处理描述
|
||||
if (updates.description !== undefined) {
|
||||
cleanUpdates.description = updates.description?.trim() || '';
|
||||
}
|
||||
|
||||
// 处理封面URL
|
||||
if (updates.coverImgUrl !== undefined) {
|
||||
cleanUpdates.coverImgUrl = updates.coverImgUrl || SongListUtils.getDefaultCoverUrl();
|
||||
}
|
||||
|
||||
// 处理来源
|
||||
if (updates.source !== undefined) {
|
||||
if (!updates.source) {
|
||||
throw new SongListError('歌单来源不能为空', 'EMPTY_SOURCE');
|
||||
}
|
||||
cleanUpdates.source = updates.source;
|
||||
}
|
||||
|
||||
return cleanUpdates;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取歌单列表
|
||||
* @returns 歌单列表数组
|
||||
*/
|
||||
static Read(): SongList[] {
|
||||
try {
|
||||
return ManageSongList.readIndexFile();
|
||||
} catch (error) {
|
||||
console.error('读取歌单列表失败:', error);
|
||||
if (error instanceof SongListError) {
|
||||
throw error;
|
||||
}
|
||||
throw new SongListError(`读取歌单列表失败: ${error instanceof Error ? error.message : '未知错误'}`, 'READ_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据hashId获取单个歌单信息
|
||||
* @param hashId 歌单hashId
|
||||
* @returns 歌单信息或null
|
||||
*/
|
||||
static getById(hashId: string): SongList | null {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
return songLists.find(item => item.id === hashId) || null;
|
||||
} catch (error) {
|
||||
console.error('获取歌单信息失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取入口文件
|
||||
* @returns 歌单列表数组
|
||||
*/
|
||||
private static readIndexFile(): SongList[] {
|
||||
const indexPath = SongListUtils.getSongListIndexPath();
|
||||
|
||||
if (!fs.existsSync(indexPath)) {
|
||||
ManageSongList.initializeIndexFile();
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(indexPath, 'utf-8');
|
||||
const parsed = SongListUtils.safeJsonParse<unknown>(content, []);
|
||||
|
||||
// 验证数据格式
|
||||
if (!Array.isArray(parsed)) {
|
||||
console.warn('入口文件格式错误,重新初始化');
|
||||
ManageSongList.initializeIndexFile();
|
||||
return [];
|
||||
}
|
||||
|
||||
return parsed as SongList[];
|
||||
} catch (error) {
|
||||
console.error('解析入口文件失败:', error);
|
||||
// 备份损坏的文件并重新初始化
|
||||
ManageSongList.backupCorruptedFile(indexPath);
|
||||
ManageSongList.initializeIndexFile();
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 备份损坏的文件
|
||||
* @param filePath 文件路径
|
||||
*/
|
||||
private static backupCorruptedFile(filePath: string): void {
|
||||
try {
|
||||
const backupPath = `${filePath}.backup.${Date.now()}`;
|
||||
fs.copyFileSync(filePath, backupPath);
|
||||
console.log(`已备份损坏的文件到: ${backupPath}`);
|
||||
} catch (error) {
|
||||
console.error('备份损坏文件失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化入口文件
|
||||
*/
|
||||
private static initializeIndexFile(): void {
|
||||
const indexPath = SongListUtils.getSongListIndexPath();
|
||||
const dir = path.dirname(indexPath);
|
||||
|
||||
SongListUtils.ensureDirectoryExists(dir);
|
||||
|
||||
try {
|
||||
fs.writeFileSync(indexPath, JSON.stringify([], null, 2));
|
||||
} catch (error) {
|
||||
throw new SongListError(`初始化入口文件失败: ${error instanceof Error ? error.message : '未知错误'}`, 'INIT_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入入口文件
|
||||
* @param songLists 歌单列表
|
||||
*/
|
||||
private static writeIndexFile(songLists: SongList[]): void {
|
||||
if (!Array.isArray(songLists)) {
|
||||
throw new SongListError('歌单列表必须是数组格式', 'INVALID_DATA_FORMAT');
|
||||
}
|
||||
|
||||
const indexPath = SongListUtils.getSongListIndexPath();
|
||||
const dir = path.dirname(indexPath);
|
||||
|
||||
SongListUtils.ensureDirectoryExists(dir);
|
||||
|
||||
try {
|
||||
// 先写入临时文件,再重命名,确保原子性操作
|
||||
const tempPath = `${indexPath}.tmp`;
|
||||
fs.writeFileSync(tempPath, JSON.stringify(songLists, null, 2));
|
||||
fs.renameSync(tempPath, indexPath);
|
||||
} catch (error) {
|
||||
console.error('写入入口文件失败:', error);
|
||||
throw new SongListError(`写入入口文件失败: ${error instanceof Error ? error.message : '未知错误'}`, 'WRITE_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新入口文件
|
||||
* @param songListInfo 歌单信息
|
||||
* @param action 操作类型
|
||||
*/
|
||||
private static updateIndexFile(
|
||||
songListInfo: SongList,
|
||||
action: 'add' | 'remove'
|
||||
): void {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
|
||||
switch (action) {
|
||||
case 'add':
|
||||
// 检查是否已存在,避免重复添加
|
||||
if (!songLists.some(item => item.id === songListInfo.id)) {
|
||||
songLists.push(songListInfo);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'remove':
|
||||
const index = songLists.findIndex(item => item.id === songListInfo.id);
|
||||
if (index !== -1) {
|
||||
songLists.splice(index, 1);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new SongListError(`不支持的操作类型: ${action}`, 'INVALID_ACTION');
|
||||
}
|
||||
|
||||
ManageSongList.writeIndexFile(songLists);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新当前歌单封面图片URL
|
||||
* @param coverImgUrl 封面图片URL
|
||||
*/
|
||||
updateCoverImg(coverImgUrl: string): void {
|
||||
try {
|
||||
const finalCoverUrl = coverImgUrl || SongListUtils.getDefaultCoverUrl();
|
||||
this.edit({ coverImgUrl: finalCoverUrl });
|
||||
} catch (error) {
|
||||
console.error('更新封面失败:', error);
|
||||
if (error instanceof SongListError) {
|
||||
throw error;
|
||||
}
|
||||
throw new SongListError(`更新封面失败: ${error instanceof Error ? error.message : '未知错误'}`, 'UPDATE_COVER_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重写父类的addSongs方法,添加自动设置封面功能
|
||||
* @param songs 要添加的歌曲列表
|
||||
*/
|
||||
addSongs(songs: Songs[]): void {
|
||||
if (!Array.isArray(songs) || songs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用父类方法添加歌曲
|
||||
super.addSongs(songs);
|
||||
|
||||
// 异步更新封面,不阻塞主要功能
|
||||
setImmediate(() => {
|
||||
this.updateCoverIfNeeded(songs);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并更新封面图片
|
||||
* @param newSongs 新添加的歌曲列表
|
||||
*/
|
||||
private updateCoverIfNeeded(newSongs: Songs[]): void {
|
||||
try {
|
||||
const currentPlaylist = ManageSongList.getById(this.hashId);
|
||||
|
||||
if (!currentPlaylist) {
|
||||
console.warn(`歌单 ${this.hashId} 不存在,跳过封面更新`);
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldUpdateCover = this.shouldUpdateCover(currentPlaylist.coverImgUrl);
|
||||
|
||||
if (shouldUpdateCover) {
|
||||
const validCoverUrl = this.findValidCoverFromSongs(newSongs);
|
||||
|
||||
if (validCoverUrl) {
|
||||
this.updateCoverImg(validCoverUrl);
|
||||
} else if (!currentPlaylist.coverImgUrl || currentPlaylist.coverImgUrl === SongListUtils.getDefaultCoverUrl()) {
|
||||
// 如果没有找到有效封面且当前也没有封面,设置默认封面
|
||||
this.updateCoverImg(SongListUtils.getDefaultCoverUrl());
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新封面失败:', error);
|
||||
// 不抛出错误,避免影响添加歌曲的主要功能
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否应该更新封面
|
||||
* @param currentCoverUrl 当前封面URL
|
||||
* @returns 是否应该更新
|
||||
*/
|
||||
private shouldUpdateCover(currentCoverUrl: string): boolean {
|
||||
return !currentCoverUrl || currentCoverUrl === SongListUtils.getDefaultCoverUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从歌曲列表中查找有效的封面图片
|
||||
* @param songs 歌曲列表
|
||||
* @returns 有效的封面URL或null
|
||||
*/
|
||||
private findValidCoverFromSongs(songs: Songs[]): string | null {
|
||||
// 优先检查新添加的歌曲
|
||||
for (const song of songs) {
|
||||
if (SongListUtils.isValidCoverUrl(song.img)) {
|
||||
return song.img;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果新添加的歌曲都没有封面,检查当前歌单中的所有歌曲
|
||||
try {
|
||||
for (const song of this.list) {
|
||||
if (SongListUtils.isValidCoverUrl(song.img)) {
|
||||
return song.img;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取歌单歌曲列表失败:', error);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查歌单是否存在
|
||||
* @param hashId 歌单hashId
|
||||
* @returns 是否存在
|
||||
*/
|
||||
static exists(hashId: string): boolean {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
return songLists.some(item => item.id === hashId);
|
||||
} catch (error) {
|
||||
console.error('检查歌单存在性失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单统计信息
|
||||
* @returns 统计信息
|
||||
*/
|
||||
static getStatistics(): { total: number; bySource: Record<string, number>; lastUpdated: string } {
|
||||
try {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
const bySource: Record<string, number> = {};
|
||||
|
||||
songLists.forEach(playlist => {
|
||||
const source = playlist.source || 'unknown';
|
||||
bySource[source] = (bySource[source] || 0) + 1;
|
||||
});
|
||||
|
||||
return {
|
||||
total: songLists.length,
|
||||
bySource,
|
||||
lastUpdated: new Date().toISOString()
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取统计信息失败:', error);
|
||||
return {
|
||||
total: 0,
|
||||
bySource: {},
|
||||
lastUpdated: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前歌单信息
|
||||
* @returns 歌单信息或null
|
||||
*/
|
||||
getPlaylistInfo(): SongList | null {
|
||||
return ManageSongList.getById(this.hashId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量操作:删除多个歌单
|
||||
* @param hashIds 歌单ID数组
|
||||
* @returns 操作结果
|
||||
*/
|
||||
static batchDelete(hashIds: string[]): { success: string[]; failed: string[] } {
|
||||
const result = { success: [] as string[], failed: [] as string[] };
|
||||
|
||||
for (const hashId of hashIds) {
|
||||
try {
|
||||
ManageSongList.deleteById(hashId);
|
||||
result.success.push(hashId);
|
||||
} catch (error) {
|
||||
console.error(`删除歌单 ${hashId} 失败:`, error);
|
||||
result.failed.push(hashId);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索歌单
|
||||
* @param keyword 搜索关键词
|
||||
* @param source 可选的来源筛选
|
||||
* @returns 匹配的歌单列表
|
||||
*/
|
||||
static search(keyword: string, source?: SongList['source']): SongList[] {
|
||||
if (!keyword?.trim()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const songLists = ManageSongList.readIndexFile();
|
||||
const lowerKeyword = keyword.toLowerCase();
|
||||
|
||||
return songLists.filter(playlist => {
|
||||
const matchesKeyword = playlist.name.toLowerCase().includes(lowerKeyword) ||
|
||||
playlist.description.toLowerCase().includes(lowerKeyword);
|
||||
const matchesSource = !source || playlist.source === source;
|
||||
|
||||
return matchesKeyword && matchesSource;
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('搜索歌单失败:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// 静态方法别名,用于删除和编辑指定hashId的歌单
|
||||
/**
|
||||
* 静态方法:删除指定歌单
|
||||
* @param hashId 歌单hashId
|
||||
*/
|
||||
static deleteById(hashId: string): void {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
throw new SongListError('无效的歌单ID', 'INVALID_HASH_ID');
|
||||
}
|
||||
|
||||
const instance = new ManageSongList(hashId);
|
||||
instance.delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态方法:编辑指定歌单
|
||||
* @param hashId 歌单hashId
|
||||
* @param updates 要更新的字段
|
||||
*/
|
||||
static editById(hashId: string, updates: Partial<Omit<SongList, 'id' | 'createTime'>>): void {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
throw new SongListError('无效的歌单ID', 'INVALID_HASH_ID');
|
||||
}
|
||||
|
||||
const instance = new ManageSongList(hashId);
|
||||
instance.edit(updates);
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态方法:更新指定歌单封面
|
||||
* @param hashId 歌单hashId
|
||||
* @param coverImgUrl 封面图片URL
|
||||
*/
|
||||
static updateCoverImgById(hashId: string, coverImgUrl: string): void {
|
||||
if (!SongListUtils.isValidHashId(hashId)) {
|
||||
throw new SongListError('无效的歌单ID', 'INVALID_HASH_ID');
|
||||
}
|
||||
|
||||
const instance = new ManageSongList(hashId);
|
||||
instance.updateCoverImg(coverImgUrl);
|
||||
}
|
||||
|
||||
// 保持向后兼容的别名方法
|
||||
static Delete = ManageSongList.deleteById;
|
||||
static Edit = ManageSongList.editById;
|
||||
static read = ManageSongList.Read;
|
||||
}
|
||||
|
||||
// 导出错误类供外部使用
|
||||
export { SongListError };
|
||||
435
src/main/services/songList/PlayListSongs.ts
Normal file
435
src/main/services/songList/PlayListSongs.ts
Normal file
@@ -0,0 +1,435 @@
|
||||
import type { Songs as SongItem } from "@common/types/songList";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { getAppDirPath } from "../../utils/path";
|
||||
|
||||
// 错误类定义
|
||||
class PlayListError extends Error {
|
||||
constructor(message: string, public code?: string) {
|
||||
super(message);
|
||||
this.name = 'PlayListError';
|
||||
}
|
||||
}
|
||||
|
||||
// 工具函数类
|
||||
class PlayListUtils {
|
||||
/**
|
||||
* 获取歌单文件路径
|
||||
*/
|
||||
static getFilePath(hashId: string): string {
|
||||
if (!hashId || typeof hashId !== 'string' || !hashId.trim()) {
|
||||
throw new PlayListError('无效的歌单ID', 'INVALID_HASH_ID');
|
||||
}
|
||||
return path.join(getAppDirPath('userData'), 'songList', `${hashId.trim()}.json`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保目录存在
|
||||
*/
|
||||
static ensureDirectoryExists(dirPath: string): void {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的JSON解析
|
||||
*/
|
||||
static safeJsonParse<T>(content: string, defaultValue: T): T {
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
return parsed as T;
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的JSON解析(专门用于数组)
|
||||
*/
|
||||
static safeJsonParseArray<T>(content: string, defaultValue: T[]): T[] {
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
return Array.isArray(parsed) ? parsed : defaultValue;
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证歌曲对象
|
||||
*/
|
||||
static isValidSong(song: any): song is SongItem {
|
||||
return song &&
|
||||
typeof song === 'object' &&
|
||||
(typeof song.songmid === 'string' || typeof song.songmid === 'number') &&
|
||||
String(song.songmid).trim().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 去重歌曲列表
|
||||
*/
|
||||
static deduplicateSongs(songs: SongItem[]): SongItem[] {
|
||||
const seen = new Set<string>();
|
||||
return songs.filter(song => {
|
||||
const songmidStr = String(song.songmid);
|
||||
if (seen.has(songmidStr)) {
|
||||
return false;
|
||||
}
|
||||
seen.add(songmidStr);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default class PlayListSongs {
|
||||
protected readonly filePath: string;
|
||||
protected list: SongItem[];
|
||||
private isDirty: boolean = false;
|
||||
|
||||
constructor(hashId: string) {
|
||||
this.filePath = PlayListUtils.getFilePath(hashId);
|
||||
this.list = [];
|
||||
this.initList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化歌单列表
|
||||
*/
|
||||
private initList(): void {
|
||||
// 增加重试机制,处理文件创建的时序问题
|
||||
const maxRetries = 3;
|
||||
const retryDelay = 100; // 100ms
|
||||
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
try {
|
||||
if (!fs.existsSync(this.filePath)) {
|
||||
if (attempt < maxRetries - 1) {
|
||||
// 等待一段时间后重试
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < retryDelay) {
|
||||
// 简单的同步等待
|
||||
}
|
||||
continue;
|
||||
}
|
||||
throw new PlayListError('歌单文件不存在', 'FILE_NOT_FOUND');
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(this.filePath, 'utf-8');
|
||||
const parsed = PlayListUtils.safeJsonParseArray<SongItem>(content, []);
|
||||
|
||||
// 验证和清理数据
|
||||
this.list = parsed.filter(PlayListUtils.isValidSong);
|
||||
|
||||
// 如果数据被清理过,标记为需要保存
|
||||
if (this.list.length !== parsed.length) {
|
||||
this.isDirty = true;
|
||||
console.warn(`歌单文件包含无效数据,已自动清理 ${parsed.length - this.list.length} 条无效记录`);
|
||||
}
|
||||
|
||||
// 成功读取,退出重试循环
|
||||
return;
|
||||
|
||||
} catch (error) {
|
||||
if (attempt < maxRetries - 1) {
|
||||
console.warn(`读取歌单文件失败,第 ${attempt + 1} 次重试:`, error);
|
||||
// 等待一段时间后重试
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < retryDelay) {
|
||||
// 简单的同步等待
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
console.error('读取歌单文件失败:', error);
|
||||
throw new PlayListError(`读取歌单失败: ${error instanceof Error ? error.message : '未知错误'}`, 'READ_FAILED');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查歌单文件是否存在
|
||||
*/
|
||||
static hasListFile(hashId: string): boolean {
|
||||
try {
|
||||
const filePath = PlayListUtils.getFilePath(hashId);
|
||||
return fs.existsSync(filePath);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加歌曲到歌单
|
||||
*/
|
||||
addSongs(songs: SongItem[]): void {
|
||||
if (!Array.isArray(songs) || songs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 验证和过滤有效歌曲
|
||||
const validSongs = songs.filter(PlayListUtils.isValidSong);
|
||||
if (validSongs.length === 0) {
|
||||
console.warn('没有有效的歌曲可添加');
|
||||
return;
|
||||
}
|
||||
|
||||
// 使用 Set 提高查重性能,统一转换为字符串进行比较
|
||||
const existingSongMids = new Set(this.list.map(song => String(song.songmid)));
|
||||
|
||||
// 添加不重复的歌曲
|
||||
const newSongs = validSongs.filter(song => !existingSongMids.has(String(song.songmid)));
|
||||
|
||||
if (newSongs.length > 0) {
|
||||
this.list.push(...newSongs);
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
|
||||
console.log(`成功添加 ${newSongs.length} 首歌曲,跳过 ${validSongs.length - newSongs.length} 首重复歌曲`);
|
||||
} else {
|
||||
console.log('所有歌曲都已存在,未添加任何歌曲');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从歌单中移除歌曲
|
||||
*/
|
||||
removeSong(songmid: string | number): boolean {
|
||||
if (!songmid && songmid !== 0) {
|
||||
throw new PlayListError('无效的歌曲ID', 'INVALID_SONG_ID');
|
||||
}
|
||||
|
||||
const songmidStr = String(songmid);
|
||||
const index = this.list.findIndex(item => String(item.songmid) === songmidStr);
|
||||
if (index !== -1) {
|
||||
this.list.splice(index, 1);
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量移除歌曲
|
||||
*/
|
||||
removeSongs(songmids: (string | number)[]): { removed: number; notFound: number } {
|
||||
if (!Array.isArray(songmids) || songmids.length === 0) {
|
||||
return { removed: 0, notFound: 0 };
|
||||
}
|
||||
|
||||
const validSongMids = songmids.filter(id => (id || id === 0) && (typeof id === 'string' || typeof id === 'number'));
|
||||
const songMidSet = new Set(validSongMids.map(id => String(id)));
|
||||
|
||||
const initialLength = this.list.length;
|
||||
this.list = this.list.filter(song => !songMidSet.has(String(song.songmid)));
|
||||
|
||||
const removedCount = initialLength - this.list.length;
|
||||
const notFoundCount = validSongMids.length - removedCount;
|
||||
|
||||
if (removedCount > 0) {
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
}
|
||||
|
||||
return { removed: removedCount, notFound: notFoundCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空歌单
|
||||
*/
|
||||
clearSongs(): void {
|
||||
if (this.list.length > 0) {
|
||||
this.list = [];
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存到文件
|
||||
*/
|
||||
private saveToFile(): void {
|
||||
if (!this.isDirty) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const dir = path.dirname(this.filePath);
|
||||
PlayListUtils.ensureDirectoryExists(dir);
|
||||
|
||||
// 原子性写入:先写临时文件,再重命名
|
||||
const tempPath = `${this.filePath}.tmp`;
|
||||
const content = JSON.stringify(this.list, null, 2);
|
||||
|
||||
fs.writeFileSync(tempPath, content);
|
||||
fs.renameSync(tempPath, this.filePath);
|
||||
|
||||
this.isDirty = false;
|
||||
} catch (error) {
|
||||
console.error('保存歌单文件失败:', error);
|
||||
throw new PlayListError(`保存歌单失败: ${error instanceof Error ? error.message : '未知错误'}`, 'SAVE_FAILED');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制保存到文件
|
||||
*/
|
||||
forceSave(): void {
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌曲列表
|
||||
*/
|
||||
getSongs(): readonly SongItem[] {
|
||||
return Object.freeze([...this.list]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌曲数量
|
||||
*/
|
||||
getCount(): number {
|
||||
return this.list.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查歌曲是否存在
|
||||
*/
|
||||
hasSong(songmid: string | number): boolean {
|
||||
if (!songmid && songmid !== 0) {
|
||||
return false;
|
||||
}
|
||||
const songmidStr = String(songmid);
|
||||
return this.list.some(song => String(song.songmid) === songmidStr);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据songmid获取歌曲
|
||||
*/
|
||||
getSong(songmid: string | number): SongItem | null {
|
||||
if (!songmid && songmid !== 0) {
|
||||
return null;
|
||||
}
|
||||
const songmidStr = String(songmid);
|
||||
return this.list.find(song => String(song.songmid) === songmidStr) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索歌曲
|
||||
*/
|
||||
searchSongs(keyword: string): SongItem[] {
|
||||
if (!keyword || typeof keyword !== 'string') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const lowerKeyword = keyword.toLowerCase();
|
||||
return this.list.filter(song =>
|
||||
song.name?.toLowerCase().includes(lowerKeyword) ||
|
||||
song.singer?.toLowerCase().includes(lowerKeyword) ||
|
||||
song.albumName?.toLowerCase().includes(lowerKeyword)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单统计信息
|
||||
*/
|
||||
getStatistics(): {
|
||||
total: number;
|
||||
bySinger: Record<string, number>;
|
||||
byAlbum: Record<string, number>;
|
||||
lastModified: string;
|
||||
} {
|
||||
const bySinger: Record<string, number> = {};
|
||||
const byAlbum: Record<string, number> = {};
|
||||
|
||||
this.list.forEach(song => {
|
||||
// 统计歌手
|
||||
if (song.singer) {
|
||||
const singerName = String(song.singer);
|
||||
bySinger[singerName] = (bySinger[singerName] || 0) + 1;
|
||||
}
|
||||
|
||||
// 统计专辑
|
||||
if (song.albumName) {
|
||||
const albumName = String(song.albumName);
|
||||
byAlbum[albumName] = (byAlbum[albumName] || 0) + 1;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
total: this.list.length,
|
||||
bySinger,
|
||||
byAlbum,
|
||||
lastModified: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证歌单完整性
|
||||
*/
|
||||
validateIntegrity(): { isValid: boolean; issues: string[] } {
|
||||
const issues: string[] = [];
|
||||
|
||||
// 检查文件是否存在
|
||||
if (!fs.existsSync(this.filePath)) {
|
||||
issues.push('歌单文件不存在');
|
||||
}
|
||||
|
||||
// 检查数据完整性
|
||||
const invalidSongs = this.list.filter(song => !PlayListUtils.isValidSong(song));
|
||||
if (invalidSongs.length > 0) {
|
||||
issues.push(`发现 ${invalidSongs.length} 首无效歌曲`);
|
||||
}
|
||||
|
||||
// 检查重复歌曲
|
||||
const songMids = this.list.map(song => String(song.songmid));
|
||||
const uniqueSongMids = new Set(songMids);
|
||||
if (songMids.length !== uniqueSongMids.size) {
|
||||
issues.push(`发现 ${songMids.length - uniqueSongMids.size} 首重复歌曲`);
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: issues.length === 0,
|
||||
issues
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复歌单数据
|
||||
*/
|
||||
repairData(): { fixed: boolean; changes: string[] } {
|
||||
const changes: string[] = [];
|
||||
let hasChanges = false;
|
||||
|
||||
// 移除无效歌曲
|
||||
const validSongs = this.list.filter(PlayListUtils.isValidSong);
|
||||
if (validSongs.length !== this.list.length) {
|
||||
changes.push(`移除了 ${this.list.length - validSongs.length} 首无效歌曲`);
|
||||
this.list = validSongs;
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
// 去重
|
||||
const deduplicatedSongs = PlayListUtils.deduplicateSongs(this.list);
|
||||
if (deduplicatedSongs.length !== this.list.length) {
|
||||
changes.push(`移除了 ${this.list.length - deduplicatedSongs.length} 首重复歌曲`);
|
||||
this.list = deduplicatedSongs;
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
this.isDirty = true;
|
||||
this.saveToFile();
|
||||
}
|
||||
|
||||
return {
|
||||
fixed: hasChanges,
|
||||
changes
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 导出错误类供外部使用
|
||||
export { PlayListError };
|
||||
32
src/preload/index.d.ts
vendored
32
src/preload/index.d.ts
vendored
@@ -8,7 +8,7 @@ interface CustomAPI {
|
||||
close: () => void
|
||||
setMiniMode: (isMini: boolean) => void
|
||||
toggleFullscreen: () => void
|
||||
onMusicCtrl: (callback: (event: Event, args: any) => void) => void
|
||||
onMusicCtrl: (callback: (event: Event, args: any) => void) => () => void
|
||||
|
||||
music: {
|
||||
request: (api: string, args: any) => Promise<any>
|
||||
@@ -26,6 +26,36 @@ interface CustomAPI {
|
||||
getSize: () => Promise<string>
|
||||
},
|
||||
|
||||
// 歌单管理 API
|
||||
songList: {
|
||||
// === 歌单管理 ===
|
||||
create: (name: string, description?: string, source?: string) => Promise<any>
|
||||
getAll: () => Promise<any>
|
||||
getById: (hashId: string) => Promise<any>
|
||||
delete: (hashId: string) => Promise<any>
|
||||
batchDelete: (hashIds: string[]) => Promise<any>
|
||||
edit: (hashId: string, updates: any) => Promise<any>
|
||||
updateCover: (hashId: string, coverImgUrl: string) => Promise<any>
|
||||
search: (keyword: string, source?: string) => Promise<any>
|
||||
getStatistics: () => Promise<any>
|
||||
exists: (hashId: string) => Promise<any>
|
||||
|
||||
// === 歌曲管理 ===
|
||||
addSongs: (hashId: string, songs: any[]) => Promise<any>
|
||||
removeSong: (hashId: string, songmid: string | number) => Promise<any>
|
||||
removeSongs: (hashId: string, songmids: (string | number)[]) => Promise<any>
|
||||
clearSongs: (hashId: string) => Promise<any>
|
||||
getSongs: (hashId: string) => Promise<any>
|
||||
getSongCount: (hashId: string) => Promise<any>
|
||||
hasSong: (hashId: string, songmid: string | number) => Promise<any>
|
||||
getSong: (hashId: string, songmid: string | number) => Promise<any>
|
||||
searchSongs: (hashId: string, keyword: string) => Promise<any>
|
||||
getSongStatistics: (hashId: string) => Promise<any>
|
||||
validateIntegrity: (hashId: string) => Promise<any>
|
||||
repairData: (hashId: string) => Promise<any>
|
||||
forceSave: (hashId: string) => Promise<any>
|
||||
},
|
||||
|
||||
ai: {
|
||||
ask: (prompt: string) => Promise<any>
|
||||
askStream: (prompt: string, streamId: string) => Promise<any>
|
||||
|
||||
@@ -21,8 +21,11 @@ const api = {
|
||||
ipcRenderer.send('window-mini-mode', isMini)
|
||||
},
|
||||
toggleFullscreen: () => ipcRenderer.send('window-toggle-fullscreen'),
|
||||
onMusicCtrl: (callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void) =>
|
||||
ipcRenderer.on('music-control', callback),
|
||||
onMusicCtrl: (callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => {
|
||||
const handler = (event: Electron.IpcRendererEvent) => callback(event)
|
||||
ipcRenderer.on('music-control', handler)
|
||||
return () => ipcRenderer.removeListener('music-control', handler)
|
||||
},
|
||||
|
||||
music: {
|
||||
request: (api: string, args: any) => ipcRenderer.invoke('service-music-request', api, args),
|
||||
@@ -67,6 +70,47 @@ const api = {
|
||||
getSize: () => ipcRenderer.invoke('music-cache:get-size')
|
||||
},
|
||||
|
||||
// 歌单管理 API
|
||||
songList: {
|
||||
// === 歌单管理 ===
|
||||
create: (name: string, description?: string, source?: string) =>
|
||||
ipcRenderer.invoke('songlist:create', name, description, source),
|
||||
getAll: () => ipcRenderer.invoke('songlist:get-all'),
|
||||
getById: (hashId: string) => ipcRenderer.invoke('songlist:get-by-id', hashId),
|
||||
delete: (hashId: string) => ipcRenderer.invoke('songlist:delete', hashId),
|
||||
batchDelete: (hashIds: string[]) => ipcRenderer.invoke('songlist:batch-delete', hashIds),
|
||||
edit: (hashId: string, updates: any) => ipcRenderer.invoke('songlist:edit', hashId, updates),
|
||||
updateCover: (hashId: string, coverImgUrl: string) =>
|
||||
ipcRenderer.invoke('songlist:update-cover', hashId, coverImgUrl),
|
||||
search: (keyword: string, source?: string) =>
|
||||
ipcRenderer.invoke('songlist:search', keyword, source),
|
||||
getStatistics: () => ipcRenderer.invoke('songlist:get-statistics'),
|
||||
exists: (hashId: string) => ipcRenderer.invoke('songlist:exists', hashId),
|
||||
|
||||
// === 歌曲管理 ===
|
||||
addSongs: (hashId: string, songs: any[]) =>
|
||||
ipcRenderer.invoke('songlist:add-songs', hashId, songs),
|
||||
removeSong: (hashId: string, songmid: string | number) =>
|
||||
ipcRenderer.invoke('songlist:remove-song', hashId, songmid),
|
||||
removeSongs: (hashId: string, songmids: (string | number)[]) =>
|
||||
ipcRenderer.invoke('songlist:remove-songs', hashId, songmids),
|
||||
clearSongs: (hashId: string) => ipcRenderer.invoke('songlist:clear-songs', hashId),
|
||||
getSongs: (hashId: string) => ipcRenderer.invoke('songlist:get-songs', hashId),
|
||||
getSongCount: (hashId: string) => ipcRenderer.invoke('songlist:get-song-count', hashId),
|
||||
hasSong: (hashId: string, songmid: string | number) =>
|
||||
ipcRenderer.invoke('songlist:has-song', hashId, songmid),
|
||||
getSong: (hashId: string, songmid: string | number) =>
|
||||
ipcRenderer.invoke('songlist:get-song', hashId, songmid),
|
||||
searchSongs: (hashId: string, keyword: string) =>
|
||||
ipcRenderer.invoke('songlist:search-songs', hashId, keyword),
|
||||
getSongStatistics: (hashId: string) =>
|
||||
ipcRenderer.invoke('songlist:get-song-statistics', hashId),
|
||||
validateIntegrity: (hashId: string) =>
|
||||
ipcRenderer.invoke('songlist:validate-integrity', hashId),
|
||||
repairData: (hashId: string) => ipcRenderer.invoke('songlist:repair-data', hashId),
|
||||
forceSave: (hashId: string) => ipcRenderer.invoke('songlist:force-save', hashId)
|
||||
},
|
||||
|
||||
getUserConfig: () => ipcRenderer.invoke('get-user-config'),
|
||||
|
||||
// 自动更新相关
|
||||
|
||||
16
src/renderer/components.d.ts
vendored
16
src/renderer/components.d.ts
vendored
@@ -9,6 +9,7 @@ export {}
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
AIFloatBallSettings: typeof import('./src/components/Settings/AIFloatBallSettings.vue')['default']
|
||||
AudioVisualizer: typeof import('./src/components/Play/AudioVisualizer.vue')['default']
|
||||
FloatBall: typeof import('./src/components/AI/FloatBall.vue')['default']
|
||||
FullPlay: typeof import('./src/components/Play/FullPlay.vue')['default']
|
||||
GlobalAudio: typeof import('./src/components/Play/GlobalAudio.vue')['default']
|
||||
@@ -21,8 +22,23 @@ declare module 'vue' {
|
||||
SearchComponent: typeof import('./src/components/Search/SearchComponent.vue')['default']
|
||||
ShaderBackground: typeof import('./src/components/Play/ShaderBackground.vue')['default']
|
||||
SongVirtualList: typeof import('./src/components/Music/SongVirtualList.vue')['default']
|
||||
TAlert: typeof import('tdesign-vue-next')['Alert']
|
||||
TAside: typeof import('tdesign-vue-next')['Aside']
|
||||
TBadge: typeof import('tdesign-vue-next')['Badge']
|
||||
TButton: typeof import('tdesign-vue-next')['Button']
|
||||
TContent: typeof import('tdesign-vue-next')['Content']
|
||||
TDialog: typeof import('tdesign-vue-next')['Dialog']
|
||||
TDropdown: typeof import('tdesign-vue-next')['Dropdown']
|
||||
TForm: typeof import('tdesign-vue-next')['Form']
|
||||
TFormItem: typeof import('tdesign-vue-next')['FormItem']
|
||||
ThemeSelector: typeof import('./src/components/ThemeSelector.vue')['default']
|
||||
TImage: typeof import('tdesign-vue-next')['Image']
|
||||
TInput: typeof import('tdesign-vue-next')['Input']
|
||||
TitleBarControls: typeof import('./src/components/TitleBarControls.vue')['default']
|
||||
TLayout: typeof import('tdesign-vue-next')['Layout']
|
||||
TLoading: typeof import('tdesign-vue-next')['Loading']
|
||||
TTextarea: typeof import('tdesign-vue-next')['Textarea']
|
||||
TTooltip: typeof import('tdesign-vue-next')['Tooltip']
|
||||
UpdateExample: typeof import('./src/components/UpdateExample.vue')['default']
|
||||
UpdateProgress: typeof import('./src/components/UpdateProgress.vue')['default']
|
||||
UpdateSettings: typeof import('./src/components/Settings/UpdateSettings.vue')['default']
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html>
|
||||
<head lang="zh-CN">
|
||||
<meta charset="UTF-8" />
|
||||
<title>Electron</title>
|
||||
<title>澜音 Music</title>
|
||||
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
|
||||
<!-- <meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
|
||||
BIN
src/renderer/public/default-cover.png
Normal file
BIN
src/renderer/public/default-cover.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 824 KiB |
468
src/renderer/src/api/songList.ts
Normal file
468
src/renderer/src/api/songList.ts
Normal file
@@ -0,0 +1,468 @@
|
||||
import type {
|
||||
SongListAPI,
|
||||
IPCResponse,
|
||||
BatchOperationResult,
|
||||
RemoveSongsResult,
|
||||
SongListStatistics,
|
||||
SongStatistics,
|
||||
IntegrityCheckResult,
|
||||
RepairResult
|
||||
} from '../../../types/songList'
|
||||
import type { SongList, Songs } from '@common/types/songList'
|
||||
|
||||
// 检查是否在 Electron 环境中
|
||||
const isElectron = typeof window !== 'undefined' && window.api && window.api.songList
|
||||
|
||||
/**
|
||||
* 歌单管理 API 封装类
|
||||
*/
|
||||
class SongListService implements SongListAPI {
|
||||
private get songListAPI() {
|
||||
if (!isElectron) {
|
||||
throw new Error('当前环境不支持 Electron API 调用')
|
||||
}
|
||||
return window.api.songList
|
||||
}
|
||||
|
||||
// === 歌单管理方法 ===
|
||||
|
||||
/**
|
||||
* 创建新歌单
|
||||
*/
|
||||
async create(name: string, description: string = '', source: SongList['source'] = 'local'): Promise<IPCResponse<{ id: string }>> {
|
||||
try {
|
||||
return await this.songListAPI.create(name, description, source)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '创建歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有歌单
|
||||
*/
|
||||
async getAll(): Promise<IPCResponse<SongList[]>> {
|
||||
try {
|
||||
return await this.songListAPI.getAll()
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌单列表失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID获取歌单信息
|
||||
*/
|
||||
async getById(hashId: string): Promise<IPCResponse<SongList | null>> {
|
||||
try {
|
||||
return await this.songListAPI.getById(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌单信息失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除歌单
|
||||
*/
|
||||
async delete(hashId: string): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.delete(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '删除歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除歌单
|
||||
*/
|
||||
async batchDelete(hashIds: string[]): Promise<IPCResponse<BatchOperationResult>> {
|
||||
try {
|
||||
return await this.songListAPI.batchDelete(hashIds)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '批量删除歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 编辑歌单信息
|
||||
*/
|
||||
async edit(hashId: string, updates: Partial<Omit<SongList, 'id' | 'createTime'>>): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.edit(hashId, updates)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '编辑歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新歌单封面
|
||||
*/
|
||||
async updateCover(hashId: string, coverImgUrl: string): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.updateCover(hashId, coverImgUrl)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '更新封面失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索歌单
|
||||
*/
|
||||
async search(keyword: string, source?: SongList['source']): Promise<IPCResponse<SongList[]>> {
|
||||
try {
|
||||
return await this.songListAPI.search(keyword, source)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '搜索歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单统计信息
|
||||
*/
|
||||
async getStatistics(): Promise<IPCResponse<SongListStatistics>> {
|
||||
try {
|
||||
return await this.songListAPI.getStatistics()
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取统计信息失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查歌单是否存在
|
||||
*/
|
||||
async exists(hashId: string): Promise<IPCResponse<boolean>> {
|
||||
try {
|
||||
return await this.songListAPI.exists(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '检查歌单存在性失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === 歌曲管理方法 ===
|
||||
|
||||
/**
|
||||
* 添加歌曲到歌单
|
||||
*/
|
||||
async addSongs(hashId: string, songs: Songs[]): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.addSongs(hashId, songs)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '添加歌曲失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从歌单移除歌曲
|
||||
*/
|
||||
async removeSong(hashId: string, songmid: string | number): Promise<IPCResponse<boolean>> {
|
||||
try {
|
||||
return await this.songListAPI.removeSong(hashId, songmid)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '移除歌曲失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量移除歌曲
|
||||
*/
|
||||
async removeSongs(hashId: string, songmids: (string | number)[]): Promise<IPCResponse<RemoveSongsResult>> {
|
||||
try {
|
||||
return await this.songListAPI.removeSongs(hashId, songmids)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '批量移除歌曲失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空歌单
|
||||
*/
|
||||
async clearSongs(hashId: string): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.clearSongs(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '清空歌单失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单中的歌曲列表
|
||||
*/
|
||||
async getSongs(hashId: string): Promise<IPCResponse<readonly Songs[]>> {
|
||||
try {
|
||||
return await this.songListAPI.getSongs(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌曲列表失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单歌曲数量
|
||||
*/
|
||||
async getSongCount(hashId: string): Promise<IPCResponse<number>> {
|
||||
try {
|
||||
return await this.songListAPI.getSongCount(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌曲数量失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查歌曲是否在歌单中
|
||||
*/
|
||||
async hasSong(hashId: string, songmid: string | number): Promise<IPCResponse<boolean>> {
|
||||
try {
|
||||
return await this.songListAPI.hasSong(hashId, songmid)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '检查歌曲存在性失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID获取歌曲
|
||||
*/
|
||||
async getSong(hashId: string, songmid: string | number): Promise<IPCResponse<Songs | null>> {
|
||||
try {
|
||||
return await this.songListAPI.getSong(hashId, songmid)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌曲信息失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索歌单中的歌曲
|
||||
*/
|
||||
async searchSongs(hashId: string, keyword: string): Promise<IPCResponse<Songs[]>> {
|
||||
try {
|
||||
return await this.songListAPI.searchSongs(hashId, keyword)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '搜索歌曲失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单歌曲统计信息
|
||||
*/
|
||||
async getSongStatistics(hashId: string): Promise<IPCResponse<SongStatistics>> {
|
||||
try {
|
||||
return await this.songListAPI.getSongStatistics(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌曲统计信息失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证歌单完整性
|
||||
*/
|
||||
async validateIntegrity(hashId: string): Promise<IPCResponse<IntegrityCheckResult>> {
|
||||
try {
|
||||
return await this.songListAPI.validateIntegrity(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '验证数据完整性失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复歌单数据
|
||||
*/
|
||||
async repairData(hashId: string): Promise<IPCResponse<RepairResult>> {
|
||||
try {
|
||||
return await this.songListAPI.repairData(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '修复数据失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制保存歌单
|
||||
*/
|
||||
async forceSave(hashId: string): Promise<IPCResponse> {
|
||||
try {
|
||||
return await this.songListAPI.forceSave(hashId)
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '强制保存失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === 便捷方法 ===
|
||||
|
||||
/**
|
||||
* 创建本地歌单的便捷方法
|
||||
*/
|
||||
async createLocal(name: string, description?: string): Promise<IPCResponse<{ id: string }>> {
|
||||
return this.create(name, description, 'local')
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取歌单详细信息(包含歌曲列表)
|
||||
*/
|
||||
async getPlaylistDetail(hashId: string): Promise<{
|
||||
playlist: SongList | null
|
||||
songs: readonly Songs[]
|
||||
success: boolean
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
const [playlistRes, songsRes] = await Promise.all([
|
||||
this.getById(hashId),
|
||||
this.getSongs(hashId)
|
||||
])
|
||||
|
||||
if (!playlistRes.success) {
|
||||
return {
|
||||
playlist: null,
|
||||
songs: [],
|
||||
success: false,
|
||||
error: playlistRes.error
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
playlist: playlistRes.data || null,
|
||||
songs: songsRes.success ? songsRes.data || [] : [],
|
||||
success: true
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
playlist: null,
|
||||
songs: [],
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '获取歌单详情失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全删除歌单(带确认)
|
||||
*/
|
||||
async safeDelete(hashId: string, confirmCallback?: () => Promise<boolean>): Promise<IPCResponse> {
|
||||
if (confirmCallback) {
|
||||
const confirmed = await confirmCallback()
|
||||
if (!confirmed) {
|
||||
return {
|
||||
success: false,
|
||||
error: '用户取消删除操作'
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.delete(hashId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并修复歌单数据
|
||||
*/
|
||||
async checkAndRepair(hashId: string): Promise<{
|
||||
needsRepair: boolean
|
||||
repairResult?: RepairResult
|
||||
success: boolean
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
const integrityRes = await this.validateIntegrity(hashId)
|
||||
if (!integrityRes.success) {
|
||||
return {
|
||||
needsRepair: false,
|
||||
success: false,
|
||||
error: integrityRes.error
|
||||
}
|
||||
}
|
||||
|
||||
const { isValid } = integrityRes.data!
|
||||
if (isValid) {
|
||||
return {
|
||||
needsRepair: false,
|
||||
success: true
|
||||
}
|
||||
}
|
||||
|
||||
const repairRes = await this.repairData(hashId)
|
||||
return {
|
||||
needsRepair: true,
|
||||
repairResult: repairRes.data,
|
||||
success: repairRes.success,
|
||||
error: repairRes.error
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
needsRepair: false,
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : '检查修复失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建单例实例
|
||||
export const songListAPI = new SongListService()
|
||||
|
||||
// 默认导出
|
||||
export default songListAPI
|
||||
|
||||
// 导出类型
|
||||
export type { SongListAPI, IPCResponse }
|
||||
@@ -1,8 +1,12 @@
|
||||
@import './icon_font/iconfont.css';
|
||||
:root {
|
||||
--play-bottom-height: max(min(10vh, 86px), 70px);
|
||||
--play-bottom-height: max(min(10vh, 80px), 70px);
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'lyricfont';
|
||||
src: url('./lyricfont.ttf');
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
|
||||
BIN
src/renderer/src/assets/logo.png
Normal file
BIN
src/renderer/src/assets/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
BIN
src/renderer/src/assets/lyricfont.ttf
Normal file
BIN
src/renderer/src/assets/lyricfont.ttf
Normal file
Binary file not shown.
326
src/renderer/src/components/Play/AudioVisualizer.vue
Normal file
326
src/renderer/src/components/Play/AudioVisualizer.vue
Normal file
@@ -0,0 +1,326 @@
|
||||
<script lang="ts" setup>
|
||||
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
|
||||
import { ControlAudioStore } from '@renderer/store/ControlAudio'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import audioManager from '@renderer/utils/audioManager'
|
||||
|
||||
interface Props {
|
||||
show?: boolean
|
||||
height?: number
|
||||
barCount?: number
|
||||
color?: string
|
||||
backgroundColor?: string
|
||||
}
|
||||
|
||||
// 定义事件
|
||||
const emit = defineEmits<{
|
||||
lowFreqUpdate: [volume: number]
|
||||
}>()
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
show: true,
|
||||
height: 80,
|
||||
barCount: 64,
|
||||
color: 'rgba(255, 255, 255, 0.8)',
|
||||
backgroundColor: 'transparent'
|
||||
})
|
||||
|
||||
const canvasRef = ref<HTMLCanvasElement>()
|
||||
const animationId = ref<number>()
|
||||
const analyser = ref<AnalyserNode>()
|
||||
const dataArray = ref<Uint8Array>()
|
||||
const resizeObserver = ref<ResizeObserver>()
|
||||
const componentId = ref<string>(`visualizer-${Date.now()}-${Math.random()}`)
|
||||
|
||||
const controlAudio = ControlAudioStore()
|
||||
const { Audio } = storeToRefs(controlAudio)
|
||||
|
||||
// 初始化音频分析器
|
||||
const initAudioAnalyser = () => {
|
||||
if (!Audio.value.audio) return
|
||||
|
||||
try {
|
||||
// 计算所需的 fftSize - 必须是 2 的幂次方
|
||||
const minSize = props.barCount * 2
|
||||
let fftSize = 32
|
||||
while (fftSize < minSize) {
|
||||
fftSize *= 2
|
||||
}
|
||||
fftSize = Math.min(fftSize, 2048) // 限制最大值
|
||||
|
||||
// 使用音频管理器创建分析器
|
||||
const createdAnalyser = audioManager.createAnalyser(Audio.value.audio, componentId.value, fftSize)
|
||||
analyser.value = createdAnalyser || undefined
|
||||
|
||||
if (analyser.value) {
|
||||
// 创建数据数组,明确指定 ArrayBuffer 类型
|
||||
const bufferLength = analyser.value.frequencyBinCount
|
||||
dataArray.value = new Uint8Array(new ArrayBuffer(bufferLength))
|
||||
console.log('音频分析器初始化成功')
|
||||
} else {
|
||||
console.warn('无法创建音频分析器,使用模拟数据')
|
||||
// 创建一个默认大小的数据数组用于模拟数据
|
||||
const bufferLength = fftSize / 2
|
||||
dataArray.value = new Uint8Array(new ArrayBuffer(bufferLength))
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('音频分析器初始化失败:', error)
|
||||
// 创建一个默认大小的数据数组用于模拟数据
|
||||
dataArray.value = new Uint8Array(new ArrayBuffer(256))
|
||||
}
|
||||
}
|
||||
|
||||
// 绘制可视化
|
||||
const draw = () => {
|
||||
if (!canvasRef.value || !analyser.value || !dataArray.value) return
|
||||
|
||||
const canvas = canvasRef.value
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return
|
||||
|
||||
// 获取频域数据或生成模拟数据
|
||||
if (analyser.value && dataArray.value) {
|
||||
// 有真实音频分析器,获取真实数据
|
||||
analyser.value.getByteFrequencyData(dataArray.value as Uint8Array<ArrayBuffer>)
|
||||
} else {
|
||||
// 没有音频分析器,生成模拟数据
|
||||
const time = Date.now() * 0.001
|
||||
for (let i = 0; i < dataArray.value.length; i++) {
|
||||
// 生成基于时间的模拟频谱数据
|
||||
const frequency = i / dataArray.value.length
|
||||
const amplitude = Math.sin(time * 2 + frequency * 10) * 0.5 + 0.5
|
||||
const bass = Math.sin(time * 4) * 0.3 + 0.7 // 低频变化
|
||||
dataArray.value[i] = Math.floor(amplitude * bass * 255 * (1 - frequency * 0.7))
|
||||
}
|
||||
}
|
||||
|
||||
// 计算低频音量 (80hz-120hz 范围)
|
||||
// 假设采样率为 44100Hz,fftSize 为 256,则每个频率 bin 约为 172Hz
|
||||
// 80-120Hz 大约对应前 1-2 个 bin
|
||||
const lowFreqStart = 0
|
||||
const lowFreqEnd = Math.min(3, dataArray.value.length) // 取前几个低频 bin
|
||||
let lowFreqSum = 0
|
||||
for (let i = lowFreqStart; i < lowFreqEnd; i++) {
|
||||
lowFreqSum += dataArray.value[i]
|
||||
}
|
||||
const lowFreqVolume = (lowFreqSum / (lowFreqEnd - lowFreqStart)) / 255
|
||||
|
||||
// 发送低频音量给父组件
|
||||
emit('lowFreqUpdate', lowFreqVolume)
|
||||
|
||||
// 完全清空画布
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
||||
|
||||
// 如果有背景色,再填充背景
|
||||
if (props.backgroundColor !== 'transparent') {
|
||||
ctx.fillStyle = props.backgroundColor
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||
}
|
||||
|
||||
// 使用容器的实际尺寸进行计算,因为 ctx 已经缩放过了
|
||||
const container = canvas.parentElement
|
||||
if (!container) return
|
||||
|
||||
const containerRect = container.getBoundingClientRect()
|
||||
const canvasWidth = containerRect.width
|
||||
const canvasHeight = props.height
|
||||
|
||||
// 计算对称柱状图参数
|
||||
const halfBarCount = Math.floor(props.barCount / 2)
|
||||
const barWidth = (canvasWidth / 2) / halfBarCount
|
||||
const maxBarHeight = canvasHeight * 0.9
|
||||
const centerX = canvasWidth / 2
|
||||
|
||||
// 绘制左右对称的频谱柱状图
|
||||
for (let i = 0; i < halfBarCount; i++) {
|
||||
// 增强低频响应,让可视化更敏感
|
||||
let barHeight = (dataArray.value[i] / 255) * maxBarHeight
|
||||
|
||||
// 对数据进行增强处理,让变化更明显
|
||||
barHeight = Math.pow(barHeight / maxBarHeight, 0.6) * maxBarHeight
|
||||
|
||||
const y = canvasHeight - barHeight
|
||||
|
||||
// 创建渐变色
|
||||
const gradient = ctx.createLinearGradient(0, canvasHeight, 0, y)
|
||||
gradient.addColorStop(0, props.color)
|
||||
gradient.addColorStop(1, props.color.replace(/[\d\.]+\)$/g, '0.3)'))
|
||||
|
||||
ctx.fillStyle = gradient
|
||||
|
||||
// 绘制左侧柱状图(从中心向左)
|
||||
const leftX = centerX - (i + 1) * barWidth
|
||||
ctx.fillRect(leftX, y, barWidth, barHeight)
|
||||
|
||||
// 绘制右侧柱状图(从中心向右)
|
||||
const rightX = centerX + i * barWidth
|
||||
ctx.fillRect(rightX, y, barWidth, barHeight)
|
||||
}
|
||||
|
||||
// 继续动画
|
||||
if (props.show && Audio.value.isPlay) {
|
||||
animationId.value = requestAnimationFrame(draw)
|
||||
}
|
||||
}
|
||||
|
||||
// 开始可视化
|
||||
const startVisualization = () => {
|
||||
if (!props.show || !Audio.value.isPlay) return
|
||||
|
||||
if (!analyser.value) {
|
||||
initAudioAnalyser()
|
||||
}
|
||||
|
||||
draw()
|
||||
}
|
||||
|
||||
// 停止可视化
|
||||
const stopVisualization = () => {
|
||||
try {
|
||||
if (animationId.value) {
|
||||
cancelAnimationFrame(animationId.value)
|
||||
animationId.value = undefined
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('停止动画帧时出错:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 监听播放状态变化
|
||||
watch(() => Audio.value.isPlay, (isPlaying) => {
|
||||
if (isPlaying && props.show) {
|
||||
startVisualization()
|
||||
} else {
|
||||
stopVisualization()
|
||||
}
|
||||
})
|
||||
|
||||
// 监听显示状态变化
|
||||
watch(() => props.show, (show) => {
|
||||
if (show && Audio.value.isPlay) {
|
||||
startVisualization()
|
||||
} else {
|
||||
stopVisualization()
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
// 设置画布尺寸的函数
|
||||
const resizeCanvas = () => {
|
||||
if (!canvasRef.value) return
|
||||
|
||||
const canvas = canvasRef.value
|
||||
const container = canvas.parentElement
|
||||
if (!container) return
|
||||
|
||||
// 获取容器的实际尺寸
|
||||
const containerRect = container.getBoundingClientRect()
|
||||
const dpr = window.devicePixelRatio || 1
|
||||
|
||||
// 设置 canvas 的实际尺寸
|
||||
canvas.width = containerRect.width * dpr
|
||||
canvas.height = props.height * dpr
|
||||
|
||||
// 设置 CSS 尺寸
|
||||
canvas.style.width = containerRect.width + 'px'
|
||||
canvas.style.height = props.height + 'px'
|
||||
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (ctx) {
|
||||
// 重置变换矩阵并重新缩放
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.scale(dpr, dpr)
|
||||
}
|
||||
|
||||
console.log('Canvas resized:', containerRect.width, 'x', props.height)
|
||||
}
|
||||
|
||||
// 组件挂载
|
||||
onMounted(() => {
|
||||
if (canvasRef.value) {
|
||||
resizeCanvas()
|
||||
|
||||
// 使用 ResizeObserver 监听容器尺寸变化
|
||||
resizeObserver.value = new ResizeObserver((entries) => {
|
||||
for (const _entry of entries) {
|
||||
// 使用 nextTick 确保 DOM 更新完成
|
||||
nextTick(() => {
|
||||
resizeCanvas()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// 观察 canvas 元素的父容器
|
||||
const container = canvasRef.value.parentElement
|
||||
if (container) {
|
||||
resizeObserver.value.observe(container)
|
||||
}
|
||||
}
|
||||
|
||||
if (Audio.value.audio && props.show && Audio.value.isPlay) {
|
||||
initAudioAnalyser()
|
||||
startVisualization()
|
||||
}
|
||||
})
|
||||
|
||||
// 组件卸载
|
||||
onBeforeUnmount(() => {
|
||||
console.log('AudioVisualizer 组件开始卸载')
|
||||
|
||||
// 停止可视化动画
|
||||
stopVisualization()
|
||||
|
||||
// 清理音频上下文和相关资源
|
||||
try {
|
||||
// 只断开分析器连接,不断开共享的音频源
|
||||
if (analyser.value) {
|
||||
analyser.value.disconnect()
|
||||
analyser.value = undefined
|
||||
}
|
||||
|
||||
|
||||
} catch (error) {
|
||||
console.warn('清理音频资源时出错:', error)
|
||||
}
|
||||
|
||||
// 断开 ResizeObserver
|
||||
try {
|
||||
if (resizeObserver.value) {
|
||||
resizeObserver.value.disconnect()
|
||||
resizeObserver.value = undefined
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('断开 ResizeObserver 时出错:', error)
|
||||
}
|
||||
|
||||
// 清理数据数组
|
||||
dataArray.value = undefined
|
||||
|
||||
console.log('AudioVisualizer 组件卸载完成')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="audio-visualizer" :style="{ height: `${height}px` }">
|
||||
<canvas
|
||||
ref="canvasRef"
|
||||
class="visualizer-canvas"
|
||||
:style="{ height: `${height}px` }"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.audio-visualizer {
|
||||
width: 100%;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
.visualizer-canvas {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border-radius: 4px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,6 +1,7 @@
|
||||
<!-- eslint-disable vue/require-toggle-inside-transition -->
|
||||
<script lang="ts" setup>
|
||||
import TitleBarControls from '../TitleBarControls.vue'
|
||||
import AudioVisualizer from './AudioVisualizer.vue'
|
||||
// import ShaderBackground from './ShaderBackground.vue'
|
||||
import {
|
||||
BackgroundRender,
|
||||
@@ -23,13 +24,15 @@ interface Props {
|
||||
show?: boolean
|
||||
coverImage?: string
|
||||
songId?: string | null
|
||||
songInfo: SongList | { songmid: number | null }
|
||||
songInfo: SongList | { songmid: number | null | string },
|
||||
mainColor:string
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
show: false,
|
||||
coverImage: '@assets/images/Default.jpg',
|
||||
songId: ''
|
||||
songId: '',
|
||||
mainColor: '#fff'
|
||||
})
|
||||
// 定义事件
|
||||
const emit = defineEmits(['toggle-fullscreen'])
|
||||
@@ -76,7 +79,8 @@ const state = reactive({
|
||||
albumUrl: props.coverImage,
|
||||
albumIsVideo: false,
|
||||
currentTime: 0,
|
||||
lyricLines: [] as LyricLine[]
|
||||
lyricLines: [] as LyricLine[],
|
||||
lowFreqVolume: 1.0
|
||||
})
|
||||
|
||||
// 监听歌曲ID变化,获取歌词
|
||||
@@ -242,93 +246,77 @@ watch(
|
||||
state.currentTime = Math.round(newTime * 1000)
|
||||
}
|
||||
)
|
||||
|
||||
// 处理低频音量更新
|
||||
const handleLowFreqUpdate = (volume: number) => {
|
||||
state.lowFreqVolume = volume
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="full-play" :class="{ active: props.show, 'use-black-text': useBlackText }">
|
||||
<!-- <ShaderBackground :cover-image="actualCoverImage" /> -->
|
||||
<BackgroundRender
|
||||
ref="bgRef"
|
||||
:album="actualCoverImage"
|
||||
:album-is-video="false"
|
||||
:fps="30"
|
||||
:flow-speed="4"
|
||||
:low-freq-volume="1"
|
||||
:has-lyric="state.lyricLines.length > 10"
|
||||
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1"
|
||||
/>
|
||||
<BackgroundRender ref="bgRef" :album="actualCoverImage" :album-is-video="false" :fps="30" :flow-speed="4"
|
||||
:has-lyric="state.lyricLines.length > 10"
|
||||
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1" />
|
||||
<!-- 全屏按钮 -->
|
||||
<button
|
||||
class="fullscreen-btn"
|
||||
:class="{ 'black-text': useBlackText }"
|
||||
@click="toggleFullscreen"
|
||||
>
|
||||
<button class="fullscreen-btn" :class="{ 'black-text': useBlackText }" @click="toggleFullscreen">
|
||||
<Fullscreen1Icon v-if="!isFullscreen" class="icon" />
|
||||
<FullscreenExit1Icon v-else class="icon" />
|
||||
</button>
|
||||
<button
|
||||
class="putawayscreen-btn"
|
||||
:class="{ 'black-text': useBlackText }"
|
||||
@click="emit('toggle-fullscreen')"
|
||||
>
|
||||
<button class="putawayscreen-btn" :class="{ 'black-text': useBlackText }" @click="emit('toggle-fullscreen')">
|
||||
<ChevronDownIcon class="icon" />
|
||||
</button>
|
||||
<Transition name="fade-nav">
|
||||
<TitleBarControls
|
||||
v-if="props.show"
|
||||
class="top"
|
||||
style="-webkit-app-region: drag"
|
||||
:color="useBlackText ? 'black' : 'white'"
|
||||
/>
|
||||
<TitleBarControls v-if="props.show" class="top" style="-webkit-app-region: drag"
|
||||
:color="useBlackText ? 'black' : 'white'" />
|
||||
</Transition>
|
||||
<div class="playbox">
|
||||
<!-- 播放控件内容
|
||||
<div v-if="props.show" class="song-info">
|
||||
<h1>当前播放</h1>
|
||||
<p>这里将显示歌曲信息</p>
|
||||
</div> -->
|
||||
<div class="left" :style="state.lyricLines.length <= 0 && 'width:100vw'">
|
||||
<div
|
||||
class="box"
|
||||
:style="
|
||||
!Audio.isPlay
|
||||
? 'animation-play-state: paused;'
|
||||
: '' +
|
||||
(state.lyricLines.length <= 0
|
||||
? 'width:70vh;height:70vh; transition: width 0.3s ease, height 0.3s ease; transition-delay: 0.8s;'
|
||||
: '')
|
||||
"
|
||||
>
|
||||
<t-image
|
||||
:src="coverImage"
|
||||
:style="
|
||||
state.lyricLines.length > 0
|
||||
? 'width: min(20vw, 380px); height: min(20vw, 380px)'
|
||||
: 'width: 45vh; height: 45vh;transition: width 0.3s ease, height 0.3s ease; transition-delay: 1s;'
|
||||
"
|
||||
shape="circle"
|
||||
class="cover"
|
||||
/>
|
||||
<div class="cd-container"
|
||||
:class="{ playing: Audio.isPlay }"
|
||||
:style="!Audio.isPlay
|
||||
? 'animation-play-state: paused;'
|
||||
: '' +
|
||||
(state.lyricLines.length <= 0
|
||||
? 'width:70vh;height:70vh; transition: width 0.3s ease, height 0.3s ease; transition-delay: 0.8s;'
|
||||
: '')
|
||||
">
|
||||
<!-- 黑胶唱片 -->
|
||||
<div class="vinyl-record"></div>
|
||||
<!-- 唱片标签 -->
|
||||
<div class="vinyl-label">
|
||||
<t-image :src="coverImage" shape="circle" class="cover" />
|
||||
<div class="label-shine"></div>
|
||||
</div>
|
||||
<!-- 中心孔 -->
|
||||
<div class="center-hole"></div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="state.lyricLines.length > 0" class="right">
|
||||
<LyricPlayer
|
||||
ref="lyricPlayerRef"
|
||||
:lyric-lines="props.show ? state.lyricLines : []"
|
||||
:current-time="state.currentTime"
|
||||
:align-position="0.38"
|
||||
style="mix-blend-mode: plus-lighter"
|
||||
class="lyric-player"
|
||||
@line-click="
|
||||
<LyricPlayer ref="lyricPlayerRef" :lyric-lines="props.show ? state.lyricLines : []"
|
||||
:current-time="state.currentTime" class="lyric-player" @line-click="
|
||||
(e) => {
|
||||
if (Audio.audio) Audio.audio.currentTime = e.line.getLine().startTime / 1000
|
||||
}
|
||||
"
|
||||
>
|
||||
|
||||
>
|
||||
<template #bottom-line> Test Bottom Line </template>
|
||||
</LyricPlayer>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 音频可视化组件 -->
|
||||
<div class="audio-visualizer-container" v-if="props.show&&coverImage">
|
||||
<AudioVisualizer
|
||||
:show="props.show && Audio.isPlay"
|
||||
:height="70"
|
||||
:bar-count="80"
|
||||
:color='mainColor'
|
||||
@low-freq-update="handleLowFreqUpdate"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -429,16 +417,15 @@ watch(
|
||||
.playbox {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
// background-color: rgba(0, 0, 0, 0.256);
|
||||
background-color: rgba(0, 0, 0, 0.256);
|
||||
drop-filter: blur(10px);
|
||||
padding: 0 10vw;
|
||||
-webkit-drop-filter: blur(10px);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
position: relative;
|
||||
|
||||
:deep(.lyric-player) {
|
||||
--amll-lyric-player-font-size: max(2vw, 29px);
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
|
||||
.left {
|
||||
width: 40%;
|
||||
@@ -454,33 +441,255 @@ watch(
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin: 0 0 var(--play-bottom-height) 0;
|
||||
perspective: 1000px;
|
||||
|
||||
.box {
|
||||
.cd-container {
|
||||
width: min(30vw, 700px);
|
||||
height: min(30vw, 700px);
|
||||
background-color: #000000;
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 1000%;
|
||||
animation: rotateRecord 10s linear infinite;
|
||||
animation: rotateRecord 33s linear infinite;
|
||||
transition: filter .3s ease;
|
||||
filter: drop-shadow(0 15px 35px rgba(0, 0, 0, 0.6));
|
||||
|
||||
:deep(.cover) img {
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
&:hover {
|
||||
filter: drop-shadow(0 20px 45px rgba(0, 0, 0, 0.7));
|
||||
}
|
||||
|
||||
/* 黑胶唱片主体 */
|
||||
.vinyl-record {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%, #1a1a1a 0%, #0d0d0d 100%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
|
||||
/* 唱片纹理轨道 */
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
repeating-conic-gradient(
|
||||
from 0deg,
|
||||
transparent 0deg,
|
||||
rgba(255, 255, 255, 0.02) 0.5deg,
|
||||
transparent 1deg,
|
||||
rgba(255, 255, 255, 0.01) 1.5deg,
|
||||
transparent 2deg
|
||||
),
|
||||
repeating-radial-gradient(
|
||||
circle at 50% 50%,
|
||||
transparent 0px,
|
||||
rgba(255, 255, 255, 0.03) 1px,
|
||||
transparent 2px,
|
||||
transparent 8px
|
||||
);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* 唱片光泽效果 */
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background:
|
||||
radial-gradient(ellipse at 30% 30%,
|
||||
rgba(255, 255, 255, 0.08) 0%,
|
||||
rgba(255, 255, 255, 0.04) 25%,
|
||||
rgba(255, 255, 255, 0.02) 50%,
|
||||
rgba(255, 255, 255, 0.01) 75%,
|
||||
transparent 100%
|
||||
);
|
||||
border-radius: 50%;
|
||||
z-index: 2;
|
||||
animation: vinylShine 6s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
/* 唱片标签区域 */
|
||||
.vinyl-label {
|
||||
position: absolute;
|
||||
width: 60%;
|
||||
height: 60%;
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%,
|
||||
rgba(40, 40, 40, 0.95) 0%,
|
||||
rgba(25, 25, 25, 0.98) 70%,
|
||||
rgba(15, 15, 15, 1) 100%
|
||||
);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 3;
|
||||
box-shadow:
|
||||
inset 0 0 20px rgba(0, 0, 0, 0.8),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.05),
|
||||
0 0 10px rgba(0, 0, 0, 0.5);
|
||||
|
||||
:deep(.cover) {
|
||||
position: relative;
|
||||
z-index: 4;
|
||||
border-radius: 50%;
|
||||
overflow: hidden;
|
||||
box-shadow:
|
||||
0 0 20px rgba(0, 0, 0, 0.4),
|
||||
inset 0 0 0 2px rgba(255, 255, 255, 0.1);
|
||||
width: 95% !important;
|
||||
height: 95% !important;
|
||||
aspect-ratio: 1 / 1;
|
||||
|
||||
img {
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
border-radius: 50%;
|
||||
filter: brightness(0.85) contrast(1.15) saturate(1.1);
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
object-fit: cover;
|
||||
}
|
||||
}
|
||||
|
||||
/* 标签光泽 */
|
||||
.label-shine {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background:
|
||||
radial-gradient(ellipse at 25% 25%,
|
||||
rgba(255, 255, 255, 0.1) 0%,
|
||||
transparent 50%
|
||||
);
|
||||
border-radius: 50%;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
animation: labelShine 8s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
/* 中心孔 */
|
||||
.center-hole {
|
||||
position: absolute;
|
||||
width: 8%;
|
||||
height: 8%;
|
||||
background:
|
||||
radial-gradient(circle,
|
||||
#000 0%,
|
||||
#111 30%,
|
||||
#222 70%,
|
||||
#333 100%
|
||||
);
|
||||
border-radius: 50%;
|
||||
z-index: 10;
|
||||
box-shadow:
|
||||
inset 0 0 8px rgba(0, 0, 0, 0.9),
|
||||
0 0 3px rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.right {
|
||||
:deep(.lyric-player) {
|
||||
font-family: lyricfont;
|
||||
--amll-lyric-player-font-size: min(2.6vw, 32px);
|
||||
|
||||
// bottom: max(2vw, 29px);
|
||||
|
||||
height: 120%;
|
||||
transform: translateY(-10%);
|
||||
&>div{
|
||||
padding-bottom: 0;
|
||||
overflow: hidden;
|
||||
transform: translateY(-20px);
|
||||
}
|
||||
}
|
||||
|
||||
padding: 0 20px;
|
||||
padding-top: 90px;
|
||||
|
||||
margin: 80px 0 calc(var(--play-bottom-height)) 0;
|
||||
overflow: hidden;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
.audio-visualizer-container {
|
||||
position: absolute;
|
||||
bottom: calc(var(--play-bottom-height) - 10px);
|
||||
z-index: 9999;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 60px;
|
||||
// background: linear-gradient(to top, rgba(0, 0, 0, 0.3), transparent);
|
||||
filter: blur(6px);
|
||||
// max-width: 1000px;
|
||||
// -webkit-backdrop-filter: blur(10px);
|
||||
// border-top: 1px solid rgba(255, 255, 255, 0.1);
|
||||
z-index: 5;
|
||||
// padding: 0 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes rotateRecord {
|
||||
to {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes vinylShine {
|
||||
0% {
|
||||
opacity: 0.1;
|
||||
transform: rotate(0deg) scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.2;
|
||||
transform: rotate(180deg) scale(1.1);
|
||||
}
|
||||
100% {
|
||||
opacity: 0.1;
|
||||
transform: rotate(360deg) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes labelShine {
|
||||
0% {
|
||||
opacity: 0.05;
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
25% {
|
||||
opacity: 0.15;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.1;
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
75% {
|
||||
opacity: 0.15;
|
||||
}
|
||||
100% {
|
||||
opacity: 0.05;
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
nextTick,
|
||||
onActivated,
|
||||
onDeactivated,
|
||||
toRaw
|
||||
toRaw,
|
||||
provide
|
||||
} from 'vue'
|
||||
import { ControlAudioStore } from '@renderer/store/ControlAudio'
|
||||
import { LocalUserDetailStore } from '@renderer/store/LocalUserDetail'
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
destroyPlaylistEventListeners,
|
||||
getSongRealUrl
|
||||
} from '@renderer/utils/playlistManager'
|
||||
import defaultCoverImg from '/default-cover.png'
|
||||
|
||||
const controlAudio = ControlAudioStore()
|
||||
const localUserStore = LocalUserDetailStore()
|
||||
@@ -34,7 +36,7 @@ const { setCurrentTime, start, stop, setVolume, setUrl } = controlAudio
|
||||
const showFullPlay = ref(false)
|
||||
document.addEventListener('keydown', KeyEvent)
|
||||
// 处理最小化右键的事件
|
||||
window.api.onMusicCtrl(() => {
|
||||
const removeMusicCtrlListener = window.api.onMusicCtrl(() => {
|
||||
togglePlayPause()
|
||||
})
|
||||
let timer: any = null
|
||||
@@ -118,7 +120,7 @@ const waitForAudioReady = (): Promise<void> => {
|
||||
|
||||
// 存储待恢复的播放位置
|
||||
let pendingRestorePosition = 0
|
||||
let pendingRestoreSongId: number | null = null
|
||||
let pendingRestoreSongId: number | string | null = null
|
||||
|
||||
// 记录组件被停用前的播放状态
|
||||
let wasPlaying = false
|
||||
@@ -172,7 +174,7 @@ const playSong = async (song: SongList) => {
|
||||
// 同时更新播放列表中对应歌曲的URL
|
||||
const playlistIndex = list.value.findIndex((item) => item.songmid === song.songmid)
|
||||
if (playlistIndex !== -1) {
|
||||
;(list.value[playlistIndex] as any).url = urlToPlay
|
||||
; (list.value[playlistIndex] as any).url = urlToPlay
|
||||
}
|
||||
} catch (error) {
|
||||
throw error
|
||||
@@ -226,7 +228,7 @@ const playSong = async (song: SongList) => {
|
||||
MessagePlugin.error('播放失败,原因:' + error.message)
|
||||
}
|
||||
}
|
||||
|
||||
provide('PlaySong', playSong)
|
||||
// 歌曲信息
|
||||
// const playMode = ref(userInfo.value.playMode || PlayMode.SEQUENCE)
|
||||
const playMode = ref(PlayMode.SEQUENCE)
|
||||
@@ -377,13 +379,10 @@ const playNext = async () => {
|
||||
if (Audio.value.audio) {
|
||||
Audio.value.audio.currentTime = 0
|
||||
}
|
||||
|
||||
// 如果当前正在播放,继续播放;如果暂停,保持暂停
|
||||
if (Audio.value.isPlay) {
|
||||
const startResult = start()
|
||||
if (startResult && typeof startResult.then === 'function') {
|
||||
await startResult
|
||||
}
|
||||
const startResult = start()
|
||||
if (startResult && typeof startResult.then === 'function') {
|
||||
await startResult
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -412,7 +411,7 @@ const playNext = async () => {
|
||||
|
||||
// 定期保存当前播放位置
|
||||
let savePositionInterval: number | null = null
|
||||
let unEnded: () => any = () => {}
|
||||
let unEnded: () => any = () => { }
|
||||
// 初始化播放器
|
||||
onMounted(async () => {
|
||||
console.log('加载')
|
||||
@@ -422,6 +421,7 @@ onMounted(async () => {
|
||||
// 监听音频结束事件,根据播放模式播放下一首
|
||||
unEnded = controlAudio.subscribe('ended', () => {
|
||||
window.requestAnimationFrame(() => {
|
||||
console.log('播放结束')
|
||||
playNext()
|
||||
})
|
||||
})
|
||||
@@ -473,6 +473,9 @@ onUnmounted(() => {
|
||||
if (savePositionInterval !== null) {
|
||||
clearInterval(savePositionInterval)
|
||||
}
|
||||
if (removeMusicCtrlListener) {
|
||||
removeMusicCtrlListener()
|
||||
}
|
||||
unEnded()
|
||||
})
|
||||
|
||||
@@ -532,6 +535,7 @@ watch(
|
||||
const toggleFullPlay = () => {
|
||||
if (!songInfo.value.songmid) return
|
||||
showFullPlay.value = !showFullPlay.value
|
||||
|
||||
}
|
||||
|
||||
// 进度条相关
|
||||
@@ -668,13 +672,13 @@ const handleProgressDragStart = (event: MouseEvent) => {
|
||||
}
|
||||
|
||||
// 歌曲信息
|
||||
const songInfo = ref<Omit<SongList, 'songmid'> & { songmid: null | number }>({
|
||||
const songInfo = ref<Omit<SongList, 'songmid'> & { songmid: null | number | string }>({
|
||||
songmid: null,
|
||||
hash: '',
|
||||
name: '欢迎使用CeruMusic 🎉',
|
||||
singer: '可以配置音源插件来播放你的歌曲',
|
||||
albumName: '',
|
||||
albumId: 0,
|
||||
albumId: '0',
|
||||
source: '',
|
||||
interval: '00:00',
|
||||
img: '',
|
||||
@@ -700,15 +704,34 @@ async function setColor() {
|
||||
playbg.value = 'rgba(255,255,255,0.2)'
|
||||
playbghover.value = 'rgba(255,255,255,0.33)'
|
||||
}
|
||||
const bg = ref('#ffffff46')
|
||||
|
||||
watch(
|
||||
songInfo,
|
||||
async (newVal) => {
|
||||
bg.value = bg.value==='#ffffff'?'#ffffff46':toRaw(bg.value)
|
||||
if (newVal.img) {
|
||||
await setColor()
|
||||
} else if(songInfo.value.songmid) {
|
||||
songInfo.value.img = defaultCoverImg
|
||||
await setColor()
|
||||
}else{
|
||||
bg.value='#ffffff'
|
||||
}
|
||||
|
||||
},
|
||||
{ deep: true, immediate: true }
|
||||
)
|
||||
|
||||
|
||||
watch(showFullPlay, (val) => {
|
||||
if (val) {
|
||||
console.log('背景hei')
|
||||
bg.value = '#00000020'
|
||||
} else {
|
||||
bg.value = '#ffffff46'
|
||||
}
|
||||
})
|
||||
// onMounted(setColor)
|
||||
</script>
|
||||
|
||||
@@ -716,12 +739,8 @@ watch(
|
||||
<div class="player-container" @click.stop="toggleFullPlay">
|
||||
<!-- 进度条 -->
|
||||
<div class="progress-bar-container">
|
||||
<div
|
||||
ref="progressRef"
|
||||
class="progress-bar"
|
||||
@mousedown="handleProgressDragStart($event)"
|
||||
@click.stop="handleProgressClick"
|
||||
>
|
||||
<div ref="progressRef" class="progress-bar" @mousedown="handleProgressDragStart($event)"
|
||||
@click.stop="handleProgressClick">
|
||||
<div class="progress-background"></div>
|
||||
<div class="progress-filled" :style="{ width: `${progressPercentage}%` }"></div>
|
||||
<div class="progress-handle" :style="{ left: `${progressPercentage}%` }"></div>
|
||||
@@ -731,8 +750,9 @@ watch(
|
||||
<div class="player-content">
|
||||
<!-- 左侧:封面和歌曲信息 -->
|
||||
<div class="left-section">
|
||||
<div class="album-cover" v-show="songInfo.img">
|
||||
<img :src="songInfo.img" alt="专辑封面" />
|
||||
<div class="album-cover" v-if="songInfo.albumId">
|
||||
<img :src="songInfo.img" alt="专辑封面" v-if="songInfo.img" />
|
||||
<img :src="defaultCoverImg" alt="默认封面" />
|
||||
</div>
|
||||
|
||||
<div class="song-info">
|
||||
@@ -764,22 +784,13 @@ watch(
|
||||
<div class="extra-controls">
|
||||
<!-- 播放模式按钮 -->
|
||||
<t-tooltip :content="playModeTip">
|
||||
<t-button
|
||||
class="control-btn"
|
||||
shape="circle"
|
||||
variant="text"
|
||||
@click.stop="updatePlayMode"
|
||||
>
|
||||
<t-button class="control-btn" shape="circle" variant="text" @click.stop="updatePlayMode">
|
||||
<i :class="playModeIconClass + ' ' + 'PlayMode'" style="width: 1.5em"></i>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
|
||||
<!-- 音量控制 -->
|
||||
<div
|
||||
class="volume-control"
|
||||
@mouseenter="showVolumeSlider = true"
|
||||
@mouseleave="showVolumeSlider = false"
|
||||
>
|
||||
<div class="volume-control" @mouseenter="showVolumeSlider = true" @mouseleave="showVolumeSlider = false">
|
||||
<button class="control-btn">
|
||||
<shengyin style="width: 1.5em; height: 1.5em" />
|
||||
</button>
|
||||
@@ -788,12 +799,8 @@ watch(
|
||||
<transition name="volume-popup">
|
||||
<div v-show="showVolumeSlider" class="volume-slider-container" @click.stop>
|
||||
<div class="volume-slider">
|
||||
<div
|
||||
ref="volumeBarRef"
|
||||
class="volume-bar"
|
||||
@click="handleVolumeClick"
|
||||
@mousedown="handleVolumeDragStart"
|
||||
>
|
||||
<div ref="volumeBarRef" class="volume-bar" @click="handleVolumeClick"
|
||||
@mousedown="handleVolumeDragStart">
|
||||
<div class="volume-background"></div>
|
||||
<div class="volume-filled" :style="{ height: `${volumeValue}%` }"></div>
|
||||
<div class="volume-handle" :style="{ bottom: `${volumeValue}%` }"></div>
|
||||
@@ -807,12 +814,7 @@ watch(
|
||||
<!-- 播放列表按钮 -->
|
||||
<t-tooltip content="播放列表">
|
||||
<t-badge :count="list.length" :maxCount="99" color="#aaa">
|
||||
<t-button
|
||||
class="control-btn"
|
||||
shape="circle"
|
||||
variant="text"
|
||||
@click.stop="togglePlaylist"
|
||||
>
|
||||
<t-button class="control-btn" shape="circle" variant="text" @click.stop="togglePlaylist">
|
||||
<liebiao style="width: 1.5em; height: 1.5em" />
|
||||
</t-button>
|
||||
</t-badge>
|
||||
@@ -822,24 +824,15 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
<div class="fullbox">
|
||||
<FullPlay
|
||||
:song-id="songInfo.songmid ? songInfo.songmid.toString() : null"
|
||||
:show="showFullPlay"
|
||||
:cover-image="songInfo.img"
|
||||
@toggle-fullscreen="toggleFullPlay"
|
||||
:song-info="songInfo"
|
||||
/>
|
||||
<FullPlay :song-id="songInfo.songmid ? songInfo.songmid.toString() : null" :show="showFullPlay"
|
||||
:cover-image="songInfo.img" @toggle-fullscreen="toggleFullPlay"
|
||||
:song-info="songInfo" :main-color="maincolor" />
|
||||
</div>
|
||||
|
||||
<!-- 播放列表 -->
|
||||
<div v-show="showPlaylist" class="cover" @click="showPlaylist = false"></div>
|
||||
<transition name="playlist-drawer">
|
||||
<div
|
||||
v-show="showPlaylist"
|
||||
class="playlist-container"
|
||||
:class="{ 'full-screen-mode': showFullPlay }"
|
||||
@click.stop
|
||||
>
|
||||
<div v-show="showPlaylist" class="playlist-container" :class="{ 'full-screen-mode': showFullPlay }" @click.stop>
|
||||
<div class="playlist-header">
|
||||
<div class="playlist-title">播放列表 ({{ list.length }})</div>
|
||||
<button class="playlist-close" @click.stop="showPlaylist = false">
|
||||
@@ -853,13 +846,8 @@ watch(
|
||||
<p>请添加歌曲到播放列表,也可在设置中导入歌曲列表</p>
|
||||
</div>
|
||||
<div v-else class="playlist-songs">
|
||||
<div
|
||||
v-for="song in list"
|
||||
:key="song.songmid"
|
||||
class="playlist-song"
|
||||
:class="{ active: song.songmid === currentSongId }"
|
||||
@click="playSong(song)"
|
||||
>
|
||||
<div v-for="song in list" :key="song.songmid" class="playlist-song"
|
||||
:class="{ active: song.songmid === currentSongId }" @click="playSong(song)">
|
||||
<div class="song-info">
|
||||
<div class="song-name">{{ song.name }}</div>
|
||||
<div class="song-artist">{{ song.singer }}</div>
|
||||
@@ -905,7 +893,8 @@ watch(
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: #ffffff31;
|
||||
transition: background .3s;
|
||||
background: v-bind(bg);
|
||||
// border-top: 1px solid #e5e7eb;
|
||||
backdrop-filter: blur(1000px);
|
||||
z-index: 1000;
|
||||
@@ -939,7 +928,7 @@ watch(
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 100%;
|
||||
background: #ffffff71;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.progress-filled {
|
||||
@@ -991,6 +980,7 @@ watch(
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
padding-top: 2px;
|
||||
|
||||
.album-cover {
|
||||
width: 50px;
|
||||
|
||||
@@ -79,12 +79,16 @@ export const LocalUserDetailStore = defineStore('Local', () => {
|
||||
return list.value
|
||||
}
|
||||
|
||||
function removeSong(songId: number) {
|
||||
function removeSong(songId: number|string) {
|
||||
const index = list.value.findIndex((item) => item.songmid === songId)
|
||||
if (index !== -1) {
|
||||
list.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
function clearList() {
|
||||
list.value = []
|
||||
}
|
||||
const userSource = computed(() => {
|
||||
return {
|
||||
pluginId: userInfo.value.pluginId,
|
||||
@@ -100,6 +104,7 @@ export const LocalUserDetailStore = defineStore('Local', () => {
|
||||
addSong,
|
||||
addSongToFirst,
|
||||
removeSong,
|
||||
clearList,
|
||||
userSource
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import playList from '@common/types/playList'
|
||||
|
||||
// 音频事件相关类型定义
|
||||
|
||||
// 事件回调函数类型定义
|
||||
@@ -44,18 +46,5 @@ export type ControlAudioState = {
|
||||
url: string
|
||||
}
|
||||
|
||||
export type SongList = {
|
||||
songmid: number
|
||||
hash?: string
|
||||
singer: string
|
||||
name: string
|
||||
albumName: string
|
||||
albumId: number
|
||||
source: string
|
||||
interval: string
|
||||
img: string
|
||||
lrc: null | string
|
||||
types: string[]
|
||||
_types: Record<string, any>
|
||||
typeUrl: Record<string, any>
|
||||
}
|
||||
|
||||
export type SongList = playList
|
||||
@@ -2,7 +2,7 @@ import { PlayMode } from './audio'
|
||||
import { Sources } from './Sources'
|
||||
|
||||
export interface UserInfo {
|
||||
lastPlaySongId?: number | null
|
||||
lastPlaySongId?: number | string | null
|
||||
currentTime?: number
|
||||
volume?: number
|
||||
topBarStyle?: boolean
|
||||
|
||||
116
src/renderer/src/utils/audioManager.ts
Normal file
116
src/renderer/src/utils/audioManager.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
// 全局音频管理器,用于管理音频源和分析器
|
||||
class AudioManager {
|
||||
private static instance: AudioManager
|
||||
private audioSources = new WeakMap<HTMLAudioElement, MediaElementAudioSourceNode>()
|
||||
private audioContexts = new WeakMap<HTMLAudioElement, AudioContext>()
|
||||
private analysers = new Map<string, AnalyserNode>()
|
||||
|
||||
static getInstance(): AudioManager {
|
||||
if (!AudioManager.instance) {
|
||||
AudioManager.instance = new AudioManager()
|
||||
}
|
||||
return AudioManager.instance
|
||||
}
|
||||
|
||||
// 获取或创建音频源
|
||||
getOrCreateAudioSource(audioElement: HTMLAudioElement): { source: MediaElementAudioSourceNode; context: AudioContext } | null {
|
||||
try {
|
||||
// 检查是否已经有音频源
|
||||
let source = this.audioSources.get(audioElement)
|
||||
let context = this.audioContexts.get(audioElement)
|
||||
|
||||
if (!source || !context || context.state === 'closed') {
|
||||
// 创建新的音频上下文和源
|
||||
context = new (window.AudioContext || (window as any).webkitAudioContext)()
|
||||
source = context.createMediaElementSource(audioElement)
|
||||
|
||||
// 连接到输出,确保音频能正常播放
|
||||
source.connect(context.destination)
|
||||
|
||||
// 存储引用
|
||||
this.audioSources.set(audioElement, source)
|
||||
this.audioContexts.set(audioElement, context)
|
||||
|
||||
console.log('AudioManager: 创建新的音频源和上下文')
|
||||
}
|
||||
|
||||
return { source, context }
|
||||
} catch (error) {
|
||||
console.error('AudioManager: 创建音频源失败:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 创建分析器
|
||||
createAnalyser(audioElement: HTMLAudioElement, id: string, fftSize: number = 256): AnalyserNode | null {
|
||||
const audioData = this.getOrCreateAudioSource(audioElement)
|
||||
if (!audioData) return null
|
||||
|
||||
const { source, context } = audioData
|
||||
|
||||
try {
|
||||
// 创建分析器
|
||||
const analyser = context.createAnalyser()
|
||||
analyser.fftSize = fftSize
|
||||
analyser.smoothingTimeConstant = 0.6
|
||||
|
||||
// 创建增益节点作为中介,避免直接断开主音频链
|
||||
const gainNode = context.createGain()
|
||||
gainNode.gain.value = 1.0
|
||||
|
||||
// 连接:source -> gainNode -> analyser
|
||||
// -> destination (保持音频播放)
|
||||
source.disconnect() // 先断开所有连接
|
||||
source.connect(gainNode)
|
||||
gainNode.connect(context.destination) // 确保音频继续播放
|
||||
gainNode.connect(analyser) // 连接到分析器
|
||||
|
||||
// 存储分析器引用
|
||||
this.analysers.set(id, analyser)
|
||||
|
||||
console.log('AudioManager: 创建分析器成功')
|
||||
return analyser
|
||||
} catch (error) {
|
||||
console.error('AudioManager: 创建分析器失败:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// 移除分析器
|
||||
removeAnalyser(id: string): void {
|
||||
const analyser = this.analysers.get(id)
|
||||
if (analyser) {
|
||||
try {
|
||||
analyser.disconnect()
|
||||
this.analysers.delete(id)
|
||||
console.log('AudioManager: 移除分析器成功')
|
||||
} catch (error) {
|
||||
console.warn('AudioManager: 移除分析器时出错:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 清理音频元素的所有资源
|
||||
cleanupAudioElement(audioElement: HTMLAudioElement): void {
|
||||
try {
|
||||
const context = this.audioContexts.get(audioElement)
|
||||
if (context && context.state !== 'closed') {
|
||||
context.close()
|
||||
}
|
||||
|
||||
this.audioSources.delete(audioElement)
|
||||
this.audioContexts.delete(audioElement)
|
||||
|
||||
console.log('AudioManager: 清理音频元素资源')
|
||||
} catch (error) {
|
||||
console.warn('AudioManager: 清理资源时出错:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取分析器
|
||||
getAnalyser(id: string): AnalyserNode | undefined {
|
||||
return this.analysers.get(id)
|
||||
}
|
||||
}
|
||||
|
||||
export default AudioManager.getInstance()
|
||||
@@ -1,4 +1,92 @@
|
||||
import { extractDominantColor } from './colorExtractor'
|
||||
import DefaultCover from '@renderer/assets/images/Default.jpg'
|
||||
import CoverImage from '@renderer/assets/images/cover.png'
|
||||
|
||||
/**
|
||||
* 直接从图片分析平均亮度,不依赖颜色提取器
|
||||
* @param imageSrc 图片路径
|
||||
* @returns 返回平均亮度值 (0-1)
|
||||
*/
|
||||
async function getImageAverageLuminance(imageSrc: string): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 处理相对路径
|
||||
let actualSrc = imageSrc
|
||||
if (
|
||||
imageSrc.includes('@assets/images/Default.jpg') ||
|
||||
imageSrc.includes('@renderer/assets/images/Default.jpg')
|
||||
) {
|
||||
actualSrc = DefaultCover
|
||||
} else if (
|
||||
imageSrc.includes('@assets/images/cover.png') ||
|
||||
imageSrc.includes('@renderer/assets/images/cover.png')
|
||||
) {
|
||||
actualSrc = CoverImage
|
||||
}
|
||||
|
||||
// 如果仍然是相对路径,使用默认亮度
|
||||
if (actualSrc.startsWith('@')) {
|
||||
console.warn('无法解析相对路径,使用默认亮度')
|
||||
resolve(0.5) // 中等亮度
|
||||
return
|
||||
}
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'Anonymous'
|
||||
|
||||
img.onload = () => {
|
||||
try {
|
||||
const canvas = document.createElement('canvas')
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) {
|
||||
reject(new Error('无法创建canvas上下文'))
|
||||
return
|
||||
}
|
||||
|
||||
// 使用较小的采样尺寸提高性能
|
||||
const size = 50
|
||||
canvas.width = size
|
||||
canvas.height = size
|
||||
|
||||
ctx.drawImage(img, 0, 0, size, size)
|
||||
const imageData = ctx.getImageData(0, 0, size, size).data
|
||||
|
||||
let totalLuminance = 0
|
||||
let pixelCount = 0
|
||||
|
||||
// 计算所有非透明像素的平均亮度
|
||||
for (let i = 0; i < imageData.length; i += 4) {
|
||||
// 忽略透明像素
|
||||
if (imageData[i + 3] < 128) continue
|
||||
|
||||
const r = imageData[i] / 255
|
||||
const g = imageData[i + 1] / 255
|
||||
const b = imageData[i + 2] / 255
|
||||
|
||||
// 使用WCAG 2.0相对亮度公式
|
||||
const R = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4)
|
||||
const G = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4)
|
||||
const B = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4)
|
||||
|
||||
const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
totalLuminance += luminance
|
||||
pixelCount++
|
||||
}
|
||||
|
||||
const averageLuminance = pixelCount > 0 ? totalLuminance / pixelCount : 0.5
|
||||
resolve(averageLuminance)
|
||||
} catch (error) {
|
||||
console.error('分析图片亮度失败:', error)
|
||||
resolve(0.5) // 默认中等亮度
|
||||
}
|
||||
}
|
||||
|
||||
img.onerror = () => {
|
||||
console.error('图片加载失败:', actualSrc)
|
||||
resolve(0.5) // 默认中等亮度
|
||||
}
|
||||
|
||||
img.src = actualSrc
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断图片应该使用黑色还是白色作为对比色
|
||||
@@ -7,46 +95,24 @@ import { extractDominantColor } from './colorExtractor'
|
||||
*/
|
||||
export async function shouldUseBlackText(imageSrc: string): Promise<boolean> {
|
||||
try {
|
||||
// 提取主要颜色
|
||||
const dominantColor = await extractDominantColor(imageSrc)
|
||||
|
||||
// 使用更准确的相对亮度计算公式 (sRGB相对亮度)
|
||||
// 先将RGB值标准化到0-1范围
|
||||
const r = dominantColor.r / 255
|
||||
const g = dominantColor.g / 255
|
||||
const b = dominantColor.b / 255
|
||||
|
||||
// 应用sRGB转换
|
||||
const R = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4)
|
||||
const G = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4)
|
||||
const B = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4)
|
||||
|
||||
// 计算相对亮度 (WCAG 2.0公式)
|
||||
const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
|
||||
// 计算与黑色和白色的对比度
|
||||
// 对比度计算公式: (L1 + 0.05) / (L2 + 0.05),其中L1是较亮的颜色,L2是较暗的颜色
|
||||
const contrastWithBlack = (luminance + 0.05) / 0.05
|
||||
const contrastWithWhite = 1.05 / (luminance + 0.05)
|
||||
// 直接分析图片的平均亮度
|
||||
const averageLuminance = await getImageAverageLuminance(imageSrc)
|
||||
|
||||
console.log(
|
||||
`颜色: RGB(${dominantColor.r},${dominantColor.g},${dominantColor.b}), ` +
|
||||
`亮度: ${luminance.toFixed(3)}, ` +
|
||||
`与黑色对比度: ${contrastWithBlack.toFixed(2)}, ` +
|
||||
`与白色对比度: ${contrastWithWhite.toFixed(2)}`
|
||||
`图片: ${imageSrc}, ` +
|
||||
`平均亮度: ${averageLuminance.toFixed(3)} ` +
|
||||
`(考虑半透明黑色背景覆盖效果)`
|
||||
)
|
||||
|
||||
// 不仅考虑亮度,还要考虑对比度
|
||||
// 如果与黑色的对比度更高,说明背景较亮,应该使用黑色文字
|
||||
// 如果与白色的对比度更高,说明背景较暗,应该使用白色文字
|
||||
// 但对于中等亮度的颜色,我们需要更精细的判断
|
||||
// 考虑到图片会受到rgba(0, 0, 0, 0.256)背景覆盖,实际显示会更暗
|
||||
// 大幅提高阈值,让白色文字在更多情况下被选择
|
||||
// 只有非常明亮的图片才使用黑色文字
|
||||
|
||||
// 对于中等亮度的颜色(0.3-0.6),我们更倾向于使用黑色文本,因为黑色文本通常更易读
|
||||
if (luminance > 0.3) {
|
||||
return true // 使用黑色文本
|
||||
} else {
|
||||
return false // 使用白色文本
|
||||
}
|
||||
const shouldUseBlack = averageLuminance >= 0.6
|
||||
|
||||
console.log(`决定使用${shouldUseBlack ? '黑色' : '白色'}文字`)
|
||||
|
||||
return shouldUseBlack
|
||||
} catch (error) {
|
||||
console.error('计算对比色失败:', error)
|
||||
// 默认返回白色作为安全选择
|
||||
@@ -75,24 +141,11 @@ export async function getBestContrastTextColorWithOpacity(
|
||||
opacity: number = 1
|
||||
): Promise<string> {
|
||||
try {
|
||||
// 提取主要颜色
|
||||
const dominantColor = await extractDominantColor(imageSrc)
|
||||
// 使用相同的亮度分析逻辑
|
||||
const averageLuminance = await getImageAverageLuminance(imageSrc)
|
||||
|
||||
// 使用更准确的相对亮度计算公式 (sRGB相对亮度)
|
||||
const r = dominantColor.r / 255
|
||||
const g = dominantColor.g / 255
|
||||
const b = dominantColor.b / 255
|
||||
|
||||
// 应用sRGB转换
|
||||
const R = r <= 0.03928 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4)
|
||||
const G = g <= 0.03928 ? g / 12.92 : Math.pow((g + 0.055) / 1.055, 2.4)
|
||||
const B = b <= 0.03928 ? b / 12.92 : Math.pow((b + 0.055) / 1.055, 2.4)
|
||||
|
||||
// 计算相对亮度
|
||||
const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
|
||||
// 根据亮度决定文本颜色,使用更低的阈值
|
||||
if (luminance > 0.3) {
|
||||
// 使用与shouldUseBlackText相同的逻辑
|
||||
if (averageLuminance >= 0.6) {
|
||||
// 背景较亮,使用黑色文本
|
||||
return `rgba(0, 0, 0, ${opacity})`
|
||||
} else {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { LocalUserDetailStore } from '@renderer/store/LocalUserDetail'
|
||||
type PlaylistEvents = {
|
||||
addToPlaylistAndPlay: SongList
|
||||
addToPlaylistEnd: SongList
|
||||
replacePlaylist: SongList[]
|
||||
}
|
||||
|
||||
// 创建全局事件总线
|
||||
@@ -46,7 +47,7 @@ export async function getSongRealUrl(song: SongList): Promise<string> {
|
||||
const urlData = await window.api.music.requestSdk('getMusicUrl', {
|
||||
pluginId: LocalUserDetail.userSource.pluginId as unknown as string,
|
||||
source: song.source,
|
||||
songInfo: song,
|
||||
songInfo: song as any,
|
||||
quality
|
||||
})
|
||||
console.log(urlData)
|
||||
@@ -124,6 +125,52 @@ export async function addToPlaylistEnd(song: SongList, localUserStore: any) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换整个播放列表
|
||||
* @param songs 要替换的歌曲列表
|
||||
* @param localUserStore LocalUserDetail store实例
|
||||
* @param playSongCallback 播放歌曲的回调函数
|
||||
*/
|
||||
export async function replacePlaylist(
|
||||
songs: SongList[],
|
||||
localUserStore: any,
|
||||
playSongCallback: (song: SongList) => Promise<void>
|
||||
) {
|
||||
try {
|
||||
if (songs.length === 0) {
|
||||
await MessagePlugin.warning('歌曲列表为空')
|
||||
return
|
||||
}
|
||||
|
||||
// 清空当前播放列表
|
||||
localUserStore.list.length = 0
|
||||
|
||||
// 添加所有歌曲到播放列表
|
||||
songs.forEach(song => {
|
||||
localUserStore.addSong(song)
|
||||
})
|
||||
|
||||
// 播放第一首歌曲
|
||||
if (songs[0]) {
|
||||
await getSongRealUrl(songs[0])
|
||||
const playResult = playSongCallback(songs[0])
|
||||
|
||||
if (playResult && typeof playResult.then === 'function') {
|
||||
await playResult
|
||||
}
|
||||
}
|
||||
|
||||
await MessagePlugin.success(`已用 ${songs.length} 首歌曲替换播放列表`)
|
||||
} catch (error: any) {
|
||||
console.error('替换播放列表失败:', error)
|
||||
if (error.message) {
|
||||
await MessagePlugin.error('替换失败: ' + error.message)
|
||||
return
|
||||
}
|
||||
await MessagePlugin.error('替换播放列表失败,请重试')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化播放列表事件监听器
|
||||
* @param localUserStore LocalUserDetail store实例
|
||||
@@ -142,6 +189,11 @@ export function initPlaylistEventListeners(
|
||||
emitter.on('addToPlaylistEnd', async (song: SongList) => {
|
||||
await addToPlaylistEnd(song, localUserStore)
|
||||
})
|
||||
|
||||
// 监听替换播放列表的事件
|
||||
emitter.on('replacePlaylist', async (songs: SongList[]) => {
|
||||
await replacePlaylist(songs, localUserStore, playSongCallback)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -150,6 +202,7 @@ export function initPlaylistEventListeners(
|
||||
export function destroyPlaylistEventListeners() {
|
||||
emitter.off('addToPlaylistAndPlay')
|
||||
emitter.off('addToPlaylistEnd')
|
||||
emitter.off('replacePlaylist')
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -182,7 +182,7 @@ const handleKeyDown = () => {
|
||||
|
||||
.sidebar {
|
||||
width: 15rem;
|
||||
background-color: #fff;
|
||||
background-image: linear-gradient(to bottom,var(--td-brand-color-4) -140vh, #ffffff 30vh);
|
||||
border-right: 0.0625rem solid #e5e7eb;
|
||||
flex-shrink: 0;
|
||||
|
||||
@@ -270,7 +270,8 @@ const handleKeyDown = () => {
|
||||
|
||||
.content {
|
||||
padding: 0;
|
||||
background: #f6f6f6;
|
||||
background-image: linear-gradient(to bottom,var(--td-brand-color-4) -110vh, #ffffff 15vh);
|
||||
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
@@ -309,12 +310,16 @@ const handleKeyDown = () => {
|
||||
-webkit-app-region: no-drag;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
transition: width 0.3s;
|
||||
padding: 0 0.5rem;
|
||||
width: 18.75rem;
|
||||
width: min(18.75rem,400px);
|
||||
margin-right: 0.5rem;
|
||||
border-radius: 1.25rem !important;
|
||||
background-color: #fff;
|
||||
overflow: hidden;
|
||||
&:has(input:focus){
|
||||
width: max(18.75rem,400px);
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.t-input) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, toRaw } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
|
||||
import { LocalUserDetailStore } from '@renderer/store/LocalUserDetail'
|
||||
import { downloadSingleSong } from '@renderer/utils/download'
|
||||
import SongVirtualList from '@renderer/components/Music/SongVirtualList.vue'
|
||||
@@ -53,12 +54,79 @@ const fetchPlaylistSongs = async () => {
|
||||
source: (route.query.source as string) || (LocalUserDetail.userSource.source as any)
|
||||
}
|
||||
|
||||
// 检查是否是本地歌单
|
||||
const isLocalPlaylist = route.query.type === 'local' || route.query.source === 'local'
|
||||
|
||||
if (isLocalPlaylist) {
|
||||
// 处理本地歌单
|
||||
await fetchLocalPlaylistSongs()
|
||||
} else {
|
||||
// 处理网络歌单
|
||||
await fetchNetworkPlaylistSongs()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取歌单歌曲失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 获取本地歌单歌曲
|
||||
const fetchLocalPlaylistSongs = async () => {
|
||||
try {
|
||||
// 调用本地歌单API获取歌曲列表
|
||||
const result = await window.api.songList.getSongs(playlistInfo.value.id)
|
||||
|
||||
if (result.success && result.data) {
|
||||
songs.value = result.data.map((song: any) => ({
|
||||
singer: song.singer || '未知歌手',
|
||||
name: song.name || '未知歌曲',
|
||||
albumName: song.albumName || '未知专辑',
|
||||
albumId: song.albumId || 0,
|
||||
source: song.source || 'local',
|
||||
interval: song.interval || '0:00',
|
||||
songmid: song.songmid,
|
||||
img: song.img || '',
|
||||
lrc: song.lrc || null,
|
||||
types: song.types || [],
|
||||
_types: song._types || {},
|
||||
typeUrl: song.typeUrl || {}
|
||||
}))
|
||||
|
||||
// 更新歌单信息中的歌曲总数
|
||||
playlistInfo.value.total = songs.value.length
|
||||
|
||||
// 获取歌单详细信息
|
||||
const playlistResult = await window.api.songList.getById(playlistInfo.value.id)
|
||||
if (playlistResult.success && playlistResult.data) {
|
||||
const playlist = playlistResult.data
|
||||
playlistInfo.value = {
|
||||
...playlistInfo.value,
|
||||
title: playlist.name,
|
||||
cover: playlist.coverImgUrl || playlistInfo.value.cover,
|
||||
total: songs.value.length
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('获取本地歌单失败:', result.error)
|
||||
songs.value = []
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取本地歌单歌曲失败:', error)
|
||||
songs.value = []
|
||||
}
|
||||
}
|
||||
|
||||
// 获取网络歌单歌曲
|
||||
const fetchNetworkPlaylistSongs = async () => {
|
||||
try {
|
||||
// 调用API获取歌单详情和歌曲列表
|
||||
const result = await window.api.music.requestSdk('getPlaylistDetail', {
|
||||
source: playlistInfo.value.source,
|
||||
id: playlistInfo.value.id,
|
||||
page: 1
|
||||
}) as any
|
||||
|
||||
console.log(result)
|
||||
if (result && result.list) {
|
||||
songs.value = result.list
|
||||
@@ -78,9 +146,8 @@ const fetchPlaylistSongs = async () => {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取歌单歌曲失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
console.error('获取网络歌单失败:', error)
|
||||
songs.value = []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +201,89 @@ const handleAddToPlaylist = (song: MusicItem) => {
|
||||
;(window as any).musicEmitter.emit('addToPlaylistEnd', toRaw(song))
|
||||
}
|
||||
}
|
||||
|
||||
// 替换播放列表的通用函数
|
||||
const replacePlaylist = (songsToReplace: MusicItem[], shouldShuffle = false) => {
|
||||
if (!(window as any).musicEmitter) {
|
||||
MessagePlugin.error('播放器未初始化')
|
||||
return
|
||||
}
|
||||
|
||||
let finalSongs = [...songsToReplace]
|
||||
|
||||
if (shouldShuffle) {
|
||||
// 创建歌曲索引数组并打乱
|
||||
const shuffledIndexes = Array.from({ length: songsToReplace.length }, (_, i) => i)
|
||||
for (let i = shuffledIndexes.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1))
|
||||
;[shuffledIndexes[i], shuffledIndexes[j]] = [shuffledIndexes[j], shuffledIndexes[i]]
|
||||
}
|
||||
|
||||
// 按打乱的顺序重新排列歌曲
|
||||
finalSongs = shuffledIndexes.map(index => songsToReplace[index])
|
||||
}
|
||||
|
||||
// 使用自定义事件替换整个播放列表
|
||||
if ((window as any).musicEmitter) {
|
||||
;(window as any).musicEmitter.emit('replacePlaylist', finalSongs.map(song => toRaw(song)))
|
||||
}
|
||||
|
||||
// // 更新当前播放状态
|
||||
// if (finalSongs[0]) {
|
||||
// currentSong.value = finalSongs[0]
|
||||
// isPlaying.value = true
|
||||
// }
|
||||
// const playerSong = inject('PlaySong',(...args:any)=>args)
|
||||
// nextTick(()=>{
|
||||
// playerSong(finalSongs[0])
|
||||
// })
|
||||
MessagePlugin.success(`请稍等歌曲加载完成播放`)
|
||||
}
|
||||
|
||||
// 播放整个歌单
|
||||
const handlePlayPlaylist = () => {
|
||||
if (songs.value.length === 0) {
|
||||
MessagePlugin.warning('歌单为空,无法播放')
|
||||
return
|
||||
}
|
||||
|
||||
const dialog = DialogPlugin.confirm({
|
||||
header: '播放歌单',
|
||||
body: `确定要用歌单"${playlistInfo.value.title}"中的 ${songs.value.length} 首歌曲替换当前播放列表吗?`,
|
||||
confirmBtn: '确定替换',
|
||||
cancelBtn: '取消',
|
||||
onConfirm: () => {
|
||||
console.log('播放歌单:', playlistInfo.value.title)
|
||||
replacePlaylist(songs.value, false)
|
||||
dialog.destroy()
|
||||
},
|
||||
onCancel: () => {
|
||||
dialog.destroy()
|
||||
}
|
||||
})
|
||||
}
|
||||
// 随机播放歌单
|
||||
const handleShufflePlaylist = () => {
|
||||
if (songs.value.length === 0) {
|
||||
MessagePlugin.warning('歌单为空,无法播放')
|
||||
return
|
||||
}
|
||||
|
||||
const dialog = DialogPlugin.confirm({
|
||||
header: '随机播放歌单',
|
||||
body: `确定要用歌单"${playlistInfo.value.title}"中的 ${songs.value.length} 首歌曲随机替换当前播放列表吗?`,
|
||||
confirmBtn: '确定替换',
|
||||
cancelBtn: '取消',
|
||||
onConfirm: () => {
|
||||
console.log('随机播放歌单:', playlistInfo.value.title)
|
||||
replacePlaylist(songs.value, true)
|
||||
dialog.destroy()
|
||||
},
|
||||
onCancel: () => {
|
||||
dialog.destroy()
|
||||
}
|
||||
})
|
||||
}
|
||||
// 组件挂载时获取数据
|
||||
onMounted(() => {
|
||||
fetchPlaylistSongs()
|
||||
@@ -153,6 +303,39 @@ onMounted(() => {
|
||||
<h1 class="playlist-title">{{ playlistInfo.title }}</h1>
|
||||
<p class="playlist-author">by {{ playlistInfo.author }}</p>
|
||||
<p class="playlist-stats">{{ playlistInfo.total }} 首歌曲</p>
|
||||
|
||||
<!-- 播放控制按钮 -->
|
||||
<div class="playlist-actions">
|
||||
<t-button
|
||||
theme="primary"
|
||||
size="medium"
|
||||
@click="handlePlayPlaylist"
|
||||
:disabled="songs.length === 0 || loading"
|
||||
class="play-btn"
|
||||
>
|
||||
<template #icon>
|
||||
<svg class="play-icon" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M8 5v14l11-7z"/>
|
||||
</svg>
|
||||
</template>
|
||||
播放全部
|
||||
</t-button>
|
||||
|
||||
<t-button
|
||||
variant="outline"
|
||||
size="medium"
|
||||
@click="handleShufflePlaylist"
|
||||
:disabled="songs.length === 0 || loading"
|
||||
class="shuffle-btn"
|
||||
>
|
||||
<template #icon>
|
||||
<svg class="shuffle-icon" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M10.59 9.17L5.41 4 4 5.41l5.17 5.17 1.42-1.41zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4h-5.5zm.33 9.41l-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04-3.13-3.13z"/>
|
||||
</svg>
|
||||
</template>
|
||||
随机播放
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -290,7 +473,24 @@ onMounted(() => {
|
||||
.playlist-stats {
|
||||
font-size: 0.875rem;
|
||||
color: #9ca3af;
|
||||
margin: 0;
|
||||
margin: 0 0 1rem 0;
|
||||
}
|
||||
|
||||
.playlist-actions {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
|
||||
.play-btn,
|
||||
.shuffle-btn {
|
||||
min-width: 120px;
|
||||
|
||||
.play-icon,
|
||||
.shuffle-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -316,6 +516,36 @@ onMounted(() => {
|
||||
width: 100px;
|
||||
height: 100px;
|
||||
}
|
||||
|
||||
.playlist-details {
|
||||
.playlist-actions {
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
|
||||
.play-btn,
|
||||
.shuffle-btn {
|
||||
width: 100%;
|
||||
min-width: auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.playlist-header {
|
||||
.playlist-details {
|
||||
.playlist-actions {
|
||||
.play-btn,
|
||||
.shuffle-btn {
|
||||
.play-icon,
|
||||
.shuffle-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -105,10 +105,10 @@ async function setPic(offset: number, source: string) {
|
||||
if (typeof url !== 'object') {
|
||||
searchResults.value[i].img = url
|
||||
} else {
|
||||
searchResults.value[i].img = 'resources/logo.png'
|
||||
searchResults.value[i].img = ''
|
||||
}
|
||||
} catch (e) {
|
||||
searchResults.value[i].img = 'logo.svg'
|
||||
searchResults.value[i].img = ''
|
||||
console.log('获取失败 index' + i, e)
|
||||
}
|
||||
}
|
||||
|
||||
205
src/types/songList.ts
Normal file
205
src/types/songList.ts
Normal file
@@ -0,0 +1,205 @@
|
||||
import type { SongList, Songs } from '@common/types/songList'
|
||||
|
||||
// IPC 响应基础类型
|
||||
export interface IPCResponse<T = any> {
|
||||
success: boolean
|
||||
data?: T
|
||||
error?: string
|
||||
message?: string
|
||||
code?: string
|
||||
}
|
||||
|
||||
// 歌单管理相关类型定义
|
||||
export interface SongListAPI {
|
||||
// === 歌单管理 ===
|
||||
|
||||
/**
|
||||
* 创建新歌单
|
||||
*/
|
||||
create(name: string, description?: string, source?: SongList['source']): Promise<IPCResponse<{ id: string }>>
|
||||
|
||||
/**
|
||||
* 获取所有歌单
|
||||
*/
|
||||
getAll(): Promise<IPCResponse<SongList[]>>
|
||||
|
||||
/**
|
||||
* 根据ID获取歌单信息
|
||||
*/
|
||||
getById(hashId: string): Promise<IPCResponse<SongList | null>>
|
||||
|
||||
/**
|
||||
* 删除歌单
|
||||
*/
|
||||
delete(hashId: string): Promise<IPCResponse>
|
||||
|
||||
/**
|
||||
* 批量删除歌单
|
||||
*/
|
||||
batchDelete(hashIds: string[]): Promise<IPCResponse<{ success: string[]; failed: string[] }>>
|
||||
|
||||
/**
|
||||
* 编辑歌单信息
|
||||
*/
|
||||
edit(hashId: string, updates: Partial<Omit<SongList, 'id' | 'createTime'>>): Promise<IPCResponse>
|
||||
|
||||
/**
|
||||
* 更新歌单封面
|
||||
*/
|
||||
updateCover(hashId: string, coverImgUrl: string): Promise<IPCResponse>
|
||||
|
||||
/**
|
||||
* 搜索歌单
|
||||
*/
|
||||
search(keyword: string, source?: SongList['source']): Promise<IPCResponse<SongList[]>>
|
||||
|
||||
/**
|
||||
* 获取歌单统计信息
|
||||
*/
|
||||
getStatistics(): Promise<IPCResponse<{
|
||||
total: number
|
||||
bySource: Record<string, number>
|
||||
lastUpdated: string
|
||||
}>>
|
||||
|
||||
/**
|
||||
* 检查歌单是否存在
|
||||
*/
|
||||
exists(hashId: string): Promise<IPCResponse<boolean>>
|
||||
|
||||
// === 歌曲管理 ===
|
||||
|
||||
/**
|
||||
* 添加歌曲到歌单
|
||||
*/
|
||||
addSongs(hashId: string, songs: Songs[]): Promise<IPCResponse>
|
||||
|
||||
/**
|
||||
* 从歌单移除歌曲
|
||||
*/
|
||||
removeSong(hashId: string, songmid: string | number): Promise<IPCResponse<boolean>>
|
||||
|
||||
/**
|
||||
* 批量移除歌曲
|
||||
*/
|
||||
removeSongs(hashId: string, songmids: (string | number)[]): Promise<IPCResponse<{ removed: number; notFound: number }>>
|
||||
|
||||
/**
|
||||
* 清空歌单
|
||||
*/
|
||||
clearSongs(hashId: string): Promise<IPCResponse>
|
||||
|
||||
/**
|
||||
* 获取歌单中的歌曲列表
|
||||
*/
|
||||
getSongs(hashId: string): Promise<IPCResponse<readonly Songs[]>>
|
||||
|
||||
/**
|
||||
* 获取歌单歌曲数量
|
||||
*/
|
||||
getSongCount(hashId: string): Promise<IPCResponse<number>>
|
||||
|
||||
/**
|
||||
* 检查歌曲是否在歌单中
|
||||
*/
|
||||
hasSong(hashId: string, songmid: string | number): Promise<IPCResponse<boolean>>
|
||||
|
||||
/**
|
||||
* 根据ID获取歌曲
|
||||
*/
|
||||
getSong(hashId: string, songmid: string | number): Promise<IPCResponse<Songs | null>>
|
||||
|
||||
/**
|
||||
* 搜索歌单中的歌曲
|
||||
*/
|
||||
searchSongs(hashId: string, keyword: string): Promise<IPCResponse<Songs[]>>
|
||||
|
||||
/**
|
||||
* 获取歌单歌曲统计信息
|
||||
*/
|
||||
getSongStatistics(hashId: string): Promise<IPCResponse<{
|
||||
total: number
|
||||
bySinger: Record<string, number>
|
||||
byAlbum: Record<string, number>
|
||||
lastModified: string
|
||||
}>>
|
||||
|
||||
/**
|
||||
* 验证歌单完整性
|
||||
*/
|
||||
validateIntegrity(hashId: string): Promise<IPCResponse<{ isValid: boolean; issues: string[] }>>
|
||||
|
||||
/**
|
||||
* 修复歌单数据
|
||||
*/
|
||||
repairData(hashId: string): Promise<IPCResponse<{ fixed: boolean; changes: string[] }>>
|
||||
|
||||
/**
|
||||
* 强制保存歌单
|
||||
*/
|
||||
forceSave(hashId: string): Promise<IPCResponse>
|
||||
}
|
||||
|
||||
// 错误码枚举
|
||||
export enum SongListErrorCode {
|
||||
INVALID_HASH_ID = 'INVALID_HASH_ID',
|
||||
EMPTY_NAME = 'EMPTY_NAME',
|
||||
EMPTY_SOURCE = 'EMPTY_SOURCE',
|
||||
CREATE_FAILED = 'CREATE_FAILED',
|
||||
FILE_CREATE_FAILED = 'FILE_CREATE_FAILED',
|
||||
PLAYLIST_NOT_FOUND = 'PLAYLIST_NOT_FOUND',
|
||||
DELETE_FAILED = 'DELETE_FAILED',
|
||||
EMPTY_UPDATES = 'EMPTY_UPDATES',
|
||||
EDIT_FAILED = 'EDIT_FAILED',
|
||||
READ_FAILED = 'READ_FAILED',
|
||||
INIT_FAILED = 'INIT_FAILED',
|
||||
WRITE_FAILED = 'WRITE_FAILED',
|
||||
INVALID_ACTION = 'INVALID_ACTION',
|
||||
UPDATE_COVER_FAILED = 'UPDATE_COVER_FAILED',
|
||||
INVALID_DATA_FORMAT = 'INVALID_DATA_FORMAT',
|
||||
FILE_NOT_FOUND = 'FILE_NOT_FOUND',
|
||||
INVALID_SONG_ID = 'INVALID_SONG_ID',
|
||||
SAVE_FAILED = 'SAVE_FAILED',
|
||||
UNKNOWN_ERROR = 'UNKNOWN_ERROR'
|
||||
}
|
||||
|
||||
// 歌单来源类型
|
||||
export type SongListSource = 'local' | 'wy' | 'tx' | 'mg' | 'kg' | 'kw'
|
||||
|
||||
// 批量操作结果类型
|
||||
export interface BatchOperationResult {
|
||||
success: string[]
|
||||
failed: string[]
|
||||
}
|
||||
|
||||
// 歌曲移除结果类型
|
||||
export interface RemoveSongsResult {
|
||||
removed: number
|
||||
notFound: number
|
||||
}
|
||||
|
||||
// 统计信息类型
|
||||
export interface SongListStatistics {
|
||||
total: number
|
||||
bySource: Record<string, number>
|
||||
lastUpdated: string
|
||||
}
|
||||
|
||||
export interface SongStatistics {
|
||||
total: number
|
||||
bySinger: Record<string, number>
|
||||
byAlbum: Record<string, number>
|
||||
lastModified: string
|
||||
}
|
||||
|
||||
// 数据完整性检查结果
|
||||
export interface IntegrityCheckResult {
|
||||
isValid: boolean
|
||||
issues: string[]
|
||||
}
|
||||
|
||||
// 数据修复结果
|
||||
export interface RepairResult {
|
||||
fixed: boolean
|
||||
changes: string[]
|
||||
}
|
||||
@@ -3,7 +3,13 @@
|
||||
"include": ["electron.vite.config.*", "src/main/**/*", "src/preload/**/*", "src/common/**/*", "src/types/**/*"],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"baseUrl": ".",
|
||||
"types": ["electron-vite/node"],
|
||||
"moduleResolution": "bundler"
|
||||
"moduleResolution": "bundler",
|
||||
"paths": {
|
||||
"@common/*":[
|
||||
"src/common/*"
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
"src/renderer/src/**/*",
|
||||
"src/renderer/src/**/*.vue",
|
||||
"src/preload/*.d.ts",
|
||||
"src/types/**/*"
|
||||
"src/types/**/*",
|
||||
"src/common/**/*"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
|
||||
@@ -11,15 +11,163 @@ function scrollToFeatures() {
|
||||
});
|
||||
}
|
||||
|
||||
// GitHub repository configuration
|
||||
// Alist API configuration
|
||||
const ALIST_BASE_URL = 'https://alist.shiqianjiang.cn';
|
||||
const ALIST_USERNAME = 'ceruupdate';
|
||||
const ALIST_PASSWORD = '123456';
|
||||
|
||||
// GitHub repository configuration (for fallback)
|
||||
const GITHUB_REPO = 'timeshiftsauce/CeruMusic';
|
||||
const GITHUB_API_URL = `https://api.github.com/repos/${GITHUB_REPO}/releases/latest`;
|
||||
|
||||
// Cache for release data
|
||||
let releaseData = null;
|
||||
let releaseDataTimestamp = null;
|
||||
let alistToken = null;
|
||||
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
// Alist authentication
|
||||
async function getAlistToken() {
|
||||
if (alistToken) {
|
||||
return alistToken;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${ALIST_BASE_URL}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
username: ALIST_USERNAME,
|
||||
password: ALIST_PASSWORD
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 200) {
|
||||
alistToken = data.data.token;
|
||||
return alistToken;
|
||||
} else {
|
||||
throw new Error(`Alist authentication failed: ${data.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Alist authentication error:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Get available versions from Alist
|
||||
async function getAlistVersions() {
|
||||
try {
|
||||
const token = await getAlistToken();
|
||||
|
||||
const response = await fetch(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
path: '/',
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 100,
|
||||
refresh: false
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 200) {
|
||||
// Filter directories that look like version numbers
|
||||
const versions = data.data.content
|
||||
.filter(item => item.is_dir && /^v?\d+\.\d+\.\d+/.test(item.name))
|
||||
.sort((a, b) => b.name.localeCompare(a.name)); // Sort by version desc
|
||||
|
||||
return versions;
|
||||
} else {
|
||||
throw new Error(`Failed to get versions: ${data.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get Alist versions:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Get files in a specific version directory
|
||||
async function getAlistVersionFiles(version) {
|
||||
try {
|
||||
const token = await getAlistToken();
|
||||
|
||||
const response = await fetch(`${ALIST_BASE_URL}/api/fs/list`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
path: `/${version}`,
|
||||
password: '',
|
||||
page: 1,
|
||||
per_page: 100,
|
||||
refresh: false
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 200) {
|
||||
return data.data.content.filter(item => !item.is_dir);
|
||||
} else {
|
||||
throw new Error(`Failed to get version files: ${data.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get version files:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// Get direct download URL from Alist
|
||||
async function getAlistDownloadUrl(version, fileName) {
|
||||
try {
|
||||
const token = await getAlistToken();
|
||||
const filePath = `/${version}/${fileName}`;
|
||||
|
||||
const response = await fetch(`${ALIST_BASE_URL}/api/fs/get`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': token,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
path: filePath
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 200) {
|
||||
const fileInfo = data.data;
|
||||
|
||||
// Try different URL formats
|
||||
if (fileInfo.raw_url) {
|
||||
return fileInfo.raw_url;
|
||||
} else if (fileInfo.sign) {
|
||||
return `${ALIST_BASE_URL}/d${filePath}?sign=${fileInfo.sign}`;
|
||||
} else {
|
||||
return `${ALIST_BASE_URL}/d${filePath}`;
|
||||
}
|
||||
} else {
|
||||
throw new Error(`Failed to get download URL: ${data.message}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get Alist download URL:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Download functionality
|
||||
async function downloadApp(platform) {
|
||||
const button = event.target;
|
||||
@@ -35,38 +183,53 @@ async function downloadApp(platform) {
|
||||
button.disabled = true;
|
||||
|
||||
try {
|
||||
// Get latest release data
|
||||
const release = await getLatestRelease();
|
||||
// Try Alist first
|
||||
const versions = await getAlistVersions();
|
||||
|
||||
if (!release) {
|
||||
throw new Error('无法获取最新版本信息');
|
||||
if (versions.length > 0) {
|
||||
const latestVersion = versions[0];
|
||||
const files = await getAlistVersionFiles(latestVersion.name);
|
||||
|
||||
// Find the appropriate file for the platform
|
||||
const fileName = findFileForPlatform(files, platform);
|
||||
|
||||
if (fileName) {
|
||||
const downloadUrl = await getAlistDownloadUrl(latestVersion.name, fileName);
|
||||
|
||||
// Show success notification
|
||||
showNotification(`正在下载 ${getPlatformName(platform)} 版本 ${latestVersion.name}...`, 'success');
|
||||
|
||||
// Start download
|
||||
window.open(downloadUrl, '_blank');
|
||||
|
||||
// Track download
|
||||
trackDownload(platform, latestVersion.name);
|
||||
|
||||
return; // Success, exit function
|
||||
}
|
||||
}
|
||||
|
||||
// Find the appropriate download asset
|
||||
const downloadUrl = findDownloadAsset(release.assets, platform);
|
||||
|
||||
if (!downloadUrl) {
|
||||
throw new Error(`暂无 ${getPlatformName(platform)} 版本下载`);
|
||||
}
|
||||
|
||||
// Show success notification
|
||||
showNotification(`正在下载 ${getPlatformName(platform)} 版本 v${release.tag_name}...`, 'success');
|
||||
|
||||
// Start download
|
||||
window.open('https://gh.bugdey.us.kg/'+downloadUrl, '_blank');
|
||||
|
||||
// Track download
|
||||
trackDownload(platform, release.tag_name);
|
||||
// Fallback to GitHub if Alist fails
|
||||
console.log('Alist download failed, trying GitHub fallback...');
|
||||
await downloadFromGitHub(platform);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Download error:', error);
|
||||
showNotification(`下载失败: ${error.message}`, 'error');
|
||||
|
||||
// Fallback to GitHub releases page
|
||||
setTimeout(() => {
|
||||
showNotification('正在跳转到GitHub下载页面...', 'info');
|
||||
window.open(`https://gh.bugdey.us.kg/https://github.com/${GITHUB_REPO}/releases/latest`, '_blank');
|
||||
}, 2000);
|
||||
// Try GitHub fallback
|
||||
try {
|
||||
console.log('Trying GitHub fallback...');
|
||||
await downloadFromGitHub(platform);
|
||||
} catch (fallbackError) {
|
||||
console.error('GitHub fallback also failed:', fallbackError);
|
||||
showNotification(`下载失败: ${error.message}`, 'error');
|
||||
|
||||
// Final fallback to GitHub releases page
|
||||
setTimeout(() => {
|
||||
showNotification('正在跳转到GitHub下载页面...', 'info');
|
||||
window.open(`https://github.com/${GITHUB_REPO}/releases/latest`, '_blank');
|
||||
}, 2000);
|
||||
}
|
||||
} finally {
|
||||
// Restore button state
|
||||
setTimeout(() => {
|
||||
@@ -76,6 +239,30 @@ async function downloadApp(platform) {
|
||||
}
|
||||
}
|
||||
|
||||
// GitHub fallback function
|
||||
async function downloadFromGitHub(platform) {
|
||||
const release = await getLatestRelease();
|
||||
|
||||
if (!release) {
|
||||
throw new Error('无法获取最新版本信息');
|
||||
}
|
||||
|
||||
const downloadUrl = findDownloadAsset(release.assets, platform);
|
||||
|
||||
if (!downloadUrl) {
|
||||
throw new Error(`暂无 ${getPlatformName(platform)} 版本下载`);
|
||||
}
|
||||
|
||||
// Show success notification
|
||||
showNotification(`正在下载 ${getPlatformName(platform)} 版本 v${release.tag_name}...`, 'success');
|
||||
|
||||
// Start download
|
||||
window.open(downloadUrl, '_blank');
|
||||
|
||||
// Track download
|
||||
trackDownload(platform, release.tag_name);
|
||||
}
|
||||
|
||||
// Get latest release from GitHub API
|
||||
async function getLatestRelease() {
|
||||
// Check cache first
|
||||
@@ -104,6 +291,64 @@ async function getLatestRelease() {
|
||||
}
|
||||
}
|
||||
|
||||
// Find appropriate file for platform from Alist files
|
||||
function findFileForPlatform(files, platform) {
|
||||
if (!files || !Array.isArray(files)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Define file patterns for each platform
|
||||
const patterns = {
|
||||
windows: [
|
||||
/\\.exe$/i,
|
||||
/windows.*\\.zip$/i,
|
||||
/win32.*\\.zip$/i,
|
||||
/win.*x64.*\\.zip$/i
|
||||
],
|
||||
macos: [
|
||||
/\\.dmg$/i,
|
||||
/darwin.*\\.zip$/i,
|
||||
/macos.*\\.zip$/i,
|
||||
/mac.*\\.zip$/i,
|
||||
/osx.*\\.zip$/i
|
||||
],
|
||||
linux: [
|
||||
/\\.AppImage$/i,
|
||||
/linux.*\\.zip$/i,
|
||||
/linux.*\\.tar\\.gz$/i,
|
||||
/\\.deb$/i,
|
||||
/\\.rpm$/i
|
||||
]
|
||||
};
|
||||
|
||||
const platformPatterns = patterns[platform] || [];
|
||||
|
||||
// Try to find exact match
|
||||
for (const pattern of platformPatterns) {
|
||||
const file = files.find(file => pattern.test(file.name));
|
||||
if (file) {
|
||||
return file.name;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: look for any file that might match the platform
|
||||
const fallbackPatterns = {
|
||||
windows: /win|exe/i,
|
||||
macos: /mac|darwin|dmg/i,
|
||||
linux: /linux|appimage|deb|rpm/i
|
||||
};
|
||||
|
||||
const fallbackPattern = fallbackPatterns[platform];
|
||||
if (fallbackPattern) {
|
||||
const file = files.find(file => fallbackPattern.test(file.name));
|
||||
if (file) {
|
||||
return file.name;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find appropriate download asset based on platform
|
||||
function findDownloadAsset(assets, platform) {
|
||||
if (!assets || !Array.isArray(assets)) {
|
||||
@@ -460,6 +705,36 @@ window.addEventListener('error', (e) => {
|
||||
// Update version information on page
|
||||
async function updateVersionInfo() {
|
||||
try {
|
||||
// Try to get version info from Alist first
|
||||
const versions = await getAlistVersions();
|
||||
|
||||
if (versions.length > 0) {
|
||||
const latestVersion = versions[0];
|
||||
const versionElement = document.querySelector('.version');
|
||||
const versionInfoElement = document.querySelector('.version-info p');
|
||||
|
||||
if (versionElement) {
|
||||
versionElement.textContent = latestVersion.name;
|
||||
}
|
||||
|
||||
if (versionInfoElement) {
|
||||
const modifyDate = new Date(latestVersion.modified);
|
||||
const formattedDate = modifyDate.toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: 'long'
|
||||
});
|
||||
versionInfoElement.innerHTML = `当前版本: <span class="version">${latestVersion.name}</span> | 更新时间: ${formattedDate}`;
|
||||
}
|
||||
|
||||
// Update download button text with file info from Alist
|
||||
const files = await getAlistVersionFiles(latestVersion.name);
|
||||
updateDownloadButtonsWithAlistFiles(files);
|
||||
|
||||
return; // Success, exit function
|
||||
}
|
||||
|
||||
// Fallback to GitHub if Alist fails
|
||||
console.log('Alist version info failed, trying GitHub fallback...');
|
||||
const release = await getLatestRelease();
|
||||
if (release) {
|
||||
const versionElement = document.querySelector('.version');
|
||||
@@ -486,6 +761,29 @@ async function updateVersionInfo() {
|
||||
}
|
||||
}
|
||||
|
||||
// Update download buttons with Alist file information
|
||||
function updateDownloadButtonsWithAlistFiles(files) {
|
||||
if (!files || !Array.isArray(files)) return;
|
||||
|
||||
const downloadCards = document.querySelectorAll('.download-card');
|
||||
const platforms = ['windows', 'macos', 'linux'];
|
||||
|
||||
downloadCards.forEach((card, index) => {
|
||||
const platform = platforms[index];
|
||||
const fileName = findFileForPlatform(files, platform);
|
||||
|
||||
if (fileName) {
|
||||
const file = files.find(f => f.name === fileName);
|
||||
const button = card.querySelector('.btn-download');
|
||||
const sizeText = formatFileSize(file.size);
|
||||
const originalText = button.innerHTML;
|
||||
|
||||
// Add file size info
|
||||
button.innerHTML = originalText.replace(/下载 \..*?$/, `下载 .${getFileExtension(fileName)} (${sizeText})`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update download buttons with asset information
|
||||
function updateDownloadButtonsWithAssets(assets) {
|
||||
if (!assets || !Array.isArray(assets)) return;
|
||||
|
||||
Reference in New Issue
Block a user