mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-24 03:37:47 +08:00
Merge pull request #172 from aL1CesT/feat/desktop-gui
桌面端:把半成品的 Avalonia 应用补完,支持酷狗 .kgg 解密,默认裁剪到 51 MB
This commit is contained in:
74 files changed
+8367
-547
No files matched your search
@@ -43,6 +43,59 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.date.outputs.date }}
|
||||
|
||||
# 桌面端构建(目前只发布 Windows,见 README 的说明)
|
||||
build-desktop:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Get build version
|
||||
id: date
|
||||
run: echo "date=$(Get-Date -Format 'yyyyMMdd')${{github.run_number}}" >> $env:GITHUB_OUTPUT
|
||||
shell: pwsh
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
- name: Publish Desktop (win-x64)
|
||||
working-directory: ./src/ZonyLrcTools.Desktop
|
||||
run: |
|
||||
dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true -p:UseAppHost=true -p:DebugType=none --self-contained true
|
||||
if ($LASTEXITCODE -ne 0) { throw '桌面端发布失败' }
|
||||
shell: pwsh
|
||||
# 单文件发布仍需附带 SQLite 原生库、配置模板及第三方许可声明。
|
||||
- name: Verify Desktop publish output
|
||||
working-directory: ./src/ZonyLrcTools.Desktop
|
||||
run: |
|
||||
$publish = './bin/Release/net10.0/win-x64/publish'
|
||||
$exe = Join-Path $publish 'ZonyLrcTools.Desktop.exe'
|
||||
$sqlite = Join-Path $publish 'e_sqlite3.dll'
|
||||
if (-not (Test-Path $exe)) { throw "缺少主程序: $exe" }
|
||||
if (-not (Test-Path $sqlite)) { throw "缺少 SQLite 原生库: $sqlite(.kgg 解密依赖它)" }
|
||||
if (-not (Test-Path (Join-Path $publish 'config.yaml'))) { throw '缺少 config.yaml 模板' }
|
||||
if (-not (Test-Path (Join-Path $publish 'THIRD-PARTY-NOTICES.md'))) { throw '缺少第三方许可声明' }
|
||||
|
||||
$totalMb = [math]::Round(((Get-ChildItem $publish -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1MB), 1)
|
||||
Write-Host "publish 目录校验通过:$((Get-ChildItem $publish -File).Count) 个文件,共 $totalMb MB"
|
||||
if ($totalMb -gt 90) {
|
||||
throw "publish 目录有 $totalMb MB,超过 90 MB 上限;这通常意味着 PublishTrimmed 被关掉了"
|
||||
}
|
||||
shell: pwsh
|
||||
- name: Package Desktop
|
||||
working-directory: ./src/ZonyLrcTools.Desktop
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path ./TempFiles | Out-Null
|
||||
Compress-Archive -Path ./bin/Release/net10.0/win-x64/publish/* -DestinationPath ./TempFiles/ZonyLrcTools.Desktop_win-x64_${{ steps.date.outputs.date }}.zip -Force
|
||||
shell: pwsh
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
retention-days: 90
|
||||
name: release-files-desktop
|
||||
path: ./src/ZonyLrcTools.Desktop/TempFiles
|
||||
outputs:
|
||||
version: ${{ steps.date.outputs.date }}
|
||||
|
||||
# macOS 构建(在 macOS runner 上,支持 ad-hoc 签名)
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
@@ -84,7 +137,7 @@ jobs:
|
||||
# Release Job - 合并所有平台的构建产物
|
||||
release:
|
||||
if: github.event_name == 'push'
|
||||
needs: [build-linux-windows, build-macos]
|
||||
needs: [build-linux-windows, build-macos, build-desktop]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout for release notes
|
||||
@@ -99,6 +152,11 @@ jobs:
|
||||
with:
|
||||
name: release-files-macos
|
||||
path: ./TempFiles
|
||||
- name: Download Desktop artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-files-desktop
|
||||
path: ./TempFiles
|
||||
- name: Upload Release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
|
||||
@@ -41,6 +41,9 @@
|
||||
<!-- Misc -->
|
||||
<PackageVersion Include="Ude.NetStandard" Version="1.2.0" />
|
||||
<PackageVersion Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageVersion Include="Microsoft.Data.Sqlite" Version="10.0.1" />
|
||||
<!-- 显式提升 SQLitePCLRaw 的原生包:Microsoft.Data.Sqlite 10.0.1 默认带下来的 2.1.11 有已知高危漏洞(GHSA-2m69-gcr7-jv3q)。 -->
|
||||
<PackageVersion Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.5" />
|
||||
<!-- Avalonia -->
|
||||
<PackageVersion Include="Avalonia" Version="11.2.3" />
|
||||
<PackageVersion Include="Avalonia.Desktop" Version="11.2.3" />
|
||||
@@ -48,6 +51,8 @@
|
||||
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" />
|
||||
<PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" />
|
||||
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
|
||||
<!-- Avalonia 的 Linux D-Bus 依赖:使用包含安全修复的兼容分支。 -->
|
||||
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.21.3" />
|
||||
<!-- MVVM -->
|
||||
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
|
||||
<!-- Localization -->
|
||||
|
||||
@@ -8,7 +8,7 @@ English | [简体中文](./docs/zh_CN.md)
|
||||
|
||||
# Introduction
|
||||
|
||||
ZonyLrcToolX 4 is a cross-platform lyrics download tool based on CEF. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
|
||||
ZonyLrcToolX 4 is a cross-platform lyrics download tool with a .NET 10 CLI and an Avalonia desktop application. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
|
||||
|
||||
🚧 The current version is under development.
|
||||
🚧 If you want to see working code, please switch to the dev branch.
|
||||
@@ -31,6 +31,20 @@ ZonyLrcTools.Cli --help
|
||||
# Usage
|
||||
Detailed usage instructions have been moved to a new documentation site. Please visit [https://docs.myzony.com](https://docs.myzony.com) for complete documentation.
|
||||
|
||||
## Run a contribution locally
|
||||
|
||||
Fork pull requests can be checked out without merging or obtaining write access to the contributor's repository. From the repository root, use a new branch and directory (replace `172` with the PR number):
|
||||
|
||||
```bash
|
||||
git fetch origin pull/172/head
|
||||
git worktree add ../ZonyLrcToolsX-pr-172 -b review/pr-172 FETCH_HEAD
|
||||
cd ../ZonyLrcToolsX-pr-172
|
||||
dotnet run --project src/ZonyLrcTools.Desktop -c Release
|
||||
```
|
||||
|
||||
Requires .NET SDK 10. Local changes do not update the PR until explicitly committed and pushed. See [desktop notes](./docs/en_US.md#desktop-development) for publishing, configuration and manual verification.
|
||||
|
||||
|
||||
# Donation
|
||||
[爱发电](https://afdian.net/a/zony-lrc-tools)
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# Third-Party Notices
|
||||
|
||||
This project contains code derived from the following MIT-licensed works.
|
||||
The MIT licence requires the copyright notice and permission notice to be
|
||||
included in all copies or substantial portions of the software, so they are
|
||||
reproduced in full below.
|
||||
|
||||
---
|
||||
|
||||
## kgg-dec — KuGou `.kgg` decryption reference implementation
|
||||
|
||||
Source: <https://github.com/lizipeng0013/kgg-dec.mirror>
|
||||
|
||||
Used by: `src/ZonyLrcTools.Common/MusicDecryption/Kugou/`
|
||||
(`TcTea.cs`, `EkeyDecoder.cs`, `Qmc2Cipher.cs`, `KugouEkeyDatabase.cs`,
|
||||
`KggMusicDecryptor.cs`)
|
||||
|
||||
The C# classes above are a port of the TC-TEA / ekey / QMC2 / KGMusicV3.db
|
||||
algorithms from that project. They were rewritten for this codebase (different
|
||||
structure, streaming I/O, cancellation support), but the cryptographic
|
||||
constants and the database page-decryption scheme originate there.
|
||||
|
||||
```
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 LSR
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
```
|
||||
+19
-1
@@ -8,7 +8,7 @@ English | [简体中文](./zh_CN.md)
|
||||
|
||||
# Introduction
|
||||
|
||||
ZonyLrcToolX 4 is a cross-platform lyrics download tool based on CEF. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
|
||||
ZonyLrcToolX 4 is a cross-platform lyrics download tool with a .NET 10 CLI and an Avalonia desktop application. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
|
||||
|
||||
🚧 The current version is under development.
|
||||
🚧 If you want to see working code, please switch to the dev branch.
|
||||
@@ -31,6 +31,24 @@ ZonyLrcTools.Cli --help
|
||||
# Usage
|
||||
Detailed usage instructions have been moved to a new documentation site. Please visit [https://docs.myzony.com](https://docs.myzony.com) for complete documentation.
|
||||
|
||||
## Desktop development
|
||||
|
||||
Requires .NET SDK 10. Run from the repository root:
|
||||
|
||||
```bash
|
||||
dotnet run --project src/ZonyLrcTools.Desktop -c Release
|
||||
dotnet publish src/ZonyLrcTools.Desktop -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
|
||||
```
|
||||
|
||||
CI distributes Windows x64. For local builds, choose the appropriate RID, such as `osx-arm64`. RID-specific desktop builds enable trimming by default; pass `-p:PublishTrimmed=false` to disable it. Publish success is not a substitute for testing the target OS. Keep the entire publish directory, including native SQLite/Avalonia libraries, configuration and `THIRD-PARTY-NOTICES.md`.
|
||||
|
||||
Settings use the writable executable directory, falling back to the user's application data directory. Saving preserves unknown YAML fields and comments; unsupported anchored or multiline values fail without overwriting the file. `netease.session.json` contains login credentials: never share or commit it. Unix restricts it to the current user; Windows inherits directory permissions. Relative block-word paths resolve against the current working directory.
|
||||
|
||||
KGG decryption requires a matching `KGMusicV3.db` containing that file's key. Automatic database discovery covers Windows KuGou locations; a matching database can also be selected manually. Existing decrypted audio is not overwritten and is reported as an output conflict. Cancellation prevents publishing partial output, but providers and third-party decryptors without cancellation support must finish their in-flight call first.
|
||||
|
||||
Before merging, manually check navigation, language/theme changes, local lyrics and cover downloads, cancel/restart, QR login/logout/restart, settings save/restart, and KGG with a real matching database. Synthetic decryption tests do not establish compatibility with every client format.
|
||||
|
||||
|
||||
# Donation
|
||||
[爱发电](https://afdian.net/a/zony-lrc-tools)
|
||||
|
||||
|
||||
+19
-1
@@ -8,7 +8,7 @@
|
||||
|
||||
# 简介
|
||||
|
||||
ZonyLrcToolX 4 是一个基于 CEF 的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。
|
||||
ZonyLrcToolX 4 是一个提供 .NET 10 CLI 和 Avalonia 桌面界面的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。
|
||||
|
||||
🚧 当前版本正在开发当中。
|
||||
🚧 如果你想查看可以工作的代码,请切换到 dev 分支。
|
||||
@@ -32,6 +32,24 @@ ZonyLrcTools.Cli --help
|
||||
|
||||
软件的具体使用方法已经迁移到了全新的文档站点,请跳转到 [https://docs.myzony.com](https://docs.myzony.com),里面包含完整的说明文档。
|
||||
|
||||
## 桌面端本地开发
|
||||
|
||||
需要 .NET SDK 10。在仓库根目录执行:
|
||||
|
||||
```bash
|
||||
dotnet run --project src/ZonyLrcTools.Desktop -c Release
|
||||
dotnet publish src/ZonyLrcTools.Desktop -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
|
||||
```
|
||||
|
||||
CI 分发 Windows x64 版本。本机发布请选择对应 RID,例如 Apple Silicon 使用 `osx-arm64`。指定 RID 时桌面端默认开启裁剪,使用 `-p:PublishTrimmed=false` 可以关闭。发布成功不等于目标系统上的功能验收通过。分发时保留整个发布目录,包括 SQLite/Avalonia 原生库、配置和 `THIRD-PARTY-NOTICES.md`。
|
||||
|
||||
配置优先保存在可写的程序目录,否则回退到用户应用数据目录。保存时保留未知 YAML 字段和注释;无法安全修改的锚点或多行值会明确报错,不覆盖原文件。`netease.session.json` 包含登录凭据,不要分享或提交到仓库。Unix 仅允许当前用户读写,Windows 继承目录权限。屏蔽词字典的相对路径以当前工作目录为基准。
|
||||
|
||||
KGG 解密需要包含对应文件密钥的 `KGMusicV3.db`。自动查找覆盖 Windows 酷狗目录,也可手动选择匹配的数据库。已有解密音频不会被覆盖,而是报告输出冲突。取消后不会发布不完整文件;不支持取消的歌词源、封面源及第三方解密器仍需等待当前调用返回。
|
||||
|
||||
合并前请手动检查:导航与语言/主题切换、本地歌词和封面下载、取消后重启任务、扫码登录/退出/重启、设置保存后重启,以及真实 KGG 配合匹配数据库的解密。合成解密测试不能代替所有客户端格式的兼容性验证。fork PR 的独立检出步骤见 [README](../README.md#run-a-contribution-locally)。
|
||||
|
||||
|
||||
# 捐赠
|
||||
[爱发电](https://afdian.net/a/zony-lrc-tools)
|
||||
|
||||
|
||||
@@ -41,13 +41,15 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
|
||||
{
|
||||
_logger.LogInformation("开始扫描文件夹,请稍等...");
|
||||
|
||||
var files = (await _fileScanner.ScanAsync(Source, DecryptoFactory.KnownExtensions.Select(x => $"*{x}")))
|
||||
var files = (await _fileScanner.ScanAsync(Source,
|
||||
DecryptoFactory.KnownExtensions.Append(".kgg").Distinct().Select(x => $"*{x}")))
|
||||
.SelectMany(f => f.FilePaths)
|
||||
.ToList();
|
||||
|
||||
_logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。");
|
||||
|
||||
var wrapTask = new WarpTask(4);
|
||||
// 等待转换结束后释放并发控制资源。
|
||||
using var wrapTask = new WarpTask(4);
|
||||
var tasks = files.Select(path => wrapTask.RunAsync(async () =>
|
||||
{
|
||||
_logger.LogInformation($"开始转换文件:{path}");
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
|
||||
namespace ZonyLrcTools.Common.Album;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
|
||||
{
|
||||
private readonly IEnumerable<IAlbumProvider> _albumProviders;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<IAlbumProvider> AvailableProviders => new Lazy<IEnumerable<IAlbumProvider>>(() =>
|
||||
{
|
||||
return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
|
||||
@@ -18,6 +19,9 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
|
||||
|
||||
private readonly IWarpLogger _logger;
|
||||
|
||||
/// <summary>
|
||||
/// 创建专辑封面下载器。
|
||||
/// </summary>
|
||||
public AlbumDownloader(IEnumerable<IAlbumProvider> albumProviders,
|
||||
IWarpLogger logger)
|
||||
{
|
||||
@@ -25,44 +29,110 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
Func<MusicInfo, Task>? callback = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _logger.InfoAsync("开始下载专辑图像数据...");
|
||||
|
||||
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
|
||||
if (provider == null)
|
||||
foreach (var info in needDownloadMusicInfos)
|
||||
{
|
||||
return;
|
||||
info.IsSuccessful = false;
|
||||
}
|
||||
|
||||
var warpTask = new WarpTask(parallelCount);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
|
||||
|
||||
if (parallelCount <= 0)
|
||||
{
|
||||
parallelCount = 1;
|
||||
}
|
||||
|
||||
using var warpTask = new WarpTask(parallelCount);
|
||||
var warpTaskList = needDownloadMusicInfos.Select(info =>
|
||||
warpTask.RunAsync(() =>
|
||||
Task.Run(async () =>
|
||||
{
|
||||
_logger.LogSuccessful(info);
|
||||
|
||||
try
|
||||
{
|
||||
var album = await provider.DownloadAsync(info.Name, info.Artist);
|
||||
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
|
||||
if (File.Exists(filePath) || album.Length <= 0)
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var filePath = Path.ChangeExtension(info.FilePath, ".png");
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
info.IsSuccessful = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (provider == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album);
|
||||
var album = await provider.DownloadAsync(info.Name, info.Artist);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (album.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var temporaryPath = $"{filePath}.{Guid.NewGuid():N}.tmp";
|
||||
try
|
||||
{
|
||||
await File.WriteAllBytesAsync(temporaryPath, album, cancellationToken);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// 完整写入后再发布,且不覆盖其他任务或用户刚创建的封面。
|
||||
try
|
||||
{
|
||||
File.Move(temporaryPath, filePath);
|
||||
}
|
||||
catch (IOException) when (File.Exists(filePath))
|
||||
{
|
||||
// 目标已由其他任务生成,保留已有封面。
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
|
||||
info.IsSuccessful = true;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
_logger.LogWarningInfo(ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _logger.ErrorAsync("下载专辑图像失败。", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (callback != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await callback(info);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _logger.WarnAsync("处理专辑下载回调失败。", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}, cancellationToken), cancellationToken));
|
||||
|
||||
await Task.WhenAll(warpTaskList);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
namespace ZonyLrcTools.Common.Album;
|
||||
namespace ZonyLrcTools.Common.Album;
|
||||
|
||||
/// <summary>
|
||||
/// 下载歌曲对应的专辑封面。
|
||||
/// </summary>
|
||||
public interface IAlbumDownloader
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用给定的歌曲信息下载专辑图像,并输出到音乐文件同目录。
|
||||
/// </summary>
|
||||
/// <param name="needDownloadMusicInfos">需要下载专辑图像的歌曲信息。</param>
|
||||
/// <param name="parallelCount">下载线程/并发量。</param>
|
||||
/// <param name="callback">单首歌曲处理完成之后的回调方法。</param>
|
||||
/// <param name="cancellationToken">任务取消标记。</param>
|
||||
Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
|
||||
int parallelCount = 2,
|
||||
Func<MusicInfo, Task>? callback = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 可用的专辑封面来源。
|
||||
/// </summary>
|
||||
IEnumerable<IAlbumProvider> AvailableProviders { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
|
||||
@@ -19,25 +17,19 @@ namespace ZonyLrcTools.Common.Infrastructure.Extensions
|
||||
/// <param name="e">异常实例,可为空。</param>
|
||||
public static void LogWarningWithErrorCode(this IWarpLogger logger, int errorCode, Exception? e = null)
|
||||
{
|
||||
logger.WarnAsync($"错误代码: {errorCode}\n堆栈异常: {e?.StackTrace}").GetAwaiter().GetResult();
|
||||
logger.WarnAsync($"错误代码: {errorCode}", e).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。
|
||||
/// 记录错误码与异常,不重新抛出业务异常。
|
||||
/// </summary>
|
||||
/// <param name="logger">日志记录器的实例。</param>
|
||||
/// <param name="exception">错误码异常实例。</param>
|
||||
public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception)
|
||||
{
|
||||
if (exception.ErrorCode < 50000)
|
||||
{
|
||||
throw exception;
|
||||
}
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}");
|
||||
sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}");
|
||||
logger.WarnAsync(sb.ToString()).GetAwaiter().GetResult();
|
||||
logger.WarnAsync(
|
||||
$"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}",
|
||||
exception).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -18,59 +18,73 @@ namespace ZonyLrcTools.Common.Infrastructure.Network
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<string> PostAsync(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null)
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption);
|
||||
var responseContentString = await responseMessage.Content.ReadAsStringAsync();
|
||||
using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption,
|
||||
cancellationToken: cancellationToken);
|
||||
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
return ValidateHttpResponse(responseMessage, parameters, responseContentString);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<TResponse> PostAsync<TResponse>(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null)
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var responseString = await PostAsync(url, parameters, isQueryStringParam, requestOption);
|
||||
var responseString = await PostAsync(url, parameters, isQueryStringParam, requestOption,
|
||||
cancellationToken: cancellationToken);
|
||||
return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null)
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var parametersStr = isQueryStringParam ? BuildQueryString(parameters) : BuildJsonBodyString(parameters);
|
||||
var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
|
||||
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
|
||||
requestMessage.Content = new StringContent(parametersStr);
|
||||
|
||||
requestOption?.Invoke(requestMessage);
|
||||
|
||||
return await BuildHttpClient().SendAsync(requestMessage);
|
||||
using var client = BuildHttpClient();
|
||||
return await client.SendAsync(requestMessage, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<string> GetAsync(string url,
|
||||
object? parameters = null,
|
||||
Action<HttpRequestMessage>? requestOption = null)
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var requestParamsStr = BuildQueryString(parameters);
|
||||
var requestMsg = new HttpRequestMessage(HttpMethod.Get, new Uri($"{url}?{requestParamsStr}"));
|
||||
using var requestMsg = new HttpRequestMessage(HttpMethod.Get, new Uri($"{url}?{requestParamsStr}"));
|
||||
requestOption?.Invoke(requestMsg);
|
||||
|
||||
using var responseMessage = await BuildHttpClient().SendAsync(requestMsg);
|
||||
var responseContentString = await responseMessage.Content.ReadAsStringAsync();
|
||||
using var client = BuildHttpClient();
|
||||
using var responseMessage = await client.SendAsync(requestMsg, cancellationToken);
|
||||
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
return ValidateHttpResponse(responseMessage, parameters, responseContentString);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<TResponse> GetAsync<TResponse>(string url,
|
||||
object? parameters = null,
|
||||
Action<HttpRequestMessage>? requestOption = null)
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var responseString = await GetAsync(url, parameters, requestOption);
|
||||
var responseString = await GetAsync(url, parameters, requestOption, cancellationToken: cancellationToken);
|
||||
return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
/// <param name="parameters">请求的参数。</param>
|
||||
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
|
||||
/// <param name="requestOption">请求时的配置动作。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>服务端的响应结果。</returns>
|
||||
ValueTask<string> PostAsync(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null);
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的配置执行 POST 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
|
||||
@@ -25,17 +27,28 @@
|
||||
/// <param name="parameters">请求的参数。</param>
|
||||
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
|
||||
/// <param name="requestOption">请求时的配置动作。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
|
||||
/// <returns>服务端的响应结果。</returns>
|
||||
ValueTask<TResponse> PostAsync<TResponse>(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null);
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 执行 POST 请求,由调用方释放返回的响应。
|
||||
/// </summary>
|
||||
/// <param name="url">请求地址。</param>
|
||||
/// <param name="parameters">请求参数。</param>
|
||||
/// <param name="isQueryStringParam">是否将参数编码为查询字符串。</param>
|
||||
/// <param name="requestOption">请求配置动作。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
|
||||
object? parameters = null,
|
||||
bool isQueryStringParam = false,
|
||||
Action<HttpRequestMessage>? requestOption = null);
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的配置执行 GET 请求,并以 <see cref="string"/> 作为返回值。
|
||||
@@ -43,10 +56,12 @@
|
||||
/// <param name="url">请求的 URL 地址。</param>
|
||||
/// <param name="parameters">请求的参数。</param>
|
||||
/// <param name="requestOption">请求时的配置动作。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>服务端的响应结果。</returns>
|
||||
ValueTask<string> GetAsync(string url,
|
||||
object? parameters = null,
|
||||
Action<HttpRequestMessage>? requestOption = null);
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 根据指定的配置执行 GET 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
|
||||
@@ -54,11 +69,13 @@
|
||||
/// <param name="url">请求的 URL 地址。</param>
|
||||
/// <param name="parameters">请求的参数。</param>
|
||||
/// <param name="requestOption">请求时的配置动作。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
|
||||
/// <returns>服务端的响应结果。</returns>
|
||||
ValueTask<TResponse> GetAsync<TResponse>(
|
||||
string url,
|
||||
object? parameters = null,
|
||||
Action<HttpRequestMessage>? requestOption = null);
|
||||
Action<HttpRequestMessage>? requestOption = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.Immutable;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
@@ -42,85 +42,152 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
|
||||
Func<MusicInfo, Task>? callback = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _logger.InfoAsync("开始下载歌词文件数据...");
|
||||
foreach (var info in needDownloadMusicInfos)
|
||||
{
|
||||
info.IsSuccessful = false;
|
||||
info.IsPruneMusic = false;
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var providers = AvailableProviders.ToArray();
|
||||
if (parallelCount <= 0)
|
||||
{
|
||||
parallelCount = 1;
|
||||
}
|
||||
|
||||
var warpTask = new WarpTask(parallelCount);
|
||||
using var warpTask = new WarpTask(parallelCount);
|
||||
var downloadTasks = needDownloadMusicInfos.Select(info =>
|
||||
warpTask.RunAsync(() =>
|
||||
Task.Run(async () =>
|
||||
{
|
||||
// Try to download lyrics from all available providers.
|
||||
foreach (var lyricsProvider in AvailableProviders)
|
||||
try
|
||||
{
|
||||
await DownloadAndWriteLyricsAsync(lyricsProvider, info);
|
||||
var isFinished = false;
|
||||
var hasProviderError = providers.Length == 0;
|
||||
|
||||
if (!info.IsSuccessful) continue;
|
||||
_logger.LogSuccessful(info);
|
||||
break;
|
||||
foreach (var lyricsProvider in providers)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info, cancellationToken);
|
||||
if (result == LyricsDownloadResult.Success)
|
||||
{
|
||||
isFinished = true;
|
||||
break;
|
||||
}
|
||||
|
||||
hasProviderError |= result == LyricsDownloadResult.Failed;
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!isFinished)
|
||||
{
|
||||
// 只有所有来源均返回空结果时,才按纯音乐处理。
|
||||
info.IsSuccessful = !hasProviderError;
|
||||
info.IsPruneMusic = !hasProviderError;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (callback != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await callback(info);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _logger.WarnAsync("处理歌曲下载回调失败。", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (callback != null) await callback(info);
|
||||
}, cancellationToken), cancellationToken));
|
||||
|
||||
await Task.WhenAll(downloadTasks);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var successfulCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: false });
|
||||
var skippedCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: true });
|
||||
var failedCount = needDownloadMusicInfos.Count(m => m.IsSuccessful == false);
|
||||
await _logger.InfoAsync($"歌词数据下载完成,成功: {successfulCount} 跳过(纯音乐): {skippedCount} 失败{failedCount}。");
|
||||
await LogFailedSongFilesInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.Now:yyyyMMddHHmmss}.txt"), needDownloadMusicInfos);
|
||||
await LogFailedSongFilesInfoAsync(
|
||||
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.UtcNow:yyyyMMddHHmmss}.txt"),
|
||||
needDownloadMusicInfos, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info)
|
||||
private async Task<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var lyrics = await provider.DownloadAsync(info.Name, info.Artist);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// 空结果只表示当前来源未找到歌词,继续尝试其他来源。
|
||||
if (lyrics.IsPruneMusic)
|
||||
{
|
||||
info.IsSuccessful = true;
|
||||
info.IsPruneMusic = true;
|
||||
return;
|
||||
return LyricsDownloadResult.Empty;
|
||||
}
|
||||
|
||||
var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
|
||||
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc");
|
||||
// 编码成功后再创建文件,避免配置错误破坏原歌词。
|
||||
var content = Utf8ToSelectedEncoding(lyrics);
|
||||
|
||||
if (File.Exists(newLyricsFilePath))
|
||||
var newLyricsFilePath = Path.ChangeExtension(info.FilePath, ".lrc");
|
||||
var temporaryPath = $"{newLyricsFilePath}.{Guid.NewGuid():N}.tmp";
|
||||
try
|
||||
{
|
||||
File.Delete(newLyricsFilePath);
|
||||
await File.WriteAllBytesAsync(temporaryPath, content, cancellationToken);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(temporaryPath, newLyricsFilePath, overwrite: true);
|
||||
}
|
||||
|
||||
// Write lyrics to file.
|
||||
await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write))
|
||||
finally
|
||||
{
|
||||
await using (var binaryWriter = new BinaryWriter(fileStream, Encoding.UTF8))
|
||||
{
|
||||
binaryWriter.Write(Utf8ToSelectedEncoding(lyrics));
|
||||
binaryWriter.Flush();
|
||||
}
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
|
||||
info.IsSuccessful = true;
|
||||
info.IsPruneMusic = false;
|
||||
return LyricsDownloadResult.Success;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (ErrorCodeException ex)
|
||||
{
|
||||
_logger.LogWarningInfo(ex);
|
||||
info.IsSuccessful = false;
|
||||
info.IsPruneMusic = false;
|
||||
_logger.LogWarningInfo(ex);
|
||||
return LyricsDownloadResult.Failed;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
|
||||
info.IsSuccessful = false;
|
||||
info.IsPruneMusic = false;
|
||||
await _logger.WarnAsync("当前歌词来源下载失败,将尝试其他来源。", ex);
|
||||
return LyricsDownloadResult.Failed;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单个歌词来源的处理结果。
|
||||
/// </summary>
|
||||
private enum LyricsDownloadResult
|
||||
{
|
||||
/// <summary>歌词已写入文件。</summary>
|
||||
Success,
|
||||
|
||||
/// <summary>该来源没有返回歌词(既可能是没有收录,也可能是纯音乐)。</summary>
|
||||
Empty,
|
||||
|
||||
/// <summary>该来源处理过程中出错。</summary>
|
||||
Failed
|
||||
}
|
||||
|
||||
// Convert UTF-8 to selected encoding.
|
||||
private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics)
|
||||
{
|
||||
@@ -140,7 +207,8 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
|
||||
return Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(_options.Provider.Lyric.Config.FileEncoding), lyrics.GetUtf8Bytes());
|
||||
}
|
||||
|
||||
private async Task LogFailedSongFilesInfo(string outFilePath, IEnumerable<MusicInfo> musicInfos)
|
||||
private async Task LogFailedSongFilesInfoAsync(string outFilePath, IEnumerable<MusicInfo> musicInfos,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var failedSongList = musicInfos.Where(m => m.IsSuccessful == false).ToImmutableList();
|
||||
if (!failedSongList.Any())
|
||||
@@ -156,6 +224,6 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
|
||||
failedSongFiles.AppendLine($"{failedSongFile.Name},{failedSongFile.Artist},{failedSongFile.FilePath}");
|
||||
}
|
||||
|
||||
await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString());
|
||||
await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString(), cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using MusicDecrypto.Library;
|
||||
using MusicDecrypto.Library;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
@@ -8,37 +9,90 @@ namespace ZonyLrcTools.Common.MusicDecryption
|
||||
public class DefaultMusicDecryptor : IMusicDecryptor, ITransientDependency
|
||||
{
|
||||
private readonly IWarpLogger _warpLogger;
|
||||
private readonly IKugouKeyProvider? _kugouKeyProvider;
|
||||
|
||||
public DefaultMusicDecryptor(IWarpLogger warpLogger)
|
||||
/// <summary>
|
||||
/// 创建音乐解密器。
|
||||
/// </summary>
|
||||
public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null)
|
||||
{
|
||||
_warpLogger = warpLogger;
|
||||
_kugouKeyProvider = kugouKeyProvider;
|
||||
}
|
||||
|
||||
public async Task<DecryptionResult> ConvertMusicAsync(string filePath)
|
||||
/// <inheritdoc />
|
||||
public async Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
// .kgg 的密钥存放在酷狗客户端数据库里,MusicDecrypto 覆盖不到这条链路。
|
||||
if (KggMusicDecryptor.IsKggFile(filePath))
|
||||
{
|
||||
return await KggMusicDecryptor.ConvertAsync(filePath, _kugouKeyProvider, cancellationToken);
|
||||
}
|
||||
|
||||
await using var buffer = new MarshalMemoryStream();
|
||||
await using var file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
||||
buffer.SetLengthWithPadding(file.Length);
|
||||
await file.CopyToAsync(buffer);
|
||||
await file.CopyToAsync(buffer, cancellationToken);
|
||||
|
||||
using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { });
|
||||
var outFileName = (await decrypto.DecryptAsync()).NewName;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var outFilePath = Path.Combine(Path.GetDirectoryName(filePath)!, outFileName);
|
||||
|
||||
if (!File.Exists(outFilePath))
|
||||
if (File.Exists(outFilePath))
|
||||
{
|
||||
await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
await buffer.CopyToAsync(outFile);
|
||||
return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outFilePath}");
|
||||
}
|
||||
|
||||
var tempPath = outFilePath + $".{Guid.NewGuid():N}.part";
|
||||
var ownsTempFile = false;
|
||||
try
|
||||
{
|
||||
await using (var outFile = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
ownsTempFile = true;
|
||||
buffer.Position = 0;
|
||||
await buffer.CopyToAsync(outFile, cancellationToken);
|
||||
await outFile.FlushAsync(cancellationToken);
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(tempPath, outFilePath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ownsTempFile)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(tempPath);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// 保留原始转换结果或异常。
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
// 保留原始转换结果或异常。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return DecryptionResult.Success(outFilePath);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 用户主动取消,交给调用方区分处理。
|
||||
throw;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return DecryptionResult.Failed(e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 酷狗数据库的探测结果。
|
||||
/// </summary>
|
||||
/// <param name="IsAvailable">数据库是否可用(文件存在且能解出密钥)。</param>
|
||||
/// <param name="DatabasePath">实际生效的数据库路径;不可用时为 null。</param>
|
||||
/// <param name="KeyCount">能从数据库里读出的密钥条目数量。</param>
|
||||
/// <param name="Message">给用户看的说明文字。</param>
|
||||
public sealed record KugouDatabaseInfo(bool IsAvailable, string? DatabasePath, int KeyCount, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// .kgg 解密前置条件的查询入口。
|
||||
/// <remarks>
|
||||
/// .kgg 的音频用 QMC2 加密,而每个文件自己的 ekey 不在文件里,
|
||||
/// 需要从酷狗客户端本地的 KGMusicV3.db 里按音频哈希查出来。
|
||||
/// GUI 需要提前知道“库在不在、这个文件有没有密钥”,才能在用户点开始之前给出提示。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public interface IKugouKeyProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// 当前生效的数据库路径;没有可用数据库时为 null。
|
||||
/// </summary>
|
||||
string? DatabasePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 手动指定数据库路径;<c>null</c> 或空字符串表示恢复自动探测。
|
||||
/// </summary>
|
||||
void SetDatabasePath(string? path);
|
||||
|
||||
/// <summary>
|
||||
/// 探测当前可用的数据库。
|
||||
/// <remarks>
|
||||
/// 实现应当缓存结果:整库解密需要几十毫秒,而查一次密钥只要零点几毫秒。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
KugouDatabaseInfo Probe();
|
||||
|
||||
/// <summary>
|
||||
/// 作废缓存,让下一次访问重新读取数据库。
|
||||
/// <remarks>
|
||||
/// 用户在酷狗里新下载了歌曲、或换了一份数据库文件之后需要调用,否则读到的还是旧快照。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
void Invalidate();
|
||||
|
||||
/// <summary>
|
||||
/// 按魔数和加密版本判断文件是否为 KGG,不看扩展名。
|
||||
/// </summary>
|
||||
bool IsKggFile(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// 读出 .kgg 文件头里的音频哈希;不是合法的 .kgg 时返回 null。
|
||||
/// </summary>
|
||||
string? ReadAudioHash(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// 取出该音频哈希对应的 ekey;没有时返回 null。
|
||||
/// </summary>
|
||||
string? FindKey(string audioHash);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using MusicDecrypto.Library;
|
||||
using MusicDecrypto.Library;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
@@ -14,7 +14,8 @@ namespace ZonyLrcTools.Common.MusicDecryption
|
||||
/// 将加密数据歌曲文件转换为可识别的歌曲格式。
|
||||
/// </summary>
|
||||
/// <param name="filePath">加密歌曲文件的路径。</param>
|
||||
/// <param name="cancellationToken">取消令牌,用于中断大文件的转换。</param>
|
||||
/// <returns>转换结果。</returns>
|
||||
Task<DecryptionResult> ConvertMusicAsync(string filePath);
|
||||
Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// Ported from the MIT-licensed reference implementation:
|
||||
// https://github.com/lizipeng0013/kgg-dec.mirror
|
||||
// Copyright (c) 2024 LSR
|
||||
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
|
||||
|
||||
using System.Text;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
|
||||
{
|
||||
/// <summary>
|
||||
/// 酷狗/QQ 音乐的 ekey 解码器。
|
||||
/// </summary>
|
||||
internal static class EkeyDecoder
|
||||
{
|
||||
/// <summary>
|
||||
/// V2 前缀,解码后即 "QQMusic EncV2,Key:"。
|
||||
/// </summary>
|
||||
private const string V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6";
|
||||
|
||||
private static readonly byte[] V2Key1 =
|
||||
[
|
||||
0x33, 0x38, 0x36, 0x5A, 0x4A, 0x59, 0x21, 0x40, 0x23, 0x2A, 0x24, 0x25, 0x5E, 0x26, 0x29, 0x28
|
||||
];
|
||||
|
||||
private static readonly byte[] V2Key2 =
|
||||
[
|
||||
0x2A, 0x2A, 0x23, 0x21, 0x28, 0x23, 0x24, 0x25, 0x26, 0x5E, 0x61, 0x31, 0x63, 0x5A, 0x2C, 0x54
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
|
||||
/// </summary>
|
||||
/// <returns>原始密钥;解码失败时为空数组。</returns>
|
||||
public static byte[] Decode(string ekey) => Decode(ekey, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
|
||||
/// </summary>
|
||||
/// <param name="ekey">数据库中的密钥。</param>
|
||||
/// <param name="invalidCharCount">Base64 中的非法字符数量,空白不计入。</param>
|
||||
/// <returns>原始密钥;解码失败时为空数组。</returns>
|
||||
public static byte[] Decode(string ekey, out int invalidCharCount)
|
||||
{
|
||||
invalidCharCount = 0;
|
||||
if (string.IsNullOrEmpty(ekey))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
if (ekey.StartsWith(V2Prefix, StringComparison.Ordinal))
|
||||
{
|
||||
var raw = Encoding.Latin1.GetBytes(ekey[V2Prefix.Length..]);
|
||||
var inner = TcTea.CbcDecrypt(raw, TcTea.ToRoundKeys(V2Key1));
|
||||
if (inner.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
inner = TcTea.CbcDecrypt(inner, TcTea.ToRoundKeys(V2Key2));
|
||||
if (inner.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return DecodeV1(Encoding.Latin1.GetString(inner), out invalidCharCount);
|
||||
}
|
||||
|
||||
return DecodeV1(ekey, out invalidCharCount);
|
||||
}
|
||||
|
||||
private static byte[] DecodeV1(string ekey, out int invalidCharCount)
|
||||
{
|
||||
var result = Base64Decode(ekey, out invalidCharCount);
|
||||
if (result.Length < 8)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var teaKey = new[]
|
||||
{
|
||||
0x69005600u | ((uint)result[0] << 16) | result[1],
|
||||
0x46003800u | ((uint)result[2] << 16) | result[3],
|
||||
0x2b002000u | ((uint)result[4] << 16) | result[5],
|
||||
0x15000b00u | ((uint)result[6] << 16) | result[7]
|
||||
};
|
||||
|
||||
var decrypted = TcTea.CbcDecrypt(result[8..], teaKey);
|
||||
if (decrypted.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var output = new byte[8 + decrypted.Length];
|
||||
result.AsSpan(0, 8).CopyTo(output);
|
||||
decrypted.CopyTo(output.AsSpan(8));
|
||||
return output;
|
||||
}
|
||||
|
||||
private static byte[] Base64Decode(string input, out int invalidCount)
|
||||
{
|
||||
var normalized = new char[input.Length + 3];
|
||||
var length = 0;
|
||||
invalidCount = 0;
|
||||
foreach (var value in input)
|
||||
{
|
||||
if (value is ' ' or '\r' or '\n' or '\t')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (value is not (>= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9'
|
||||
or '+' or '/' or '-' or '_' or '='))
|
||||
{
|
||||
invalidCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
normalized[length++] = value switch
|
||||
{
|
||||
'-' => '+',
|
||||
'_' => '/',
|
||||
_ => value
|
||||
};
|
||||
}
|
||||
|
||||
if (invalidCount != 0 || length == 0 || length % 4 == 1)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
// 兼容省略末尾填充的密钥,由标准解码器校验填充位置。
|
||||
while (length % 4 != 0)
|
||||
{
|
||||
normalized[length++] = '=';
|
||||
}
|
||||
|
||||
var padding = normalized[length - 1] == '=' ? 1 : 0;
|
||||
if (normalized[length - 2] == '=')
|
||||
{
|
||||
padding++;
|
||||
}
|
||||
|
||||
var output = new byte[length / 4 * 3 - padding];
|
||||
return Convert.TryFromBase64Chars(normalized.AsSpan(0, length), output, out _) ? output : [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// Ported from the MIT-licensed reference implementation:
|
||||
// https://github.com/lizipeng0013/kgg-dec.mirror
|
||||
// Copyright (c) 2024 LSR
|
||||
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
|
||||
{
|
||||
/// <summary>
|
||||
/// 酷狗 .kgg 文件的解密器。
|
||||
/// <remarks>
|
||||
/// .kgg 的音频主体用 QMC2 加密,而每个文件自己的 ekey 并不在文件里,
|
||||
/// 需要从酷狗客户端本地的 KGMusicV3.db 中按音频哈希查出来。
|
||||
/// 因此这个格式无法脱离酷狗客户端单独解密。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
internal static class KggMusicDecryptor
|
||||
{
|
||||
private const int HeaderSize = KugouEkeyDatabase.KggHeaderSize;
|
||||
private const int BufferSize = 1024 * 1024;
|
||||
private const uint ExpectedEncodingVersion = 5;
|
||||
private const uint ExpectedHashLength = 0x20;
|
||||
|
||||
/// <summary>
|
||||
/// .kgg 文件的 16 字节魔数。
|
||||
/// </summary>
|
||||
private static byte[] Magic => KugouEkeyDatabase.KggMagic;
|
||||
|
||||
/// <summary>
|
||||
/// 按魔数和加密版本判断是否为 KGG,避免误判共用魔数的旧版 KGM。
|
||||
/// </summary>
|
||||
public static bool IsKggFile(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(filePath);
|
||||
Span<byte> buffer = stackalloc byte[0x18];
|
||||
return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length
|
||||
&& buffer[..Magic.Length].SequenceEqual(Magic)
|
||||
&& BinaryPrimitives.ReadUInt32LittleEndian(buffer[0x14..]) == ExpectedEncodingVersion;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解密 .kgg 文件。
|
||||
/// </summary>
|
||||
/// <param name="filePath">待解密的文件路径。</param>
|
||||
/// <param name="keyProvider">密钥来源;为 null 时使用自动探测到的酷狗数据库。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>解密结果;失败时带有可读的错误说明。</returns>
|
||||
public static async Task<DecryptionResult> ConvertAsync(string filePath,
|
||||
IKugouKeyProvider? keyProvider,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
return DecryptionResult.Failed($"文件不存在: {filePath}");
|
||||
}
|
||||
|
||||
await using var input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, true);
|
||||
|
||||
var header = new byte[HeaderSize];
|
||||
if (await input.ReadAtLeastAsync(header, HeaderSize, throwOnEndOfStream: false, cancellationToken) !=
|
||||
HeaderSize)
|
||||
{
|
||||
return DecryptionResult.Failed("文件过小,不是有效的 kgg 文件。");
|
||||
}
|
||||
|
||||
if (!header.AsSpan(0, Magic.Length).SequenceEqual(Magic))
|
||||
{
|
||||
return DecryptionResult.Failed("文件头校验失败,不是有效的 kgg 文件。");
|
||||
}
|
||||
|
||||
var offsetToAudio = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10));
|
||||
if (offsetToAudio < HeaderSize || offsetToAudio > input.Length - 4)
|
||||
{
|
||||
return DecryptionResult.Failed("kgg 音频偏移超出有效范围。");
|
||||
}
|
||||
|
||||
var encodingVersion = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14));
|
||||
if (encodingVersion != ExpectedEncodingVersion)
|
||||
{
|
||||
return DecryptionResult.Failed($"不支持的 kgg 加密版本 0x{encodingVersion:X2},目前只支持 0x05。");
|
||||
}
|
||||
|
||||
var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
|
||||
if (hashLength != ExpectedHashLength)
|
||||
{
|
||||
return DecryptionResult.Failed($"kgg 音频哈希长度异常(期望 0x20,实际 0x{hashLength:X2})。");
|
||||
}
|
||||
|
||||
var audioHash = Encoding.ASCII.GetString(header, 0x48, (int)hashLength);
|
||||
|
||||
if (!HasDatabase(keyProvider))
|
||||
{
|
||||
return DecryptionResult.Failed(keyProvider?.Probe().Message ?? KugouEkeyDatabase.BuildMissingDatabaseMessage());
|
||||
}
|
||||
|
||||
var ekey = ResolveEkey(keyProvider, audioHash);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (string.IsNullOrEmpty(ekey))
|
||||
{
|
||||
return DecryptionResult.Failed(
|
||||
$"在酷狗数据库中没有找到该文件的解密密钥(音频哈希 {audioHash})。" +
|
||||
"通常表示这首歌尚未在酷狗客户端里播放或下载过。");
|
||||
}
|
||||
|
||||
var qmcKey = EkeyDecoder.Decode(ekey, out var invalidCharCount);
|
||||
if (invalidCharCount > 0)
|
||||
{
|
||||
return DecryptionResult.Failed(
|
||||
$"酷狗数据库里的 ekey 已损坏(有 {invalidCharCount} 个非法 Base64 字符),无法解码。" +
|
||||
"通常表示数据库文件被写坏了,可以尝试重新登录酷狗客户端刷新该记录。");
|
||||
}
|
||||
|
||||
var cipher = Qmc2Cipher.Create(qmcKey);
|
||||
if (cipher == null)
|
||||
{
|
||||
return DecryptionResult.Failed("ekey 解码失败,无法构造解密器。");
|
||||
}
|
||||
|
||||
input.Seek(offsetToAudio, SeekOrigin.Begin);
|
||||
|
||||
// 先解密开头 4 字节用于判断真实格式,再回去完整解密一遍。
|
||||
var magic = new byte[4];
|
||||
if (await input.ReadAtLeastAsync(magic, 4, throwOnEndOfStream: false, cancellationToken) != 4)
|
||||
{
|
||||
return DecryptionResult.Failed("kgg 音频数据为空。");
|
||||
}
|
||||
|
||||
cipher.Decrypt(magic, 0);
|
||||
var extension = DetectExtension(magic);
|
||||
if (extension == null)
|
||||
{
|
||||
return DecryptionResult.Failed("解密后的音频格式无法识别,文件或密钥可能已损坏。");
|
||||
}
|
||||
|
||||
input.Seek(offsetToAudio, SeekOrigin.Begin);
|
||||
|
||||
var outputPath = Path.Combine(
|
||||
Path.GetDirectoryName(filePath)!,
|
||||
$"{Path.GetFileNameWithoutExtension(filePath)}.{extension}");
|
||||
|
||||
// 期望的输出字节数,用于校验写盘是否完整。
|
||||
var expectedLength = input.Length - offsetToAudio;
|
||||
|
||||
if (File.Exists(outputPath))
|
||||
{
|
||||
return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outputPath}");
|
||||
}
|
||||
|
||||
// 每次转换独占临时文件,仅在完整写入后发布,且不覆盖已有输出。
|
||||
var tempPath = outputPath + $".{Guid.NewGuid():N}.part";
|
||||
var ownsTempFile = false;
|
||||
try
|
||||
{
|
||||
await using (var output = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
|
||||
BufferSize, true))
|
||||
{
|
||||
ownsTempFile = true;
|
||||
var buffer = new byte[BufferSize];
|
||||
var offset = 0L;
|
||||
while (true)
|
||||
{
|
||||
var read = await input.ReadAsync(buffer, cancellationToken);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
cipher.Decrypt(buffer.AsSpan(0, read), offset);
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
|
||||
offset += read;
|
||||
}
|
||||
|
||||
await output.FlushAsync(cancellationToken);
|
||||
|
||||
if (offset != expectedLength)
|
||||
{
|
||||
throw new IOException($"解密写入的字节数不匹配(期望 {expectedLength},实际 {offset})。");
|
||||
}
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(tempPath, outputPath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ownsTempFile)
|
||||
{
|
||||
TryDelete(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
return DecryptionResult.Success(outputPath);
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 保留原始转换结果或异常。
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasDatabase(IKugouKeyProvider? keyProvider)
|
||||
{
|
||||
return keyProvider != null ? keyProvider.DatabasePath != null : KugouEkeyDatabase.FindDatabasePath() != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取出音频哈希对应的 ekey;优先走外部提供的密钥来源。
|
||||
/// </summary>
|
||||
public static string? ResolveEkey(IKugouKeyProvider? keyProvider, string audioHash)
|
||||
{
|
||||
if (keyProvider != null)
|
||||
{
|
||||
return keyProvider.FindKey(audioHash);
|
||||
}
|
||||
|
||||
var databasePath = KugouEkeyDatabase.FindDatabasePath();
|
||||
if (databasePath == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var keys = KugouEkeyDatabase.ReadEncryptionKeys(databasePath);
|
||||
return keys.TryGetValue(audioHash, out var ekey) ? ekey : null;
|
||||
}
|
||||
|
||||
private static string? DetectExtension(ReadOnlySpan<byte> magic)
|
||||
{
|
||||
if (magic.SequenceEqual("fLaC"u8))
|
||||
{
|
||||
return "flac";
|
||||
}
|
||||
|
||||
if (magic.SequenceEqual("OggS"u8))
|
||||
{
|
||||
return "ogg";
|
||||
}
|
||||
|
||||
return magic[..3].SequenceEqual("ID3"u8)
|
||||
|| (magic[0] == 0xFF && (magic[1] & 0xE0) == 0xE0 && (magic[1] & 0x06) != 0)
|
||||
? "mp3"
|
||||
: null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
// Ported from the MIT-licensed reference implementation:
|
||||
// https://github.com/lizipeng0013/kgg-dec.mirror
|
||||
// Copyright (c) 2024 LSR
|
||||
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
|
||||
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
|
||||
{
|
||||
/// <summary>
|
||||
/// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。
|
||||
/// <remarks>
|
||||
/// 数据库按 1KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥和页号派生。
|
||||
/// 解密后可以读到 <c>ShareFileItems</c> 表里的 ekey,那是 .kgg 文件真正用的解密密钥。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
internal static class KugouEkeyDatabase
|
||||
{
|
||||
/// <summary>
|
||||
/// .kgg 文件头的长度,音频数据从这个位置之后开始。
|
||||
/// </summary>
|
||||
internal const int KggHeaderSize = 0x400;
|
||||
|
||||
/// <summary>
|
||||
/// .kgg 文件的 16 字节魔数。
|
||||
/// </summary>
|
||||
internal static readonly byte[] KggMagic =
|
||||
[
|
||||
0x7C, 0xD5, 0x32, 0xEB, 0x86, 0x02, 0x7F, 0x4B,
|
||||
0xA8, 0xAF, 0xA6, 0x8E, 0x0F, 0xFF, 0x99, 0x14
|
||||
];
|
||||
|
||||
private const int PageSize = 0x400;
|
||||
private const uint PageKeySalt = 0x546C4173;
|
||||
private const uint IvMultiplier = 0x7FFFFF07;
|
||||
private const uint IvDivisor = 0xce26;
|
||||
private const uint IvBase = 0x9EF4;
|
||||
|
||||
/// <summary>
|
||||
/// 酷狗客户端内置的主密钥。
|
||||
/// </summary>
|
||||
private static readonly byte[] MasterKey =
|
||||
[
|
||||
0x1d, 0x61, 0x31, 0x45, 0xb2, 0x47, 0xbf, 0x7f,
|
||||
0x3d, 0x18, 0x96, 0x72, 0x14, 0x4f, 0xe4, 0xbf
|
||||
];
|
||||
|
||||
private static readonly byte[] SqliteHeader =
|
||||
[
|
||||
(byte)'S', (byte)'Q', (byte)'L', (byte)'i', (byte)'t', (byte)'e', (byte)' ',
|
||||
(byte)'f', (byte)'o', (byte)'r', (byte)'m', (byte)'a', (byte)'t', (byte)' ', (byte)'3', 0
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 从数据库里读出所有非空的 ekey。
|
||||
/// </summary>
|
||||
/// <returns>音频哈希到 ekey 的映射;文件不存在或解密失败时返回空字典。</returns>
|
||||
public static IReadOnlyDictionary<string, string> ReadEncryptionKeys(string databasePath)
|
||||
{
|
||||
return ReadEncryptionKeys(databasePath, out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从数据库里读出所有非空的 ekey,并在失败时给出可读的原因。
|
||||
/// <remarks>
|
||||
/// 读取失败的原因有多种(文件不存在 / 不是酷狗数据库 / 主密钥不匹配 / 表结构缺失 / 权限不足),
|
||||
/// 这些在 UI 上的处置完全不同,因此不能再把所有异常压成「没有密钥」。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
/// <param name="databasePath">数据库文件路径。</param>
|
||||
/// <param name="failureReason">读取失败时的原因说明;成功时为 null。</param>
|
||||
public static IReadOnlyDictionary<string, string> ReadEncryptionKeys(string databasePath, out string? failureReason)
|
||||
{
|
||||
failureReason = null;
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(databasePath))
|
||||
{
|
||||
failureReason = "没有指定酷狗数据库路径。";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!File.Exists(databasePath))
|
||||
{
|
||||
failureReason = $"数据库文件不存在:{databasePath}";
|
||||
return result;
|
||||
}
|
||||
|
||||
byte[] plain;
|
||||
try
|
||||
{
|
||||
plain = DecryptDatabase(databasePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failureReason = $"数据库解密失败(文件可能不是酷狗 KGMusicV3.db,或版本不受支持):{ex.Message}";
|
||||
return result;
|
||||
}
|
||||
|
||||
if (plain.Length == 0)
|
||||
{
|
||||
failureReason = $"数据库解密后内容为空,格式不像酷狗 KGMusicV3.db:{databasePath}";
|
||||
return result;
|
||||
}
|
||||
|
||||
// 直接从内存解析,避免明文密钥落盘和并发清理临时文件的竞争。
|
||||
var pinned = GCHandle.Alloc(plain, GCHandleType.Pinned);
|
||||
try
|
||||
{
|
||||
using var connection = new SqliteConnection("Data Source=:memory:;Pooling=False");
|
||||
connection.Open();
|
||||
var error = SQLitePCL.raw.sqlite3_deserialize(connection.Handle, "main",
|
||||
pinned.AddrOfPinnedObject(), plain.Length, plain.Length, SQLitePCL.raw.SQLITE_DESERIALIZE_READONLY);
|
||||
if (error != SQLitePCL.raw.SQLITE_OK)
|
||||
{
|
||||
throw new SqliteException("无法读取解密后的酷狗数据库。", error);
|
||||
}
|
||||
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''";
|
||||
using var reader = command.ExecuteReader();
|
||||
while (reader.Read())
|
||||
{
|
||||
if (reader.IsDBNull(0) || reader.IsDBNull(1))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var keyId = reader.GetString(0);
|
||||
var ekey = reader.GetString(1);
|
||||
if (keyId.Length > 0 && ekey.Length > 0)
|
||||
{
|
||||
result[keyId] = ekey;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failureReason = $"数据库内容读取失败(表 ShareFileItems 可能不存在):{ex.Message}";
|
||||
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
finally
|
||||
{
|
||||
pinned.Free();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把整个加密数据库解密成明文的 SQLite 字节流。
|
||||
/// </summary>
|
||||
private static byte[] DecryptDatabase(string databasePath)
|
||||
{
|
||||
using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
|
||||
var sourceLength = source.Length;
|
||||
if (sourceLength == 0 || sourceLength > Array.MaxLength || sourceLength % PageSize != 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var length = (int)sourceLength;
|
||||
var pageCount = length / PageSize;
|
||||
var plain = new byte[length];
|
||||
var headerBuffer = new byte[8];
|
||||
|
||||
// 复用同一个 Aes 实例:每页只是换 Key,避免 16000+ 次 Aes.Create() 的对象构造开销。
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.None;
|
||||
|
||||
for (var pageIndex = 1; pageIndex <= pageCount; pageIndex++)
|
||||
{
|
||||
var target = plain.AsSpan((pageIndex - 1) * PageSize, PageSize);
|
||||
source.ReadExactly(target);
|
||||
|
||||
DerivePageKeyIv((uint)pageIndex, out var key, out var iv);
|
||||
|
||||
if (pageIndex == 1)
|
||||
{
|
||||
// 首页前 16 字节是明文文件头,真正从 0x10 开始加密;
|
||||
// 解密前要把 0x08..0x10 复制到 0x10 处作为 CBC 的密文块。
|
||||
target.Slice(0x10, 8).CopyTo(headerBuffer);
|
||||
target.Slice(0x08, 8).CopyTo(target[0x10..]);
|
||||
|
||||
AesCbcDecryptInPlace(aes, target[0x10..], key, iv);
|
||||
|
||||
if (!target.Slice(0x10, 8).SequenceEqual(headerBuffer))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
SqliteHeader.CopyTo(target);
|
||||
}
|
||||
else
|
||||
{
|
||||
AesCbcDecryptInPlace(aes, target, key, iv);
|
||||
}
|
||||
}
|
||||
|
||||
return plain;
|
||||
}
|
||||
|
||||
private static void AesCbcDecryptInPlace(Aes aes, Span<byte> buffer, byte[] key, byte[] iv)
|
||||
{
|
||||
aes.Key = key;
|
||||
|
||||
// 两个坑都要显式避开:
|
||||
// 1) 参数顺序是 TryDecryptCbc(ciphertext, iv, destination, out written, padding),
|
||||
// 写成 (buffer, buffer, iv, ...) 会把 buffer 自己当 IV、把真正的 IV 覆盖掉;
|
||||
// 2) padding 的默认值是 PKCS7 而不是实例上的 aes.Padding,分页数据是整块无填充的,
|
||||
// 不传 PaddingMode.None 就会在每页末尾抛「Padding is invalid」。
|
||||
if (!aes.TryDecryptCbc(buffer, iv, buffer, out var written, PaddingMode.None) ||
|
||||
written != buffer.Length)
|
||||
{
|
||||
throw new CryptographicException("酷狗数据库分页解密失败。");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按页号派生出该页使用的 AES 密钥与 IV。
|
||||
/// </summary>
|
||||
private static void DerivePageKeyIv(uint pageNumber, out byte[] key, out byte[] iv)
|
||||
{
|
||||
var buffer = new byte[0x18];
|
||||
MasterKey.CopyTo(buffer, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x10), pageNumber);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x14), PageKeySalt);
|
||||
|
||||
key = MD5.HashData(buffer);
|
||||
|
||||
// IV 由一个线性同余式的四次迭代结果拼成。
|
||||
var value = pageNumber + 1;
|
||||
for (var i = 0; i < 16; i += 4)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
var quotient = value / IvDivisor;
|
||||
var product = IvMultiplier * quotient;
|
||||
var next = IvBase * value - product;
|
||||
if ((next & 0x8000_0000) != 0)
|
||||
{
|
||||
next += IvMultiplier;
|
||||
}
|
||||
|
||||
value = next;
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(i), value);
|
||||
}
|
||||
}
|
||||
|
||||
iv = MD5.HashData(buffer.AsSpan(0, 0x10));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 酷狗客户端数据库的常见位置。
|
||||
/// </summary>
|
||||
public static IEnumerable<string> EnumerateCandidatePaths()
|
||||
{
|
||||
var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||||
if (!string.IsNullOrEmpty(roaming))
|
||||
{
|
||||
yield return Path.Combine(roaming, "KuGou8", "KGMusicV3.db");
|
||||
yield return Path.Combine(roaming, "KuGou", "KGMusicV3.db");
|
||||
}
|
||||
|
||||
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
if (!string.IsNullOrEmpty(localAppData))
|
||||
{
|
||||
yield return Path.Combine(localAppData, "KuGou8", "KGMusicV3.db");
|
||||
yield return Path.Combine(localAppData, "KuGou", "KGMusicV3.db");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 找到第一个存在的数据库路径。
|
||||
/// </summary>
|
||||
public static string? FindDatabasePath()
|
||||
{
|
||||
foreach (var path in EnumerateCandidatePaths())
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让用户能看懂的错误信息。
|
||||
/// </summary>
|
||||
public static string BuildMissingDatabaseMessage()
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
builder.Append("未找到酷狗客户端数据库 KGMusicV3.db,无法获取解密密钥。");
|
||||
builder.Append("请确认已安装酷狗音乐并至少登录过一次。已尝试的路径:");
|
||||
foreach (var path in EnumerateCandidatePaths())
|
||||
{
|
||||
builder.Append(' ').Append(path).Append(';');
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
// Ported from the MIT-licensed reference implementation:
|
||||
// https://github.com/lizipeng0013/kgg-dec.mirror
|
||||
// Copyright (c) 2024 LSR
|
||||
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
|
||||
{
|
||||
/// <summary>
|
||||
/// QMC2 加密流的解密器基类,负责按偏移量流式解出明文。
|
||||
/// </summary>
|
||||
internal abstract class Qmc2Cipher
|
||||
{
|
||||
/// <summary>
|
||||
/// 首段的长度,这一段的密钥派生方式与其他段不同。
|
||||
/// </summary>
|
||||
protected const int FirstSegmentSize = 0x80;
|
||||
|
||||
/// <summary>
|
||||
/// 其余段落的长度。
|
||||
/// </summary>
|
||||
protected const int OtherSegmentSize = 0x1400;
|
||||
|
||||
/// <summary>
|
||||
/// 解密数据流中的一个字节。
|
||||
/// </summary>
|
||||
/// <param name="cipher">密文中的该字节。</param>
|
||||
/// <param name="offset">该字节在完整音频流中的偏移量。</param>
|
||||
public abstract byte Decrypt(byte cipher, long offset);
|
||||
|
||||
/// <summary>
|
||||
/// 就地把一段数据解密。
|
||||
/// <remarks>
|
||||
/// 批量接口,避免逐字节走虚函数调用;几十 MB 的文件靠逐字节会慢到不可接受。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
/// <param name="data">待解密的密文,解密结果原地写回。</param>
|
||||
/// <param name="offset">这段数据在完整音频流中的起始偏移量。</param>
|
||||
public virtual void Decrypt(Span<byte> data, long offset)
|
||||
{
|
||||
for (var i = 0; i < data.Length; i++)
|
||||
{
|
||||
data[i] = Decrypt(data[i], offset + i);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据解码后的 ekey 长度选择具体的实现。
|
||||
/// </summary>
|
||||
public static Qmc2Cipher? Create(byte[] key)
|
||||
{
|
||||
if (key.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return key.Length < 300 ? new Qmc2MapCipher(key) : new Qmc2Rc4Cipher(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 短密钥(长度小于 300)使用的查表型解密器。
|
||||
/// </summary>
|
||||
internal sealed class Qmc2MapCipher : Qmc2Cipher
|
||||
{
|
||||
private const int MapIndexOffset = 71214;
|
||||
private const int MapKeySize = 128;
|
||||
private const int MapIndexBoundary = 0x7FFF;
|
||||
|
||||
private readonly byte[] _key;
|
||||
|
||||
/// <summary>
|
||||
/// 根据短密钥生成查找表。
|
||||
/// </summary>
|
||||
public Qmc2MapCipher(byte[] key)
|
||||
{
|
||||
_key = new byte[MapKeySize];
|
||||
var length = key.Length;
|
||||
for (var i = 0; i < MapKeySize; i++)
|
||||
{
|
||||
var j = (int)(((long)i * i + MapIndexOffset) % length);
|
||||
var shift = (j + 4) % 8;
|
||||
var value = key[j];
|
||||
_key[i] = (byte)((value << shift) | (value >> shift));
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override byte Decrypt(byte cipher, long offset)
|
||||
{
|
||||
var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary;
|
||||
return (byte)(cipher ^ _key[index % MapKeySize]);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Decrypt(Span<byte> data, long offset)
|
||||
{
|
||||
for (var i = 0; i < data.Length; i++)
|
||||
{
|
||||
var position = offset + i;
|
||||
var index = position <= MapIndexBoundary ? position : position % MapIndexBoundary;
|
||||
data[i] ^= _key[index % MapKeySize];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 长密钥使用的 RC4 派生流解密器。
|
||||
/// </summary>
|
||||
internal sealed class Qmc2Rc4Cipher : Qmc2Cipher
|
||||
{
|
||||
/// <summary>
|
||||
/// 每段从密钥流中取用的前置长度上限。
|
||||
/// </summary>
|
||||
private const int SegmentSkipMask = 0x1FF;
|
||||
|
||||
/// <summary>
|
||||
/// 密钥流的长度,比普通段多出 512 字节用于起始偏移。
|
||||
/// </summary>
|
||||
private const int KeyStreamSize = OtherSegmentSize + 512;
|
||||
|
||||
private readonly byte[] _key;
|
||||
private readonly byte[] _keyStream = new byte[KeyStreamSize];
|
||||
private readonly uint _keyHash;
|
||||
|
||||
/// <summary>
|
||||
/// 根据长密钥生成密钥流。
|
||||
/// </summary>
|
||||
public Qmc2Rc4Cipher(byte[] key)
|
||||
{
|
||||
_key = key;
|
||||
_keyHash = ComputeKeyHash(key);
|
||||
DeriveKeyStream();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override byte Decrypt(byte cipher, long offset)
|
||||
{
|
||||
if (offset < FirstSegmentSize)
|
||||
{
|
||||
// 首段的索引直接由当前偏移推导,且随偏移逐字节变化。
|
||||
var seed = _key[(int)(offset % _key.Length)];
|
||||
var index = GetSegmentKey(_keyHash, offset, seed) % _key.Length;
|
||||
return (byte)(cipher ^ _key[index]);
|
||||
}
|
||||
|
||||
var segmentIndex = offset / OtherSegmentSize;
|
||||
var segmentOffset = offset % OtherSegmentSize;
|
||||
var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask;
|
||||
return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Decrypt(Span<byte> data, long offset)
|
||||
{
|
||||
// 首段与常规段的算法不同,先按边界切一刀。
|
||||
if (offset < FirstSegmentSize)
|
||||
{
|
||||
var length = (int)Math.Min(data.Length, FirstSegmentSize - offset);
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var seed = _key[(int)((offset + i) % _key.Length)];
|
||||
var index = GetSegmentKey(_keyHash, offset + i, seed) % _key.Length;
|
||||
data[i] ^= _key[index];
|
||||
}
|
||||
|
||||
offset += length;
|
||||
data = data[length..];
|
||||
}
|
||||
|
||||
while (data.Length > 0)
|
||||
{
|
||||
var segmentIndex = offset / OtherSegmentSize;
|
||||
var segmentOffset = (int)(offset % OtherSegmentSize);
|
||||
var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask;
|
||||
var length = Math.Min(data.Length, OtherSegmentSize - segmentOffset);
|
||||
|
||||
var stream = _keyStream.AsSpan((int)skipLength + segmentOffset, length);
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
data[i] ^= stream[i];
|
||||
}
|
||||
|
||||
offset += length;
|
||||
data = data[length..];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把密钥压成一个 32 位的乘法哈希,遇到溢出就提前结束。
|
||||
/// </summary>
|
||||
private static uint ComputeKeyHash(ReadOnlySpan<byte> key)
|
||||
{
|
||||
var hash = 1u;
|
||||
foreach (var item in key)
|
||||
{
|
||||
if (item == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var next = hash * item;
|
||||
if (next <= hash)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
hash = next;
|
||||
}
|
||||
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按段号与种子计算出该段在密钥或密钥流中的起始位置。
|
||||
/// <remarks>
|
||||
/// 中间结果可能远超 int 上限,必须用 long 承载,否则会截断出错位。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
private static long GetSegmentKey(uint hash, long segmentId, int seed)
|
||||
{
|
||||
if (seed == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (long)(hash / (double)(seed * (segmentId + 1)) * 100.0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用 RC4 的 KSA 生成密钥流。
|
||||
/// </summary>
|
||||
private void DeriveKeyStream()
|
||||
{
|
||||
var length = _key.Length;
|
||||
var state = new byte[length];
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
state[i] = (byte)i;
|
||||
}
|
||||
|
||||
// 这里的 i / j 必须是宽于 byte 的整数,长度 512 时 byte 会回绕。
|
||||
var j = 0;
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
j = (j + state[i] + _key[i]) % length;
|
||||
(state[i], state[j]) = (state[j], state[i]);
|
||||
}
|
||||
|
||||
var a = 0;
|
||||
var b = 0;
|
||||
for (var i = 0; i < KeyStreamSize; i++)
|
||||
{
|
||||
a = (a + 1) % length;
|
||||
b = (b + state[a]) % length;
|
||||
(state[a], state[b]) = (state[b], state[a]);
|
||||
_keyStream[i] = state[(state[a] + state[b]) % length];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Ported from the MIT-licensed reference implementation:
|
||||
// https://github.com/lizipeng0013/kgg-dec.mirror
|
||||
// Copyright (c) 2024 LSR
|
||||
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
|
||||
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
|
||||
{
|
||||
/// <summary>
|
||||
/// 腾讯 TEA(TC-TEA)加解密实现,用于解析酷狗的 ekey 密文。
|
||||
/// <remarks>
|
||||
/// 这里只实现了 QMC2 所需的部分:单块 ECB 解密与带双 IV 链的 CBC 解密。
|
||||
/// 算法来源于酷狗客户端的实际行为,与 MusicDecrypto 内置的格式无关。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
internal static class TcTea
|
||||
{
|
||||
private const int Rounds = 16;
|
||||
private const uint Delta = 0x9e3779b9;
|
||||
|
||||
/// <summary>
|
||||
/// 16 轮累加后的 sum 值,等价于 <c>Rounds * Delta</c> 在 uint32 下的溢出结果。
|
||||
/// </summary>
|
||||
private const uint ExpectedSum = 0xE3779B90;
|
||||
|
||||
private const int BlockSize = 8;
|
||||
private const int FixedSaltLength = 2;
|
||||
private const int ZeroPaddingLength = 7;
|
||||
private const int HeaderSize = BlockSize * 2;
|
||||
|
||||
private static uint SingleRound(uint value, uint sum, uint key1, uint key2)
|
||||
{
|
||||
return ((value << 4) + key1) ^ (value + sum) ^ ((value >> 5) + key2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TEA 单块解密(ECB)。
|
||||
/// </summary>
|
||||
public static ulong DecryptBlock(ulong value, ReadOnlySpan<uint> key)
|
||||
{
|
||||
var y = (uint)(value >> 32);
|
||||
var z = (uint)value;
|
||||
var sum = ExpectedSum;
|
||||
|
||||
for (var i = 0; i < Rounds; i++)
|
||||
{
|
||||
z -= SingleRound(y, sum, key[2], key[3]);
|
||||
y -= SingleRound(z, sum, key[0], key[1]);
|
||||
sum -= Delta;
|
||||
}
|
||||
|
||||
return ((ulong)y << 32) | z;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TC-TEA 的 CBC 解密,带自定义的头部跳过与零填充校验。
|
||||
/// <remarks>
|
||||
/// 参数与返回值都用数组而非 Span,是因为内部要用局部函数保存解密状态。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
/// <returns>解密后的明文;若校验失败则返回空数组。</returns>
|
||||
public static byte[] CbcDecrypt(byte[] cipher, uint[] key)
|
||||
{
|
||||
// 由于填充方案的特殊性,密文至少要两个块长。
|
||||
if (cipher.Length % BlockSize != 0 || cipher.Length < HeaderSize)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var iv1 = 0UL;
|
||||
var iv2 = 0UL;
|
||||
var inOffset = 0;
|
||||
var header = new byte[HeaderSize];
|
||||
|
||||
// 解密一轮,把结果写到 target 指定的 8 字节位置。
|
||||
void DecryptRound(byte[] target, int targetOffset)
|
||||
{
|
||||
var iv1Next = BinaryPrimitives.ReadUInt64BigEndian(cipher.AsSpan(inOffset));
|
||||
var iv2Next = DecryptBlock(iv1Next ^ iv2, key);
|
||||
var plain = iv2Next ^ iv1;
|
||||
|
||||
iv1 = iv1Next;
|
||||
iv2 = iv2Next;
|
||||
BinaryPrimitives.WriteUInt64BigEndian(target.AsSpan(targetOffset), plain);
|
||||
inOffset += BlockSize;
|
||||
}
|
||||
|
||||
DecryptRound(header, 0);
|
||||
DecryptRound(header, BlockSize);
|
||||
|
||||
var headerSkipLength = 1 + (header[0] & 7) + FixedSaltLength;
|
||||
var realPlainLength = cipher.Length - headerSkipLength - ZeroPaddingLength;
|
||||
if (realPlainLength <= 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new byte[realPlainLength];
|
||||
|
||||
// 先拷出头部块里剩余的明文。
|
||||
var copyLength = Math.Min(HeaderSize - headerSkipLength, realPlainLength);
|
||||
Array.Copy(header, headerSkipLength, result, 0, copyLength);
|
||||
var outOffset = copyLength;
|
||||
|
||||
if (realPlainLength != copyLength)
|
||||
{
|
||||
for (var i = cipher.Length - BlockSize * 3; i != 0; i -= BlockSize)
|
||||
{
|
||||
DecryptRound(header, 0);
|
||||
Array.Copy(header, 0, result, outOffset, BlockSize);
|
||||
outOffset += BlockSize;
|
||||
}
|
||||
|
||||
// 最后一个块只取首字节,且必须落在 header 的第二个块位置,供下方零填充校验使用。
|
||||
DecryptRound(header, BlockSize);
|
||||
result[outOffset] = header[BlockSize];
|
||||
}
|
||||
|
||||
// 校验零填充:末尾 8 字节左移一位后必须为 0。
|
||||
var verify = BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(BlockSize)) << 8;
|
||||
return verify != 0 ? [] : result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 16 字节的密钥按大端拆成 4 个 uint32,供 TEA 使用。
|
||||
/// </summary>
|
||||
public static uint[] ToRoundKeys(byte[] key)
|
||||
{
|
||||
var result = new uint[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
result[i] = BinaryPrimitives.ReadUInt32BigEndian(key.AsSpan(i * 4));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Common.MusicDecryption
|
||||
{
|
||||
/// <inheritdoc cref="ZonyLrcTools.Common.MusicDecryption.IKugouKeyProvider" />
|
||||
public class KugouKeyProvider : IKugouKeyProvider, ISingletonDependency
|
||||
{
|
||||
private const int HeaderSize = Kugou.KugouEkeyDatabase.KggHeaderSize;
|
||||
private const int AudioHashOffset = 0x48;
|
||||
private const int AudioHashLength = 0x20;
|
||||
|
||||
private readonly object _syncRoot = new();
|
||||
private readonly Dictionary<string, string> _keys = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private string? _manualPath;
|
||||
private string? _databasePath;
|
||||
private string? _failureReason;
|
||||
private bool _isLoaded;
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? DatabasePath
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _databasePath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SetDatabasePath(string? path)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
var normalized = string.IsNullOrWhiteSpace(path) ? null : path;
|
||||
if (string.Equals(normalized, _manualPath,
|
||||
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
|
||||
{
|
||||
// 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。
|
||||
return;
|
||||
}
|
||||
|
||||
_manualPath = normalized;
|
||||
Invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 探测当前可用的酷狗数据库。
|
||||
/// <remarks>
|
||||
/// 结果会被缓存:整库解密需要几十毫秒,而真正查一次密钥只要 0.1 毫秒。
|
||||
/// 只有在 <see cref="SetDatabasePath"/> 改变了路径、或显式调用 <see cref="Invalidate"/> 时才会重新读取。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
public KugouDatabaseInfo Probe()
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
||||
if (_databasePath == null)
|
||||
{
|
||||
var message = _manualPath != null
|
||||
? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}"
|
||||
: _failureReason ?? Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage();
|
||||
|
||||
return new KugouDatabaseInfo(false, null, 0, message);
|
||||
}
|
||||
|
||||
return _keys.Count == 0
|
||||
? new KugouDatabaseInfo(false, _databasePath, 0,
|
||||
$"已找到酷狗数据库,但里面没有任何解密密钥:{_databasePath}")
|
||||
: new KugouDatabaseInfo(true, _databasePath, _keys.Count,
|
||||
$"已读取 {_keys.Count} 个解密密钥:{_databasePath}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让下一次访问重新读取数据库(例如用户在酷狗里新下载了歌曲)。
|
||||
/// </summary>
|
||||
public void Invalidate()
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
_isLoaded = false;
|
||||
_keys.Clear();
|
||||
_databasePath = null;
|
||||
_failureReason = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsKggFile(string filePath) => Kugou.KggMusicDecryptor.IsKggFile(filePath);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? ReadAudioHash(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(filePath);
|
||||
var header = new byte[HeaderSize];
|
||||
if (stream.ReadAtLeast(header, HeaderSize, throwOnEndOfStream: false) != HeaderSize)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!header.AsSpan(0, 16).SequenceEqual(Kugou.KugouEkeyDatabase.KggMagic))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var audioOffset = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10));
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14)) != 5
|
||||
|| audioOffset < HeaderSize || audioOffset > stream.Length - 4)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
|
||||
if (hashLength != AudioHashLength)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Encoding.ASCII.GetString(header, AudioHashOffset, (int)hashLength);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? FindKey(string audioHash)
|
||||
{
|
||||
if (string.IsNullOrEmpty(audioHash))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (_syncRoot)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _keys.TryGetValue(audioHash, out var ekey) && !string.IsNullOrEmpty(ekey) ? ekey : null;
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureLoaded()
|
||||
{
|
||||
if (_isLoaded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isLoaded = true;
|
||||
_keys.Clear();
|
||||
_databasePath = null;
|
||||
_failureReason = null;
|
||||
|
||||
var path = _manualPath;
|
||||
if (path == null)
|
||||
{
|
||||
path = Kugou.KugouEkeyDatabase.FindDatabasePath();
|
||||
if (path == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (!File.Exists(path))
|
||||
{
|
||||
_failureReason = "文件不存在";
|
||||
return;
|
||||
}
|
||||
|
||||
var keys = Kugou.KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason);
|
||||
if (keys.Count == 0)
|
||||
{
|
||||
_failureReason = failureReason ?? "没有读到任何密钥";
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_databasePath = path;
|
||||
foreach (var pair in keys)
|
||||
{
|
||||
_keys[pair.Key] = pair.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,22 +15,28 @@ public class CsvFileMusicScanner : ITransientDependency
|
||||
/// <param name="csvFilePath">CSV 文件的路径。</param>
|
||||
/// <param name="outputDirectory">歌词文件的输出目录。</param>
|
||||
/// <param name="pattern">输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
public async Task<List<MusicInfo>> GetMusicInfoFromCsvFileAsync(string csvFilePath, string outputDirectory,
|
||||
string pattern)
|
||||
string pattern, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var encoding = DetectFileEncoding(csvFilePath);
|
||||
|
||||
var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding);
|
||||
var csvFileLines = csvFileContent.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries);
|
||||
return csvFileLines.Skip(1).Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern))
|
||||
var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding, cancellationToken);
|
||||
|
||||
// 兼容不同操作系统导出的换行符。
|
||||
var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
|
||||
return csvFileLines.Skip(1)
|
||||
.Where(line => line.Contains(','))
|
||||
.Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private MusicInfo GetMusicInfoFromCsvFileLine(string csvFileLine, string outputDirectory, string pattern)
|
||||
{
|
||||
var csvFileLineItems = csvFileLine.Split(',');
|
||||
var name = csvFileLineItems[0];
|
||||
var artist = csvFileLineItems[1];
|
||||
var name = csvFileLineItems[0].Trim();
|
||||
var artist = csvFileLineItems.Length > 1 ? csvFileLineItems[1].Trim() : string.Empty;
|
||||
var fakeFilePath = Path.Combine(outputDirectory, pattern.Replace("{Name}", name).Replace("{Artist}", artist));
|
||||
var musicInfo = new MusicInfo(fakeFilePath, name, artist);
|
||||
return musicInfo;
|
||||
|
||||
@@ -20,9 +20,60 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
private readonly IWarpHttpClient _warpHttpClient;
|
||||
private readonly ILogger<NetEaseMusicSongListMusicScanner> _logger;
|
||||
private const string Host = "https://music.163.com";
|
||||
private readonly SemaphoreSlim _loginSemaphore = new(1, 1);
|
||||
private readonly object _loginStateLock = new();
|
||||
private string _cookie = string.Empty;
|
||||
private string _csrfToken = string.Empty;
|
||||
private long _loginStateVersion;
|
||||
|
||||
private string Cookie { get; set; } = string.Empty;
|
||||
private string CsrfToken { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。
|
||||
/// </summary>
|
||||
public string Cookie
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
return _cookie;
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
_cookie = value ?? string.Empty;
|
||||
_loginStateVersion++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 登录后的 CSRF Token,通常与 <see cref="Cookie"/> 一起持久化。
|
||||
/// </summary>
|
||||
public string CsrfToken
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
return _csrfToken;
|
||||
}
|
||||
}
|
||||
set
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
_csrfToken = value ?? string.Empty;
|
||||
_loginStateVersion++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当前是否已经持有登录态。
|
||||
/// </summary>
|
||||
public bool IsLoggedIn => !string.IsNullOrEmpty(Cookie);
|
||||
|
||||
/// <summary>
|
||||
/// 构建一个新的 <see cref="NetEaseMusicSongListMusicScanner"/> 对象。
|
||||
@@ -34,34 +85,122 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除当前登录态,下次调用歌单接口时会重新要求扫码。
|
||||
/// </summary>
|
||||
public void ClearLoginState()
|
||||
{
|
||||
RestoreLoginState(string.Empty, string.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复一个已有的登录态,供 GUI 从本地缓存中读回 Cookie 之后调用。
|
||||
/// </summary>
|
||||
/// <param name="cookie">之前登录成功时保存的 Cookie。</param>
|
||||
/// <param name="csrfToken">与 <paramref name="cookie"/> 一起保存的 CSRF Token。</param>
|
||||
public void RestoreLoginState(string cookie, string csrfToken)
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
_cookie = cookie ?? string.Empty;
|
||||
_csrfToken = csrfToken ?? string.Empty;
|
||||
_loginStateVersion++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主动触发一次扫码登录(如果已经登录则直接返回 true)。
|
||||
/// </summary>
|
||||
/// <param name="onQrCodeReady">二维码就绪回调。</param>
|
||||
/// <param name="onStateChanged">登录状态变化回调,GUI 用它显示「已扫码,请在手机上确认」之类的中间态。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>登录成功时为 true。</returns>
|
||||
public async Task<bool> LoginAsync(
|
||||
Action<NetEaseQrCodePayload>? onQrCodeReady = null,
|
||||
Action<NetEaseLoginState>? onStateChanged = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _loginSemaphore.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var session = GetLoginState();
|
||||
if (!string.IsNullOrEmpty(session.Cookie))
|
||||
{
|
||||
onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
|
||||
return true;
|
||||
}
|
||||
|
||||
var loginResponse = await LoginViaQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
// 退出或恢复会话后,不能再提交旧二维码的登录结果。
|
||||
if (session.Version != _loginStateVersion)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_cookie = cookie;
|
||||
_csrfToken = loginResponse.csrfToken ?? string.Empty;
|
||||
_loginStateVersion++;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(cookie))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_loginSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从网易云歌单获取需要下载的歌曲列表,调用这个 API 需要用户登录,否则获取的歌单数据不全。
|
||||
/// </summary>
|
||||
/// <param name="songListIds">网易云音乐歌单的 ID。</param>
|
||||
/// <param name="songListIds">网易云音乐歌单的 ID,多个歌单以分号分隔。</param>
|
||||
/// <param name="outputDirectory">歌词文件的输出路径。</param>
|
||||
/// <param name="pattern">输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。</param>
|
||||
/// <param name="onQrCodeReady">
|
||||
/// 二维码就绪时的回调。CLI 不传,走原有的终端 ASCII 输出;GUI 传入后会收到可渲染的二维码数据。
|
||||
/// </param>
|
||||
/// <param name="onStateChanged">登录状态变化回调。</param>
|
||||
/// <param name="cancellationToken">取消令牌,用于中断扫码等待与歌单请求。</param>
|
||||
/// <returns>返回获取到的歌曲列表。</returns>
|
||||
public async Task<List<MusicInfo>> GetMusicInfoFromNetEaseMusicSongListAsync(string songListIds, string outputDirectory, string pattern)
|
||||
public async Task<List<MusicInfo>> GetMusicInfoFromNetEaseMusicSongListAsync(
|
||||
string songListIds,
|
||||
string outputDirectory,
|
||||
string pattern,
|
||||
Action<NetEaseQrCodePayload>? onQrCodeReady = null,
|
||||
Action<NetEaseLoginState>? onStateChanged = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(Cookie))
|
||||
if (!await LoginAsync(onQrCodeReady, onStateChanged, cancellationToken))
|
||||
{
|
||||
var loginResponse = await LoginViqQrCodeAsync();
|
||||
Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
|
||||
CsrfToken = loginResponse.csrfToken ?? string.Empty;
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
async Task<List<MusicInfo>> GetMusicInfoBySongIdAsync(string songId)
|
||||
var session = GetLoginState();
|
||||
|
||||
async Task<List<MusicInfo>> GetMusicInfoBySongIdAsync(string songId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
|
||||
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
|
||||
var response = await _warpHttpClient.PostAsync<GetMusicInfoFromNetEaseMusicSongListResponse>(
|
||||
$"{Host}/weapi/v6/playlist/detail?csrf_token={CsrfToken}", requestOption:
|
||||
$"{Host}/weapi/v6/playlist/detail?csrf_token={session.CsrfToken}", requestOption:
|
||||
request =>
|
||||
{
|
||||
request.Headers.Add("Cookie", Cookie);
|
||||
request.Headers.Add("Cookie", session.Cookie);
|
||||
request.Content = new FormUrlEncodedContent(HandleRequest(new
|
||||
{
|
||||
csrf_token = CsrfToken,
|
||||
csrf_token = session.CsrfToken,
|
||||
id = songId,
|
||||
n = 1000,
|
||||
offset = 0,
|
||||
@@ -69,11 +208,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
limit = 1000,
|
||||
}, secretKey, encSecKey));
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
|
||||
});
|
||||
}, cancellationToken: cancellationToken);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (response.Code != 200 || response.PlayList?.SongList == null)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding);
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
return response.PlayList.SongList
|
||||
@@ -88,16 +228,25 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
}
|
||||
|
||||
var musicInfoList = new List<MusicInfo>();
|
||||
foreach (var songListId in songListIds.Split(';'))
|
||||
foreach (var songListId in songListIds.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
{
|
||||
_logger.LogInformation("正在获取歌单 {SongListId} 的歌曲列表。", songListId);
|
||||
var musicInfos = await GetMusicInfoBySongIdAsync(songListId);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var musicInfos = await GetMusicInfoBySongIdAsync(songListId, cancellationToken);
|
||||
musicInfoList.AddRange(musicInfos);
|
||||
}
|
||||
|
||||
return musicInfoList;
|
||||
}
|
||||
|
||||
private (string Cookie, string CsrfToken, long Version) GetLoginState()
|
||||
{
|
||||
lock (_loginStateLock)
|
||||
{
|
||||
return (_cookie, _csrfToken, _loginStateVersion);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。
|
||||
/// </summary>
|
||||
@@ -121,73 +270,103 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
/// <summary>
|
||||
/// 通过二维码登录网易云音乐,登录成功后返回 Cookie 和 CSRF Token。
|
||||
/// </summary>
|
||||
private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync()
|
||||
/// <param name="onQrCodeReady">
|
||||
/// 二维码就绪回调。为空时保持原有行为 —— 把 ASCII 二维码打到日志里,供 CLI 在终端展示。
|
||||
/// </param>
|
||||
/// <param name="onStateChanged">登录状态变化回调。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViaQrCodeAsync(
|
||||
Action<NetEaseQrCodePayload>? onQrCodeReady,
|
||||
Action<NetEaseLoginState>? onStateChanged,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Get unikey.
|
||||
var qrCodeKeyJson = await (await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
|
||||
using var keyResponse = await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
|
||||
{
|
||||
type = 1
|
||||
})).Content.ReadAsStringAsync();
|
||||
var uniKey = JObject.Parse(qrCodeKeyJson).SelectToken("$.unikey")!.Value<string>();
|
||||
if (string.IsNullOrEmpty(uniKey)) return (null, null);
|
||||
}, cancellationToken: cancellationToken);
|
||||
var keyResponseJson = JObject.Parse(await keyResponse.Content.ReadAsStringAsync(cancellationToken));
|
||||
var uniKey = keyResponseJson.Value<string>("unikey");
|
||||
if (keyResponseJson.Value<int?>("code") != 200 || string.IsNullOrEmpty(uniKey))
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
// Generate QR code.
|
||||
var qrGenerator = new QRCodeGenerator();
|
||||
var qrCodeData = qrGenerator.CreateQrCode($"{Host}/login?codekey={uniKey}",
|
||||
QRCodeGenerator.ECCLevel.L);
|
||||
var qrCode = new AsciiQRCode(qrCodeData);
|
||||
using var qrGenerator = new QRCodeGenerator();
|
||||
var qrContent = $"{Host}/login?codekey={uniKey}";
|
||||
using var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L);
|
||||
using var qrCode = new AsciiQRCode(qrCodeData);
|
||||
var asciiQrCodeString = qrCode.GetGraphic(1, drawQuietZones: false);
|
||||
|
||||
_logger.LogInformation("请使用网易云 APP 扫码登录:");
|
||||
_logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString);
|
||||
|
||||
// Wait for login success.
|
||||
var isLogin = false;
|
||||
while (!isLogin)
|
||||
if (onQrCodeReady != null)
|
||||
{
|
||||
var (isSuccess, cookieContainer) = await CheckIsLoginAsync(uniKey);
|
||||
isLogin = isSuccess;
|
||||
onQrCodeReady(new NetEaseQrCodePayload(qrContent, uniKey, asciiQrCodeString));
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("请使用网易云 APP 扫码登录:");
|
||||
_logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString);
|
||||
}
|
||||
|
||||
if (!isLogin)
|
||||
onStateChanged?.Invoke(NetEaseLoginState.Waiting);
|
||||
var lastState = NetEaseLoginState.Waiting;
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken);
|
||||
|
||||
if (state != lastState && state != NetEaseLoginState.Succeeded)
|
||||
{
|
||||
await Task.Delay(2000);
|
||||
lastState = state;
|
||||
onStateChanged?.Invoke(state);
|
||||
}
|
||||
else
|
||||
|
||||
if (state == NetEaseLoginState.Succeeded)
|
||||
{
|
||||
return (cookieContainer?.GetCookies(new Uri(Host))["__csrf"]?.Value, cookieContainer);
|
||||
}
|
||||
}
|
||||
|
||||
return (null, null);
|
||||
if (state == NetEaseLoginState.Expired)
|
||||
{
|
||||
// 二维码已失效,继续轮询没有意义。
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
await Task.Delay(2000, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用 <paramref name="uniKey"/> 检测是否登录成功。
|
||||
/// </summary>
|
||||
/// <param name="uniKey">由网易云 API 生成的唯一 Key,用于登录。</param>
|
||||
/// <returns>
|
||||
/// 当登录成功的时候,元组 <c>isSuccess</c> 会为 true,<c>cookieContainer</c> 会包含登录成功后的 Cookie。<br/>
|
||||
/// 如果登录失败,<c>isSuccess</c> 会为 false,<c>cookieContainer</c> 会为 null。
|
||||
/// </returns>
|
||||
private async Task<(bool isSuccess, CookieContainer? cookieContainer)> CheckIsLoginAsync(string uniKey)
|
||||
private async Task<(NetEaseLoginState state, CookieContainer? cookieContainer)> CheckIsLoginAsync(
|
||||
string uniKey,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var responseMessage = await PostAsync($"{Host}/weapi/login/qrcode/client/login", new
|
||||
using var responseMessage = await PostAsync($"{Host}/weapi/login/qrcode/client/login", new
|
||||
{
|
||||
key = uniKey,
|
||||
type = 1
|
||||
});
|
||||
}, cancellationToken: cancellationToken);
|
||||
|
||||
var responseString = await responseMessage.Content.ReadAsStringAsync();
|
||||
var responseString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
|
||||
var responseCode = JObject.Parse(responseString)["code"]?.Value<int>();
|
||||
|
||||
if (responseCode != 803)
|
||||
switch (responseCode)
|
||||
{
|
||||
return (false, null);
|
||||
// 800 二维码过期、801 等待扫码、802 已扫码待确认、803 登录成功。
|
||||
case 800:
|
||||
return (NetEaseLoginState.Expired, null);
|
||||
case 801:
|
||||
return (NetEaseLoginState.Waiting, null);
|
||||
case 802:
|
||||
return (NetEaseLoginState.ScanConfirmed, null);
|
||||
case 803:
|
||||
break;
|
||||
default:
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies))
|
||||
{
|
||||
return (false, null);
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
var cookieContainer = new CookieContainer();
|
||||
@@ -196,7 +375,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
cookieContainer.SetCookies(new Uri(Host), cookie);
|
||||
}
|
||||
|
||||
return (true, cookieContainer);
|
||||
if (cookieContainer.GetCookies(new Uri(Host)).Count == 0)
|
||||
{
|
||||
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
|
||||
}
|
||||
|
||||
return (NetEaseLoginState.Succeeded, cookieContainer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -204,19 +388,34 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
|
||||
/// </summary>
|
||||
/// <param name="url">需要请求的网易云音乐 API 地址。</param>
|
||||
/// <param name="params">API 请求参数。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>
|
||||
/// 正常情况下会返回一个 <see cref="HttpResponseMessage"/> 对象。
|
||||
/// </returns>
|
||||
private async Task<HttpResponseMessage> PostAsync(string url, object @params)
|
||||
private async Task<HttpResponseMessage> PostAsync(string url, object @params,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
|
||||
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
|
||||
|
||||
return await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption:
|
||||
var response = await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption:
|
||||
request =>
|
||||
{
|
||||
request.Content = new FormUrlEncodedContent(HandleRequest(@params, secretKey, encSecKey));
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
|
||||
});
|
||||
}, cancellationToken: cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return response;
|
||||
}
|
||||
catch
|
||||
{
|
||||
response.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace ZonyLrcTools.Common.MusicScanner;
|
||||
|
||||
/// <summary>
|
||||
/// 网易云音乐扫码登录的二维码数据。
|
||||
/// </summary>
|
||||
/// <param name="Content">二维码指向的 URL,GUI 侧用它渲染二维码图片。</param>
|
||||
/// <param name="UniKey">本次登录的唯一 Key,用于轮询登录状态。</param>
|
||||
/// <param name="AsciiGraphic">ASCII 形态的二维码,CLI 在终端里直接打印它。</param>
|
||||
public sealed record NetEaseQrCodePayload(string Content, string UniKey, string AsciiGraphic);
|
||||
|
||||
/// <summary>
|
||||
/// 网易云音乐扫码登录的状态。
|
||||
/// </summary>
|
||||
public enum NetEaseLoginState
|
||||
{
|
||||
/// <summary>二维码已生成,等待用户扫码。</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>用户已扫码,等待在手机上确认。</summary>
|
||||
ScanConfirmed,
|
||||
|
||||
/// <summary>登录成功。</summary>
|
||||
Succeeded,
|
||||
|
||||
/// <summary>二维码已过期,需要重新获取。</summary>
|
||||
Expired
|
||||
}
|
||||
@@ -7,6 +7,9 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite"/>
|
||||
<!-- 直接引用 bundle 以覆盖 Microsoft.Data.Sqlite 传递进来的旧版原生包(消除 NU1903)。 -->
|
||||
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Http"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Localization"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions"/>
|
||||
@@ -24,4 +27,16 @@
|
||||
<Compile Remove="Lyrics\Providers\Kugeci\KugeciDownloader.cs"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\..\THIRD-PARTY-NOTICES.md" Link="THIRD-PARTY-NOTICES.md">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
|
||||
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="ZonyLrcTools.Tests"/>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -6,6 +6,46 @@
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
|
||||
|
||||
<!-- 统一按钮尺寸与文字对齐方式。 -->
|
||||
<Style Selector="Button">
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="Padding" Value="16,6" />
|
||||
<Setter Property="MinHeight" Value="34" />
|
||||
<Setter Property="CornerRadius" Value="6" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<!-- 主操作按钮(开始下载 / 开始解密):文字稍微加粗,和次要按钮拉开层次 -->
|
||||
<Style Selector="Button.accent">
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="18,6" />
|
||||
</Style>
|
||||
<!-- 图标与文字之间统一留白,图标本身垂直居中,避免和文字基线错位 -->
|
||||
<Style Selector="Button.accent PathIcon">
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="Width" Value="14" />
|
||||
<Setter Property="Height" Value="14" />
|
||||
</Style>
|
||||
|
||||
<!-- 设置列表中的紧凑图标按钮。 -->
|
||||
<Style Selector="Button.icon">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Padding" Value="6" />
|
||||
<Setter Property="MinWidth" Value="0" />
|
||||
<Setter Property="MinHeight" Value="0" />
|
||||
<Setter Property="CornerRadius" Value="4" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
</Style>
|
||||
<Style Selector="Button.icon:pointerover /template/ ContentPresenter">
|
||||
<Setter Property="Background" Value="{DynamicResource SeparatorBrush}" />
|
||||
</Style>
|
||||
<Style Selector="Button.icon:disabled">
|
||||
<Setter Property="Opacity" Value="0.25" />
|
||||
</Style>
|
||||
</Application.Styles>
|
||||
|
||||
<Application.Resources>
|
||||
@@ -19,6 +59,13 @@
|
||||
<StreamGeometry x:Key="SunIcon">M3.55 19.09L4.96 20.5L6.76 18.71L5.34 17.29M12 6C8.69 6 6 8.69 6 12S8.69 18 12 18 18 15.31 18 12 15.31 6 12 6M20 13H23V11H20M17.24 18.71L19.04 20.5L20.45 19.09L18.66 17.29M20.45 5.41L19.04 4L17.24 5.79L18.66 7.21M13 1H11V4H13M6.76 5.79L4.96 4L3.55 5.41L5.34 7.21L6.76 5.79M1 13H4V11H1M13 20H11V23H13Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="DownloadIcon">M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="FolderIcon">M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="LockIcon">M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="CheckCircleIcon">M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M11,16.5L6.5,12L7.91,10.59L11,13.67L16.59,8.09L18,9.5L11,16.5Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="ChevronUpIcon">M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="ChevronDownIcon">M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="ChevronRightIcon">M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="AlertIcon">M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z</StreamGeometry>
|
||||
<StreamGeometry x:Key="AccountIcon">M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z</StreamGeometry>
|
||||
|
||||
<ResourceDictionary.ThemeDictionaries>
|
||||
<ResourceDictionary x:Key="Light">
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 裁剪时保留通过反射、序列化及系统无障碍接口访问的程序集。 -->
|
||||
<linker>
|
||||
<!-- 自动注入依赖扫描程序集中的服务类型。 -->
|
||||
<assembly fullname="ZonyLrcTools.Common" preserve="all" />
|
||||
|
||||
<!-- 保留桌面服务及界面绑定使用的类型。 -->
|
||||
<assembly fullname="ZonyLrcTools.Desktop" preserve="all" />
|
||||
|
||||
<!-- Avalonia 的无障碍节点通过运行时查找创建。 -->
|
||||
<assembly fullname="Avalonia.Controls" preserve="all" />
|
||||
<assembly fullname="Avalonia.Controls.DataGrid" preserve="all" />
|
||||
<!-- Windows 无障碍提供程序还会通过 COM 激活。 -->
|
||||
<assembly fullname="Avalonia.Win32" preserve="all" />
|
||||
<assembly fullname="Avalonia.Base" preserve="all" />
|
||||
|
||||
<!-- 保留配置映射、音频元数据、解密及 SQLite 运行时加载所需类型。 -->
|
||||
<assembly fullname="YamlDotNet" preserve="all" />
|
||||
<assembly fullname="Newtonsoft.Json" preserve="all" />
|
||||
<assembly fullname="TagLibSharp" preserve="all" />
|
||||
<!-- MusicDecrypto.Library 包中的程序集名为 libmusicdecrypto。 -->
|
||||
<assembly fullname="libmusicdecrypto" preserve="all" />
|
||||
<assembly fullname="QRCoder" preserve="all" />
|
||||
<assembly fullname="SQLitePCLRaw.core" preserve="all" />
|
||||
<assembly fullname="SQLitePCLRaw.batteries_v2" preserve="all" />
|
||||
<assembly fullname="SQLitePCLRaw.provider.e_sqlite3" preserve="all" />
|
||||
</linker>
|
||||
@@ -0,0 +1,103 @@
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>解析桌面应用的配置目录。</summary>
|
||||
/// <remarks>优先使用便携目录;不可写时回退到当前用户的应用数据目录。</remarks>
|
||||
public static class AppPaths
|
||||
{
|
||||
private const string ApplicationFolderName = "ZonyLrcTools";
|
||||
private const string ConfigFileName = "config.yaml";
|
||||
|
||||
private static readonly Lazy<string> LazyConfigDirectory = new(ResolveConfigDirectory);
|
||||
|
||||
/// <summary>配置文件所在目录。</summary>
|
||||
public static string ConfigDirectory => LazyConfigDirectory.Value;
|
||||
|
||||
/// <summary>配置文件的完整路径。</summary>
|
||||
public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName);
|
||||
|
||||
/// <summary>首次启动时将随程序附带的配置复制到用户目录。</summary>
|
||||
public static void EnsureConfigFile()
|
||||
{
|
||||
if (File.Exists(ConfigFilePath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var template = Path.Combine(AppContext.BaseDirectory, ConfigFileName);
|
||||
if (!File.Exists(template))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.Equals(
|
||||
Path.GetFullPath(template),
|
||||
Path.GetFullPath(ConfigFilePath),
|
||||
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
File.Copy(template, ConfigFilePath);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// 模板无法复制时由调用方处理缺失配置。
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveConfigDirectory()
|
||||
{
|
||||
var baseDirectory = AppContext.BaseDirectory;
|
||||
if (IsWritable(baseDirectory))
|
||||
{
|
||||
return baseDirectory;
|
||||
}
|
||||
|
||||
var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||||
var fallback = Path.Combine(roaming, ApplicationFolderName);
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(fallback);
|
||||
if (IsWritable(fallback))
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// 没有可写目录时仍允许读取便携目录的配置。
|
||||
}
|
||||
|
||||
return baseDirectory;
|
||||
}
|
||||
|
||||
private static bool IsWritable(string directory)
|
||||
{
|
||||
if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var probe = Path.Combine(directory, $".write-probe-{Guid.NewGuid():N}");
|
||||
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(
|
||||
probe,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
bufferSize: 1,
|
||||
FileOptions.DeleteOnClose);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>桌面配置服务注册。</summary>
|
||||
public static class ConfigurationServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>从可写配置目录加载配置并注册设置存储。</summary>
|
||||
public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services)
|
||||
{
|
||||
AppPaths.EnsureConfigFile();
|
||||
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(AppPaths.ConfigDirectory)
|
||||
.AddYamlFile(Path.GetFileName(AppPaths.ConfigFilePath), optional: true, reloadOnChange: false)
|
||||
.Build();
|
||||
|
||||
services.Configure<GlobalOptions>(configuration);
|
||||
services.AddSingleton<ISettingsStore, SettingsStore>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>设置保存结果。</summary>
|
||||
/// <param name="IsSuccess">是否保存成功。</param>
|
||||
/// <param name="FilePath">保存成功的文件路径。</param>
|
||||
/// <param name="ErrorMessage">保存失败的原因。</param>
|
||||
public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage)
|
||||
{
|
||||
/// <summary>创建保存成功的结果。</summary>
|
||||
public static SettingsSaveResult Success(string filePath) => new(true, filePath, null);
|
||||
|
||||
/// <summary>创建保存失败的结果。</summary>
|
||||
public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage);
|
||||
}
|
||||
|
||||
/// <summary>统一管理共享配置及其持久化。</summary>
|
||||
public interface ISettingsStore
|
||||
{
|
||||
/// <summary>应用共享配置,修改后对按操作读取配置的组件立即生效。</summary>
|
||||
GlobalOptions Options { get; }
|
||||
|
||||
/// <summary>当前配置文件的完整路径。</summary>
|
||||
string ConfigFilePath { get; }
|
||||
|
||||
/// <summary>保存界面管理的配置值,不覆盖无法安全修改的文件。</summary>
|
||||
Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>保存本机手动选择的酷狗数据库路径。</summary>
|
||||
public sealed class KugouDatabaseStore
|
||||
{
|
||||
private const string FileName = "kugou.database.json";
|
||||
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
|
||||
/// <summary>本机状态文件的完整路径。</summary>
|
||||
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
|
||||
|
||||
/// <summary>读取数据库路径;文件缺失或损坏时返回空。</summary>
|
||||
public async Task<string?> LoadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
|
||||
var stored = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.KugouDatabaseSetting);
|
||||
|
||||
return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
|
||||
{
|
||||
// 缓存损坏时恢复自动查找。
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>保存数据库路径。</summary>
|
||||
public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
var setting = new KugouDatabaseSetting { DatabasePath = databasePath };
|
||||
await DesktopStateFile.WriteAsync(FilePath, setting,
|
||||
DesktopStateJsonContext.Default.KugouDatabaseSetting, ownerOnly: false, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// 缓存写入失败不影响本次使用。
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>忘记手动路径,恢复自动查找。</summary>
|
||||
public async Task ClearAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// 调用方仍可使用本次自动查找结果。
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>酷狗数据库路径的持久化格式。</summary>
|
||||
public sealed class KugouDatabaseSetting
|
||||
{
|
||||
/// <summary>数据库的完整路径。</summary>
|
||||
public string DatabasePath { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>持久化网易云登录会话。</summary>
|
||||
/// <remarks>会话属于登录凭据;Unix 文件仅限当前用户读写,Windows 继承目录权限。</remarks>
|
||||
public sealed class NetEaseSessionStore
|
||||
{
|
||||
private const string FileName = "netease.session.json";
|
||||
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
|
||||
/// <summary>会话文件的完整路径。</summary>
|
||||
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
|
||||
|
||||
/// <summary>是否存在已保存的会话。</summary>
|
||||
public bool HasStoredSession => File.Exists(FilePath);
|
||||
|
||||
/// <summary>读取会话;文件缺失或损坏时返回空。</summary>
|
||||
public async Task<NetEaseSession?> LoadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(FilePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
|
||||
var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
|
||||
var session = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.NetEaseSession);
|
||||
|
||||
return string.IsNullOrEmpty(session?.Cookie) ? null : session;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
|
||||
{
|
||||
// 损坏的缓存按未登录处理。
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>保存会话。</summary>
|
||||
public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await DesktopStateFile.WriteAsync(FilePath, session,
|
||||
DesktopStateJsonContext.Default.NetEaseSession, ownerOnly: true, cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// 缓存写入失败不影响本次会话。
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>删除已保存的会话。</summary>
|
||||
public async Task ClearAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>网易云登录凭据。</summary>
|
||||
public sealed class NetEaseSession
|
||||
{
|
||||
/// <summary>登录 Cookie。</summary>
|
||||
public string Cookie { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>请求校验令牌。</summary>
|
||||
public string CsrfToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>会话保存时间,使用 UTC。</summary>
|
||||
public DateTimeOffset SavedAtUtc { get; set; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
[JsonSerializable(typeof(NetEaseSession))]
|
||||
[JsonSerializable(typeof(KugouDatabaseSetting))]
|
||||
internal partial class DesktopStateJsonContext : JsonSerializerContext
|
||||
{
|
||||
}
|
||||
|
||||
internal static class DesktopStateFile
|
||||
{
|
||||
internal static async Task WriteAsync<T>(string path, T value, JsonTypeInfo<T> typeInfo,
|
||||
bool ownerOnly, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
var temporaryPath = path + $".{Guid.NewGuid():N}.tmp";
|
||||
var options = new FileStreamOptions
|
||||
{
|
||||
Mode = FileMode.CreateNew,
|
||||
Access = FileAccess.Write,
|
||||
Share = FileShare.None,
|
||||
Options = FileOptions.Asynchronous
|
||||
};
|
||||
if (ownerOnly && !OperatingSystem.IsWindows())
|
||||
{
|
||||
// 在创建时限制权限,避免先写入凭据再修改权限的泄露窗口。
|
||||
options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using (var stream = new FileStream(temporaryPath, options))
|
||||
{
|
||||
await JsonSerializer.SerializeAsync(stream, value, typeInfo, cancellationToken);
|
||||
await stream.FlushAsync(cancellationToken);
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(temporaryPath, path, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using YamlDotNet.Core;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.EventEmitters;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>将含控制字符的文本输出为单行双引号标量。</summary>
|
||||
public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
|
||||
{
|
||||
/// <summary>创建标量输出器。</summary>
|
||||
public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
|
||||
{
|
||||
if (eventInfo.Source.Value is string text && NeedsQuoting(text))
|
||||
{
|
||||
eventInfo.Style = ScalarStyle.DoubleQuoted;
|
||||
}
|
||||
|
||||
base.Emit(eventInfo, emitter);
|
||||
}
|
||||
|
||||
private static bool NeedsQuoting(string text)
|
||||
{
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (c is '\n' or '\r' or '\t' or '"' or '\\')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 保留首尾空格,避免普通标量读取时丢失。
|
||||
return text.Length > 0 && (text[0] == ' ' || text[^1] == ' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using YamlDotNet.Core;
|
||||
using YamlDotNet.Core.Events;
|
||||
using YamlDotNet.RepresentationModel;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <inheritdoc cref="ISettingsStore" />
|
||||
/// <remarks>只修改界面管理的值,保留其他配置和注释;无法安全修改时返回错误。</remarks>
|
||||
public sealed class SettingsStore : ISettingsStore, IDisposable
|
||||
{
|
||||
private const string RegeneratedHeaderText = "# ZonyLrcTools X 配置文件";
|
||||
|
||||
private readonly ISerializer _serializer;
|
||||
private readonly IDeserializer _deserializer;
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>使用应用共享配置创建设置存储。</summary>
|
||||
public SettingsStore(IOptions<GlobalOptions> options)
|
||||
{
|
||||
Options = options.Value;
|
||||
|
||||
_serializer = new SerializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
|
||||
// 换行符保持双引号转义形式,便于手工编辑。
|
||||
.WithEventEmitter(next => new QuotedScalarEventEmitter(next))
|
||||
.Build();
|
||||
|
||||
_deserializer = new DeserializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.IgnoreUnmatchedProperties()
|
||||
.Build();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public GlobalOptions Options { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ConfigFilePath => AppPaths.ConfigFilePath;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
var targetPath = ConfigFilePath;
|
||||
var managed = BuildManagedScalars(Options);
|
||||
|
||||
var text = await TryPatchInPlaceAsync(targetPath, managed, cancellationToken).ConfigureAwait(false)
|
||||
?? BuildFromScratch();
|
||||
|
||||
var directory = Path.GetDirectoryName(targetPath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
// 使用独立临时文件,避免多个进程互相截断写入。
|
||||
var tempPath = targetPath + $".{Guid.NewGuid():N}.tmp";
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
File.Move(tempPath, targetPath, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(tempPath);
|
||||
}
|
||||
|
||||
return SettingsSaveResult.Success(targetPath);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return SettingsSaveResult.Failure(ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_writeLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>按 YAML 节点位置修改配置;仅文件不存在时允许重新生成。</summary>
|
||||
private async Task<string?> TryPatchInPlaceAsync(
|
||||
string path,
|
||||
IReadOnlyDictionary<string, string> managed,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
var patched = PatchText(original, managed);
|
||||
if (!VerifyRoundTrip(patched, managed))
|
||||
{
|
||||
throw new InvalidDataException("无法安全修改配置文件,请检查 YAML 内容。原文件未更改。");
|
||||
}
|
||||
|
||||
return patched;
|
||||
}
|
||||
|
||||
private string BuildFromScratch()
|
||||
{
|
||||
// 新文件使用统一的 LF 行尾。
|
||||
var body = _serializer.Serialize(Options);
|
||||
return RegeneratedHeaderText + "\n" + body;
|
||||
}
|
||||
|
||||
private bool VerifyRoundTrip(string yaml, IReadOnlyDictionary<string, string> managed)
|
||||
{
|
||||
try
|
||||
{
|
||||
var parsed = _deserializer.Deserialize<GlobalOptions>(yaml);
|
||||
if (parsed == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (key, expected) in managed)
|
||||
{
|
||||
if (!string.Equals(ReadScalar(parsed, key), expected, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读取反序列化后的受管配置值。</summary>
|
||||
private static string? ReadScalar(GlobalOptions options, string path)
|
||||
{
|
||||
if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal))
|
||||
{
|
||||
var close = path.IndexOf(']');
|
||||
if (close < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = path["provider.lyric.plugin[".Length..close];
|
||||
var leaf = path[(close + 2)..];
|
||||
var plugin = options.Provider?.Lyric?.Plugin?.FirstOrDefault(p => p?.Name == name);
|
||||
if (plugin == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return leaf switch
|
||||
{
|
||||
"priority" => plugin.Priority.ToString(CultureInfo.InvariantCulture),
|
||||
"depth" => plugin.Depth.ToString(CultureInfo.InvariantCulture),
|
||||
"additional.isEnableRomanOutput" =>
|
||||
plugin.Additional != null && plugin.Additional.TryGetValue("isEnableRomanOutput", out var v)
|
||||
? Normalize(v)
|
||||
: null,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
if (path.StartsWith("provider.tag.plugin[", StringComparison.Ordinal))
|
||||
{
|
||||
var close = path.IndexOf(']');
|
||||
if (close < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = path["provider.tag.plugin[".Length..close];
|
||||
var leaf = path[(close + 2)..];
|
||||
var plugin = options.Provider?.Tag?.Plugin?.FirstOrDefault(p => p?.Name == name);
|
||||
if (plugin == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return leaf == "priority" ? plugin.Priority.ToString(CultureInfo.InvariantCulture) : null;
|
||||
}
|
||||
|
||||
return path switch
|
||||
{
|
||||
"networkOptions.isEnable" => Normalize(options.NetworkOptions?.IsEnable),
|
||||
"networkOptions.ip" => options.NetworkOptions?.Ip,
|
||||
"networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture),
|
||||
"provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine),
|
||||
// 换行符不能去除空白。
|
||||
"provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak,
|
||||
"provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation),
|
||||
"provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation),
|
||||
"provider.lyric.config.isSkipExistLyricFiles" => Normalize(options.Provider?.Lyric?.Config?.IsSkipExistLyricFiles),
|
||||
"provider.lyric.config.fileEncoding" => options.Provider?.Lyric?.Config?.FileEncoding,
|
||||
"provider.tag.blockWord.isEnable" => Normalize(options.Provider?.Tag?.BlockWord?.IsEnable),
|
||||
"provider.tag.blockWord.filePath" => options.Provider?.Tag?.BlockWord?.FilePath,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>统一布尔值的文本形式。</summary>
|
||||
private static string Normalize(bool value) => value ? "true" : "false";
|
||||
|
||||
private static string? Normalize(bool? value) => value.HasValue ? Normalize(value.Value) : null;
|
||||
|
||||
private static string Normalize(string? raw) => raw switch
|
||||
{
|
||||
null => string.Empty,
|
||||
"True" => "true",
|
||||
"False" => "false",
|
||||
_ => raw
|
||||
};
|
||||
|
||||
/// <summary>用解析器的位置替换标量,保留流式映射、注释和未管理的字段。</summary>
|
||||
private static string PatchText(string original, IReadOnlyDictionary<string, string> managed)
|
||||
{
|
||||
var stream = new YamlStream();
|
||||
stream.Load(new StringReader(original));
|
||||
if (stream.Documents.Count != 1 || stream.Documents[0].RootNode is not YamlMappingNode root)
|
||||
{
|
||||
throw new InvalidDataException("配置必须是单个 YAML 映射文档。");
|
||||
}
|
||||
|
||||
var edits = new List<(int Start, int End, string Text)>();
|
||||
var additions = new Dictionary<YamlMappingNode, Dictionary<string, object>>(ReferenceEqualityComparer.Instance);
|
||||
foreach (var (path, value) in managed)
|
||||
{
|
||||
var parts = path.Split('.');
|
||||
var current = (YamlNode)root;
|
||||
for (var i = 0; i < parts.Length; i++)
|
||||
{
|
||||
if (!current.Anchor.IsEmpty || current is not YamlMappingNode mapping)
|
||||
{
|
||||
throw new InvalidDataException($"无法安全修改带锚点或非映射的配置:{path}");
|
||||
}
|
||||
|
||||
var part = parts[i];
|
||||
var bracket = part.IndexOf('[');
|
||||
var key = bracket < 0 ? part : part[..bracket];
|
||||
if (!mapping.Children.TryGetValue(new YamlScalarNode(key), out var child))
|
||||
{
|
||||
if (bracket >= 0)
|
||||
{
|
||||
throw new InvalidDataException($"配置源已更改,请重新启动应用:{path}");
|
||||
}
|
||||
|
||||
if (!additions.TryGetValue(mapping, out var fields))
|
||||
{
|
||||
fields = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
additions.Add(mapping, fields);
|
||||
}
|
||||
|
||||
for (var j = i; j < parts.Length - 1; j++)
|
||||
{
|
||||
if (parts[j].Contains('['))
|
||||
{
|
||||
throw new InvalidDataException($"配置源已更改,请重新启动应用:{path}");
|
||||
}
|
||||
if (!fields.TryGetValue(parts[j], out var nested))
|
||||
{
|
||||
nested = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
fields.Add(parts[j], nested);
|
||||
}
|
||||
fields = (Dictionary<string, object>)nested;
|
||||
}
|
||||
fields[parts[^1]] = value;
|
||||
break;
|
||||
}
|
||||
|
||||
if (bracket >= 0)
|
||||
{
|
||||
var name = part[(bracket + 1)..^1];
|
||||
child = (child as YamlSequenceNode)?.Children.OfType<YamlMappingNode>()
|
||||
.SingleOrDefault(item => item.Children.TryGetValue(new YamlScalarNode("name"), out var node)
|
||||
&& node is YamlScalarNode scalar && scalar.Value == name)
|
||||
?? throw new InvalidDataException($"找不到配置源:{name}");
|
||||
}
|
||||
|
||||
current = child;
|
||||
if (i != parts.Length - 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (child is not YamlScalarNode existing || !child.Anchor.IsEmpty)
|
||||
{
|
||||
throw new InvalidDataException($"无法安全修改非标量或带锚点的配置:{path}");
|
||||
}
|
||||
if (existing.Value == value)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (existing.Style is ScalarStyle.Literal or ScalarStyle.Folded)
|
||||
{
|
||||
throw new InvalidDataException($"请先将多行配置值改为双引号形式:{path}。原文件未更改。");
|
||||
}
|
||||
|
||||
edits.Add(((int)child.Start.Index, (int)child.End.Index, QuoteScalar(value)));
|
||||
}
|
||||
}
|
||||
|
||||
var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
|
||||
foreach (var (mapping, fields) in additions)
|
||||
{
|
||||
if (mapping.Style == MappingStyle.Flow)
|
||||
{
|
||||
// 在首个键之前插入;空映射则插入到左花括号之后。
|
||||
var position = mapping.Children.Count > 0
|
||||
? (int)mapping.Children.First().Key.Start.Index
|
||||
: (int)mapping.End.Index + 1;
|
||||
var text = string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}"));
|
||||
edits.Add((position, position, text + (mapping.Children.Count > 0 ? ", " : string.Empty)));
|
||||
}
|
||||
else
|
||||
{
|
||||
var first = mapping.Children.First().Key;
|
||||
var indent = new string(' ', (int)first.Start.Column - 1);
|
||||
var text = string.Join(newline + indent,
|
||||
fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}"));
|
||||
edits.Add(((int)first.Start.Index, (int)first.Start.Index, text + newline + indent));
|
||||
}
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(original);
|
||||
var nextStart = original.Length;
|
||||
foreach (var edit in edits.OrderByDescending(edit => edit.Start))
|
||||
{
|
||||
if (edit.End > nextStart)
|
||||
{
|
||||
throw new InvalidDataException("配置包含重叠的 YAML 别名,无法安全修改。");
|
||||
}
|
||||
builder.Remove(edit.Start, edit.End - edit.Start).Insert(edit.Start, edit.Text);
|
||||
nextStart = edit.Start;
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string FormatValue(object value) => value is Dictionary<string, object> fields
|
||||
? "{ " + string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")) + " }"
|
||||
: QuoteScalar((string)value);
|
||||
|
||||
private static string QuoteScalar(string value) => "\"" + value
|
||||
.Replace("\\", "\\\\", StringComparison.Ordinal)
|
||||
.Replace("\"", "\\\"", StringComparison.Ordinal)
|
||||
.Replace("\r", "\\r", StringComparison.Ordinal)
|
||||
.Replace("\n", "\\n", StringComparison.Ordinal)
|
||||
.Replace("\t", "\\t", StringComparison.Ordinal)
|
||||
.Replace("\0", "\\0", StringComparison.Ordinal) + "\"";
|
||||
|
||||
/// <summary>收集设置界面管理的配置路径和值。</summary>
|
||||
private static Dictionary<string, string> BuildManagedScalars(GlobalOptions options)
|
||||
{
|
||||
var managed = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
if (options.NetworkOptions != null)
|
||||
{
|
||||
managed["networkOptions.isEnable"] = Normalize(options.NetworkOptions.IsEnable);
|
||||
managed["networkOptions.ip"] = options.NetworkOptions.Ip ?? string.Empty;
|
||||
managed["networkOptions.port"] = options.NetworkOptions.Port.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
var config = options.Provider?.Lyric?.Config;
|
||||
if (config != null)
|
||||
{
|
||||
managed["provider.lyric.config.isOneLine"] = Normalize(config.IsOneLine);
|
||||
managed["provider.lyric.config.lineBreak"] = config.LineBreak ?? string.Empty;
|
||||
managed["provider.lyric.config.isEnableTranslation"] = Normalize(config.IsEnableTranslation);
|
||||
managed["provider.lyric.config.isOnlyOutputTranslation"] = Normalize(config.IsOnlyOutputTranslation);
|
||||
managed["provider.lyric.config.isSkipExistLyricFiles"] = Normalize(config.IsSkipExistLyricFiles);
|
||||
managed["provider.lyric.config.fileEncoding"] = config.FileEncoding ?? string.Empty;
|
||||
}
|
||||
|
||||
var blockWord = options.Provider?.Tag?.BlockWord;
|
||||
if (blockWord != null)
|
||||
{
|
||||
managed["provider.tag.blockWord.isEnable"] = Normalize(blockWord.IsEnable);
|
||||
managed["provider.tag.blockWord.filePath"] = blockWord.FilePath ?? string.Empty;
|
||||
}
|
||||
|
||||
foreach (var plugin in options.Provider?.Lyric?.Plugin ?? [])
|
||||
{
|
||||
if (plugin?.Name == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var prefix = $"provider.lyric.plugin[{plugin.Name}]";
|
||||
managed[$"{prefix}.priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
managed[$"{prefix}.depth"] = plugin.Depth.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
if (plugin.Additional != null &&
|
||||
plugin.Additional.TryGetValue("isEnableRomanOutput", out var roman))
|
||||
{
|
||||
managed[$"{prefix}.additional.isEnableRomanOutput"] = Normalize(roman);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var plugin in options.Provider?.Tag?.Plugin ?? [])
|
||||
{
|
||||
if (plugin?.Name == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
managed[$"provider.tag.plugin[{plugin.Name}].priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return managed;
|
||||
}
|
||||
|
||||
/// <summary>释放写入锁。</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_writeLock.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -79,10 +79,10 @@
|
||||
<value>Music Folder</value>
|
||||
</data>
|
||||
<data name="Lyrics_SelectFolder" xml:space="preserve">
|
||||
<value>Select a folder containing music files...</value>
|
||||
<value>Select a folder containing music files…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Browse" xml:space="preserve">
|
||||
<value>Browse...</value>
|
||||
<value>Browse…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Parallel" xml:space="preserve">
|
||||
<value>Parallel Tasks</value>
|
||||
@@ -100,10 +100,10 @@
|
||||
<value>Idle</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Scanning" xml:space="preserve">
|
||||
<value>Scanning files...</value>
|
||||
<value>Scanning files…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Downloading" xml:space="preserve">
|
||||
<value>Downloading lyrics...</value>
|
||||
<value>Downloading lyrics…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Complete" xml:space="preserve">
|
||||
<value>Download Complete</value>
|
||||
@@ -134,10 +134,10 @@
|
||||
<value>Music Folder</value>
|
||||
</data>
|
||||
<data name="Album_SelectFolder" xml:space="preserve">
|
||||
<value>Select a folder containing music files...</value>
|
||||
<value>Select a folder containing music files…</value>
|
||||
</data>
|
||||
<data name="Album_Browse" xml:space="preserve">
|
||||
<value>Browse...</value>
|
||||
<value>Browse…</value>
|
||||
</data>
|
||||
<data name="Album_Parallel" xml:space="preserve">
|
||||
<value>Parallel Tasks</value>
|
||||
@@ -258,4 +258,263 @@
|
||||
<data name="Error_NoMusicFiles" xml:space="preserve">
|
||||
<value>No music files found in the selected folder.</value>
|
||||
</data>
|
||||
<!-- Decryption / Settings / Home additions -->
|
||||
<data name="Nav_Decrypt" xml:space="preserve">
|
||||
<value>Music Decryption</value>
|
||||
</data>
|
||||
<data name="Decrypt_Title" xml:space="preserve">
|
||||
<value>Music Decryption</value>
|
||||
</data>
|
||||
<data name="Decrypt_Description" xml:space="preserve">
|
||||
<value>Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats</value>
|
||||
</data>
|
||||
<data name="Decrypt_SelectFiles" xml:space="preserve">
|
||||
<value>Select encrypted music files…</value>
|
||||
</data>
|
||||
<data name="Decrypt_Browse" xml:space="preserve">
|
||||
<value>Add Files…</value>
|
||||
</data>
|
||||
<data name="Decrypt_Parallel" xml:space="preserve">
|
||||
<value>Parallel:</value>
|
||||
</data>
|
||||
<data name="Decrypt_Start" xml:space="preserve">
|
||||
<value>Start Decrypt</value>
|
||||
</data>
|
||||
<data name="Decrypt_Stop" xml:space="preserve">
|
||||
<value>Stop</value>
|
||||
</data>
|
||||
<data name="Decrypt_EmptyState" xml:space="preserve">
|
||||
<value>No files yet, add files to start decrypting</value>
|
||||
</data>
|
||||
<data name="Decrypt_Clear" xml:space="preserve">
|
||||
<value>Clear</value>
|
||||
</data>
|
||||
<data name="Decrypt_FilesLabel" xml:space="preserve">
|
||||
<value>Files</value>
|
||||
</data>
|
||||
<data name="Column_FileName" xml:space="preserve">
|
||||
<value>File Name</value>
|
||||
</data>
|
||||
<data name="Column_OutputPath" xml:space="preserve">
|
||||
<value>Output</value>
|
||||
</data>
|
||||
<data name="Settings_BasicSection" xml:space="preserve">
|
||||
<value>Basic Settings</value>
|
||||
</data>
|
||||
<data name="Settings_AdvancedSection" xml:space="preserve">
|
||||
<value>Advanced Settings</value>
|
||||
</data>
|
||||
<data name="Settings_ShowAdvanced" xml:space="preserve">
|
||||
<value>Show advanced settings</value>
|
||||
</data>
|
||||
<data name="Settings_LyricsSection" xml:space="preserve">
|
||||
<value>Lyrics Settings</value>
|
||||
</data>
|
||||
<data name="Settings_EnableTranslation" xml:space="preserve">
|
||||
<value>Enable translation lyrics</value>
|
||||
</data>
|
||||
<data name="Settings_OneLineMode" xml:space="preserve">
|
||||
<value>One-line mode (original + translation on the same line)</value>
|
||||
</data>
|
||||
<data name="Settings_OnlyTranslation" xml:space="preserve">
|
||||
<value>Only output translation lyrics</value>
|
||||
</data>
|
||||
<data name="Settings_SkipExisting" xml:space="preserve">
|
||||
<value>Skip existing lyrics files</value>
|
||||
</data>
|
||||
<data name="Settings_FileEncoding" xml:space="preserve">
|
||||
<value>File Encoding:</value>
|
||||
</data>
|
||||
<data name="Settings_LineBreak" xml:space="preserve">
|
||||
<value>Line Break:</value>
|
||||
</data>
|
||||
<data name="Settings_RomanOutput" xml:space="preserve">
|
||||
<value>Output romanized lyrics</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordSection" xml:space="preserve">
|
||||
<value>Block Words</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordEnable" xml:space="preserve">
|
||||
<value>Enable block word filtering</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordPath" xml:space="preserve">
|
||||
<value>Block Words File (relative to current working directory):</value>
|
||||
</data>
|
||||
<data name="Settings_TagProvider" xml:space="preserve">
|
||||
<value>Tag Providers</value>
|
||||
</data>
|
||||
<data name="Settings_Priority" xml:space="preserve">
|
||||
<value>Priority</value>
|
||||
</data>
|
||||
<data name="Settings_Storage" xml:space="preserve">
|
||||
<value>Configuration File</value>
|
||||
</data>
|
||||
<data name="Settings_Saved" xml:space="preserve">
|
||||
<value>Settings saved</value>
|
||||
</data>
|
||||
<data name="Settings_SaveFailed" xml:space="preserve">
|
||||
<value>Failed to save settings</value>
|
||||
</data>
|
||||
<data name="Settings_ProxyRestartHint" xml:space="preserve">
|
||||
<value>Restart the application for proxy changes to take effect.</value>
|
||||
</data>
|
||||
<data name="Settings_ResetConfirm" xml:space="preserve">
|
||||
<value>Reset all settings to their default values?</value>
|
||||
</data>
|
||||
<data name="Home_QuickActions" xml:space="preserve">
|
||||
<value>Quick Actions</value>
|
||||
</data>
|
||||
<data name="Home_Decrypt" xml:space="preserve">
|
||||
<value>Decrypt Music</value>
|
||||
</data>
|
||||
<data name="Home_FeatureFormats" xml:space="preserve">
|
||||
<value>Supports NetEase, QQ Music, KuGou and KuWo lyric sources</value>
|
||||
</data>
|
||||
<data name="Home_FeatureParallel" xml:space="preserve">
|
||||
<value>Parallel downloads with automatic overwrite protection</value>
|
||||
</data>
|
||||
<data name="Home_FeatureEncodings" xml:space="preserve">
|
||||
<value>Multiple file encodings and translated lyrics output</value>
|
||||
</data>
|
||||
<data name="Home_FeatureCrossPlatform" xml:space="preserve">
|
||||
<value>Runs on Windows, Linux and macOS</value>
|
||||
</data>
|
||||
<data name="Home_GetStarted" xml:space="preserve">
|
||||
<value>Get Started</value>
|
||||
</data>
|
||||
<data name="Lyrics_Scanner" xml:space="preserve">
|
||||
<value>Source</value>
|
||||
</data>
|
||||
<data name="Scanner_Local" xml:space="preserve">
|
||||
<value>Local Folder</value>
|
||||
</data>
|
||||
<data name="Scanner_Csv" xml:space="preserve">
|
||||
<value>CSV File</value>
|
||||
</data>
|
||||
<data name="Scanner_NetEase" xml:space="preserve">
|
||||
<value>NetEase Playlist</value>
|
||||
</data>
|
||||
<data name="Lyrics_Scan" xml:space="preserve">
|
||||
<value>Scan</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvLabel" xml:space="preserve">
|
||||
<value>CSV File</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvSelect" xml:space="preserve">
|
||||
<value>Select a CSV file…</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvBrowse" xml:space="preserve">
|
||||
<value>Choose…</value>
|
||||
</data>
|
||||
<data name="Lyrics_SongListLabel" xml:space="preserve">
|
||||
<value>Playlist ID</value>
|
||||
</data>
|
||||
<data name="Lyrics_SongListWatermark" xml:space="preserve">
|
||||
<value>e.g. 7224428149 (separate multiple ids with ;)</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputLabel" xml:space="preserve">
|
||||
<value>Save To</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputSelect" xml:space="preserve">
|
||||
<value>Where the .lrc files should be written</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputBrowse" xml:space="preserve">
|
||||
<value>Choose…</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginTitle" xml:space="preserve">
|
||||
<value>Sign in to NetEase Cloud Music</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginTip" xml:space="preserve">
|
||||
<value>Scan the QR code with the NetEase Cloud Music app on your phone.</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginWaiting" xml:space="preserve">
|
||||
<value>Waiting for you to scan…</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginScanned" xml:space="preserve">
|
||||
<value>Scanned, please confirm on your phone.</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginSucceeded" xml:space="preserve">
|
||||
<value>Signed in.</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginExpired" xml:space="preserve">
|
||||
<value>The QR code expired. Close this dialog and try again.</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginFailed" xml:space="preserve">
|
||||
<value>Login did not complete. Close this dialog and try again.</value>
|
||||
</data>
|
||||
<data name="Home_Features" xml:space="preserve">
|
||||
<value>Features</value>
|
||||
</data>
|
||||
<data name="Home_Version" xml:space="preserve">
|
||||
<value>Version</value>
|
||||
</data>
|
||||
<data name="Home_DownloadLyricsHint" xml:space="preserve">
|
||||
<value>Batch download lyrics for your music files</value>
|
||||
</data>
|
||||
<data name="Home_DownloadAlbumCoverHint" xml:space="preserve">
|
||||
<value>Fetch album artwork for your collection</value>
|
||||
</data>
|
||||
<data name="Home_DecryptHint" xml:space="preserve">
|
||||
<value>Decrypt protected music files</value>
|
||||
</data>
|
||||
<data name="Settings_MoveUp" xml:space="preserve">
|
||||
<value>Move up</value>
|
||||
</data>
|
||||
<data name="Settings_MoveDown" xml:space="preserve">
|
||||
<value>Move down</value>
|
||||
</data>
|
||||
<data name="Decrypt_KugouMissing" xml:space="preserve">
|
||||
<value>kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)</value>
|
||||
</data>
|
||||
<data name="Decrypt_SelectDatabase" xml:space="preserve">
|
||||
<value>Choose Database…</value>
|
||||
</data>
|
||||
<data name="Decrypt_DatabaseOk" xml:space="preserve">
|
||||
<value>{0} decryption keys loaded</value>
|
||||
</data>
|
||||
<data name="Decrypt_DatabaseMissing" xml:space="preserve">
|
||||
<value>KuGou database not found, kgg files cannot be decrypted</value>
|
||||
</data>
|
||||
<data name="Decrypt_SpecifyDatabase" xml:space="preserve">
|
||||
<value>Locate Database…</value>
|
||||
</data>
|
||||
<data name="Decrypt_StatusMissingDb" xml:space="preserve">
|
||||
<value>KuGou database missing</value>
|
||||
</data>
|
||||
<data name="Decrypt_ViewDetail" xml:space="preserve">
|
||||
<value>View details</value>
|
||||
</data>
|
||||
<data name="Decrypt_FailureTitle" xml:space="preserve">
|
||||
<value>Decryption failure</value>
|
||||
</data>
|
||||
<data name="Settings_ProviderOrderHint" xml:space="preserve">
|
||||
<value>The list order is the search order. Use the arrows on the right to change which source is tried first.</value>
|
||||
</data>
|
||||
<data name="NetEase_SignOut" xml:space="preserve">
|
||||
<value>Sign out</value>
|
||||
</data>
|
||||
<data name="NetEase_SignOutHint" xml:space="preserve">
|
||||
<value>Forget the saved session so the next playlist scan asks for a QR login again.</value>
|
||||
</data>
|
||||
<data name="NetEase_SignedOut" xml:space="preserve">
|
||||
<value>Signed out. The next playlist scan will ask for a QR login.</value>
|
||||
</data>
|
||||
<data name="NetEase_SignIn" xml:space="preserve">
|
||||
<value>Sign in…</value>
|
||||
</data>
|
||||
<data name="NetEase_SignInHint" xml:space="preserve">
|
||||
<value>Scan a QR code now instead of waiting until the next scan.</value>
|
||||
</data>
|
||||
<data name="NetEase_LoggedIn" xml:space="preserve">
|
||||
<value>Signed in. Scanning a playlist reuses this session.</value>
|
||||
</data>
|
||||
<data name="NetEase_NotLoggedIn" xml:space="preserve">
|
||||
<value>Not signed in. Scanning a playlist will show a QR code.</value>
|
||||
</data>
|
||||
<data name="NetEase_AccountLabel" xml:space="preserve">
|
||||
<value>Account</value>
|
||||
</data>
|
||||
<data name="Common_Copy" xml:space="preserve">
|
||||
<value>Copy</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -79,10 +79,10 @@
|
||||
<value>音乐文件夹</value>
|
||||
</data>
|
||||
<data name="Lyrics_SelectFolder" xml:space="preserve">
|
||||
<value>请选择包含音乐文件的目录...</value>
|
||||
<value>请选择包含音乐文件的目录…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Browse" xml:space="preserve">
|
||||
<value>浏览...</value>
|
||||
<value>浏览…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Parallel" xml:space="preserve">
|
||||
<value>并行任务数</value>
|
||||
@@ -100,10 +100,10 @@
|
||||
<value>等待中</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Scanning" xml:space="preserve">
|
||||
<value>正在扫描文件...</value>
|
||||
<value>正在扫描文件…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Downloading" xml:space="preserve">
|
||||
<value>正在下载歌词...</value>
|
||||
<value>正在下载歌词…</value>
|
||||
</data>
|
||||
<data name="Lyrics_Status_Complete" xml:space="preserve">
|
||||
<value>下载完成</value>
|
||||
@@ -134,10 +134,10 @@
|
||||
<value>音乐文件夹</value>
|
||||
</data>
|
||||
<data name="Album_SelectFolder" xml:space="preserve">
|
||||
<value>请选择包含音乐文件的目录...</value>
|
||||
<value>请选择包含音乐文件的目录…</value>
|
||||
</data>
|
||||
<data name="Album_Browse" xml:space="preserve">
|
||||
<value>浏览...</value>
|
||||
<value>浏览…</value>
|
||||
</data>
|
||||
<data name="Album_Parallel" xml:space="preserve">
|
||||
<value>并行任务数</value>
|
||||
@@ -258,4 +258,263 @@
|
||||
<data name="Error_NoMusicFiles" xml:space="preserve">
|
||||
<value>在所选文件夹中没有找到任何音乐文件。</value>
|
||||
</data>
|
||||
<!-- Decryption / Settings / Home additions -->
|
||||
<data name="Nav_Decrypt" xml:space="preserve">
|
||||
<value>音乐解密</value>
|
||||
</data>
|
||||
<data name="Decrypt_Title" xml:space="preserve">
|
||||
<value>音乐解密</value>
|
||||
</data>
|
||||
<data name="Decrypt_Description" xml:space="preserve">
|
||||
<value>将加密的音乐文件(ncm / qmc / kgm / kgg / kwm)转换为可播放格式</value>
|
||||
</data>
|
||||
<data name="Decrypt_SelectFiles" xml:space="preserve">
|
||||
<value>请选择要解密的加密音乐文件…</value>
|
||||
</data>
|
||||
<data name="Decrypt_Browse" xml:space="preserve">
|
||||
<value>添加文件…</value>
|
||||
</data>
|
||||
<data name="Decrypt_Parallel" xml:space="preserve">
|
||||
<value>并行数:</value>
|
||||
</data>
|
||||
<data name="Decrypt_Start" xml:space="preserve">
|
||||
<value>开始解密</value>
|
||||
</data>
|
||||
<data name="Decrypt_Stop" xml:space="preserve">
|
||||
<value>停止</value>
|
||||
</data>
|
||||
<data name="Decrypt_EmptyState" xml:space="preserve">
|
||||
<value>暂无文件,请添加文件后开始解密</value>
|
||||
</data>
|
||||
<data name="Decrypt_Clear" xml:space="preserve">
|
||||
<value>清空</value>
|
||||
</data>
|
||||
<data name="Decrypt_FilesLabel" xml:space="preserve">
|
||||
<value>文件</value>
|
||||
</data>
|
||||
<data name="Column_FileName" xml:space="preserve">
|
||||
<value>文件名</value>
|
||||
</data>
|
||||
<data name="Column_OutputPath" xml:space="preserve">
|
||||
<value>输出路径</value>
|
||||
</data>
|
||||
<data name="Settings_BasicSection" xml:space="preserve">
|
||||
<value>基础设置</value>
|
||||
</data>
|
||||
<data name="Settings_AdvancedSection" xml:space="preserve">
|
||||
<value>高级设置</value>
|
||||
</data>
|
||||
<data name="Settings_ShowAdvanced" xml:space="preserve">
|
||||
<value>显示高级设置</value>
|
||||
</data>
|
||||
<data name="Settings_LyricsSection" xml:space="preserve">
|
||||
<value>歌词设置</value>
|
||||
</data>
|
||||
<data name="Settings_EnableTranslation" xml:space="preserve">
|
||||
<value>启用翻译歌词</value>
|
||||
</data>
|
||||
<data name="Settings_OneLineMode" xml:space="preserve">
|
||||
<value>单行模式(原文与翻译在同一行)</value>
|
||||
</data>
|
||||
<data name="Settings_OnlyTranslation" xml:space="preserve">
|
||||
<value>只输出翻译歌词</value>
|
||||
</data>
|
||||
<data name="Settings_SkipExisting" xml:space="preserve">
|
||||
<value>跳过已存在的歌词文件</value>
|
||||
</data>
|
||||
<data name="Settings_FileEncoding" xml:space="preserve">
|
||||
<value>文件编码:</value>
|
||||
</data>
|
||||
<data name="Settings_LineBreak" xml:space="preserve">
|
||||
<value>换行符:</value>
|
||||
</data>
|
||||
<data name="Settings_RomanOutput" xml:space="preserve">
|
||||
<value>输出罗马音歌词</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordSection" xml:space="preserve">
|
||||
<value>屏蔽词</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordEnable" xml:space="preserve">
|
||||
<value>启用屏蔽词过滤</value>
|
||||
</data>
|
||||
<data name="Settings_BlockWordPath" xml:space="preserve">
|
||||
<value>屏蔽词文件路径(相对当前工作目录):</value>
|
||||
</data>
|
||||
<data name="Settings_TagProvider" xml:space="preserve">
|
||||
<value>标签源</value>
|
||||
</data>
|
||||
<data name="Settings_Priority" xml:space="preserve">
|
||||
<value>优先级</value>
|
||||
</data>
|
||||
<data name="Settings_Storage" xml:space="preserve">
|
||||
<value>配置文件位置</value>
|
||||
</data>
|
||||
<data name="Settings_Saved" xml:space="preserve">
|
||||
<value>设置已保存</value>
|
||||
</data>
|
||||
<data name="Settings_SaveFailed" xml:space="preserve">
|
||||
<value>设置保存失败</value>
|
||||
</data>
|
||||
<data name="Settings_ProxyRestartHint" xml:space="preserve">
|
||||
<value>修改代理设置后需要重启程序才能生效。</value>
|
||||
</data>
|
||||
<data name="Settings_ResetConfirm" xml:space="preserve">
|
||||
<value>确定要将所有设置恢复为默认值吗?</value>
|
||||
</data>
|
||||
<data name="Home_QuickActions" xml:space="preserve">
|
||||
<value>快速操作</value>
|
||||
</data>
|
||||
<data name="Home_Decrypt" xml:space="preserve">
|
||||
<value>解密音乐</value>
|
||||
</data>
|
||||
<data name="Home_FeatureFormats" xml:space="preserve">
|
||||
<value>支持网易云、QQ音乐、酷狗、酷我四大歌词源</value>
|
||||
</data>
|
||||
<data name="Home_FeatureParallel" xml:space="preserve">
|
||||
<value>多线程并行下载,自动规避覆盖</value>
|
||||
</data>
|
||||
<data name="Home_FeatureEncodings" xml:space="preserve">
|
||||
<value>支持多种文件编码与翻译歌词输出</value>
|
||||
</data>
|
||||
<data name="Home_FeatureCrossPlatform" xml:space="preserve">
|
||||
<value>跨平台运行,支持 Windows、Linux 与 macOS</value>
|
||||
</data>
|
||||
<data name="Home_GetStarted" xml:space="preserve">
|
||||
<value>开始使用</value>
|
||||
</data>
|
||||
<data name="Lyrics_Scanner" xml:space="preserve">
|
||||
<value>来源</value>
|
||||
</data>
|
||||
<data name="Scanner_Local" xml:space="preserve">
|
||||
<value>本地文件夹</value>
|
||||
</data>
|
||||
<data name="Scanner_Csv" xml:space="preserve">
|
||||
<value>CSV 文件</value>
|
||||
</data>
|
||||
<data name="Scanner_NetEase" xml:space="preserve">
|
||||
<value>网易云歌单</value>
|
||||
</data>
|
||||
<data name="Lyrics_Scan" xml:space="preserve">
|
||||
<value>解析</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvLabel" xml:space="preserve">
|
||||
<value>CSV 文件</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvSelect" xml:space="preserve">
|
||||
<value>请选择 CSV 文件…</value>
|
||||
</data>
|
||||
<data name="Lyrics_CsvBrowse" xml:space="preserve">
|
||||
<value>选择…</value>
|
||||
</data>
|
||||
<data name="Lyrics_SongListLabel" xml:space="preserve">
|
||||
<value>歌单 ID</value>
|
||||
</data>
|
||||
<data name="Lyrics_SongListWatermark" xml:space="preserve">
|
||||
<value>例如 7224428149(多个歌单用分号分隔)</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputLabel" xml:space="preserve">
|
||||
<value>保存到</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputSelect" xml:space="preserve">
|
||||
<value>歌词文件的输出目录</value>
|
||||
</data>
|
||||
<data name="Lyrics_OutputBrowse" xml:space="preserve">
|
||||
<value>选择…</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginTitle" xml:space="preserve">
|
||||
<value>登录网易云音乐</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginTip" xml:space="preserve">
|
||||
<value>请使用手机上的网易云音乐 App 扫描二维码。</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginWaiting" xml:space="preserve">
|
||||
<value>等待扫码…</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginScanned" xml:space="preserve">
|
||||
<value>已扫码,请在手机上确认。</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginSucceeded" xml:space="preserve">
|
||||
<value>登录成功。</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginExpired" xml:space="preserve">
|
||||
<value>二维码已过期,请关闭窗口后重新登录。</value>
|
||||
</data>
|
||||
<data name="NetEase_LoginFailed" xml:space="preserve">
|
||||
<value>登录未完成,请关闭窗口后重试。</value>
|
||||
</data>
|
||||
<data name="Home_Features" xml:space="preserve">
|
||||
<value>功能特性</value>
|
||||
</data>
|
||||
<data name="Home_Version" xml:space="preserve">
|
||||
<value>版本</value>
|
||||
</data>
|
||||
<data name="Home_DownloadLyricsHint" xml:space="preserve">
|
||||
<value>批量下载音乐文件的歌词</value>
|
||||
</data>
|
||||
<data name="Home_DownloadAlbumCoverHint" xml:space="preserve">
|
||||
<value>为音乐库获取专辑封面</value>
|
||||
</data>
|
||||
<data name="Home_DecryptHint" xml:space="preserve">
|
||||
<value>解密受保护的音乐文件</value>
|
||||
</data>
|
||||
<data name="Settings_MoveUp" xml:space="preserve">
|
||||
<value>上移</value>
|
||||
</data>
|
||||
<data name="Settings_MoveDown" xml:space="preserve">
|
||||
<value>下移</value>
|
||||
</data>
|
||||
<data name="Decrypt_KugouMissing" xml:space="preserve">
|
||||
<value>kgg 解密需要酷狗数据库 KGMusicV3.db(酷狗下载过该歌曲才会写入密钥)</value>
|
||||
</data>
|
||||
<data name="Decrypt_SelectDatabase" xml:space="preserve">
|
||||
<value>选择数据库文件…</value>
|
||||
</data>
|
||||
<data name="Decrypt_DatabaseOk" xml:space="preserve">
|
||||
<value>已读取 {0} 个解密密钥</value>
|
||||
</data>
|
||||
<data name="Decrypt_DatabaseMissing" xml:space="preserve">
|
||||
<value>未找到酷狗数据库,kgg 文件将无法解密</value>
|
||||
</data>
|
||||
<data name="Decrypt_SpecifyDatabase" xml:space="preserve">
|
||||
<value>指定数据库…</value>
|
||||
</data>
|
||||
<data name="Decrypt_StatusMissingDb" xml:space="preserve">
|
||||
<value>缺少酷狗数据库</value>
|
||||
</data>
|
||||
<data name="Decrypt_ViewDetail" xml:space="preserve">
|
||||
<value>查看详情</value>
|
||||
</data>
|
||||
<data name="Decrypt_FailureTitle" xml:space="preserve">
|
||||
<value>解密失败原因</value>
|
||||
</data>
|
||||
<data name="Settings_ProviderOrderHint" xml:space="preserve">
|
||||
<value>列表顺序即搜索顺序,用右侧箭头调整优先尝试哪一家。</value>
|
||||
</data>
|
||||
<data name="NetEase_SignOut" xml:space="preserve">
|
||||
<value>退出登录</value>
|
||||
</data>
|
||||
<data name="NetEase_SignOutHint" xml:space="preserve">
|
||||
<value>清除已保存的登录状态,下次解析歌单需要重新扫码。</value>
|
||||
</data>
|
||||
<data name="NetEase_SignedOut" xml:space="preserve">
|
||||
<value>已退出登录,下次解析歌单需要重新扫码。</value>
|
||||
</data>
|
||||
<data name="NetEase_SignIn" xml:space="preserve">
|
||||
<value>登录…</value>
|
||||
</data>
|
||||
<data name="NetEase_SignInHint" xml:space="preserve">
|
||||
<value>立即扫码登录,不必等到下次解析歌单。</value>
|
||||
</data>
|
||||
<data name="NetEase_LoggedIn" xml:space="preserve">
|
||||
<value>已登录,解析歌单会直接使用这个会话。</value>
|
||||
</data>
|
||||
<data name="NetEase_NotLoggedIn" xml:space="preserve">
|
||||
<value>未登录,解析歌单时会弹出二维码。</value>
|
||||
</data>
|
||||
<data name="NetEase_AccountLabel" xml:space="preserve">
|
||||
<value>账号状态</value>
|
||||
</data>
|
||||
<data name="Common_Copy" xml:space="preserve">
|
||||
<value>复制</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -2,6 +2,8 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Platform.Storage;
|
||||
using Avalonia.Threading;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
using ZonyLrcTools.Desktop.Views.Dialogs;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Services;
|
||||
@@ -23,27 +25,77 @@ public class DialogService : IDialogService
|
||||
AllowMultiple = false
|
||||
});
|
||||
|
||||
return folders.FirstOrDefault()?.Path.LocalPath;
|
||||
return folders.FirstOrDefault()?.TryGetLocalPath();
|
||||
}
|
||||
|
||||
public async Task<string?> ShowFilePickerAsync(string title, string[]? filters = null)
|
||||
{
|
||||
if (MainWindow == null) return null;
|
||||
|
||||
var fileTypes = filters?.Select(f => new FilePickerFileType(f)
|
||||
{
|
||||
Patterns = new[] { f }
|
||||
}).ToList();
|
||||
|
||||
var files = await MainWindow.StorageProvider.OpenFilePickerAsync(
|
||||
new FilePickerOpenOptions
|
||||
{
|
||||
Title = title,
|
||||
AllowMultiple = false,
|
||||
FileTypeFilter = fileTypes
|
||||
FileTypeFilter = BuildFileTypes(filters)
|
||||
});
|
||||
|
||||
return files.FirstOrDefault()?.Path.LocalPath;
|
||||
return files.FirstOrDefault()?.TryGetLocalPath();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (MainWindow == null) return Array.Empty<string>();
|
||||
|
||||
var fileTypes = BuildFileTypes(filters);
|
||||
|
||||
var files = await MainWindow.StorageProvider.OpenFilePickerAsync(
|
||||
new FilePickerOpenOptions
|
||||
{
|
||||
Title = title,
|
||||
AllowMultiple = true,
|
||||
FileTypeFilter = fileTypes
|
||||
});
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
return files
|
||||
.Select(f => f.TryGetLocalPath())
|
||||
.OfType<string>()
|
||||
.Where(p => !string.IsNullOrEmpty(p))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将文件扩展名转换为文件选择器筛选条件。
|
||||
/// </summary>
|
||||
private static List<FilePickerFileType>? BuildFileTypes(string[]? filters)
|
||||
{
|
||||
if (filters == null || filters.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var patterns = filters
|
||||
.Where(f => !string.IsNullOrWhiteSpace(f))
|
||||
.Select(f => f.StartsWith('*') ? f : $"*.{f.TrimStart('.')}")
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
if (patterns.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = string.Join(" / ", patterns.Select(p => p.TrimStart('*', '.')));
|
||||
|
||||
return new List<FilePickerFileType>
|
||||
{
|
||||
new(name) { Patterns = patterns },
|
||||
new("All files") { Patterns = new[] { "*" } }
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<bool> ShowConfirmDialogAsync(string title, string message)
|
||||
@@ -62,4 +114,20 @@ public class DialogService : IDialogService
|
||||
var dialog = new MessageDialog(title, message);
|
||||
await dialog.ShowDialog(MainWindow);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (MainWindow == null)
|
||||
{
|
||||
viewModel.NotifyClosed();
|
||||
return;
|
||||
}
|
||||
|
||||
var dialog = new QrCodeLoginDialog(viewModel);
|
||||
using var registration = cancellationToken.Register(
|
||||
() => Dispatcher.UIThread.Post(viewModel.RequestClose));
|
||||
await dialog.ShowDialog(MainWindow);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,25 @@
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Services;
|
||||
|
||||
public interface IDialogService
|
||||
{
|
||||
Task<string?> ShowFolderPickerAsync(string title);
|
||||
|
||||
Task<string?> ShowFilePickerAsync(string title, string[]? filters = null);
|
||||
|
||||
/// <summary>
|
||||
/// 选择多个本地文件。
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<bool> ShowConfirmDialogAsync(string title, string message);
|
||||
|
||||
Task ShowMessageAsync(string title, string message);
|
||||
|
||||
/// <summary>
|
||||
/// 显示网易云扫码登录对话框,关闭窗口后返回。
|
||||
/// </summary>
|
||||
Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -7,7 +7,16 @@ public interface INavigationService
|
||||
ViewModelBase? CurrentViewModel { get; }
|
||||
event EventHandler<ViewModelBase>? NavigationChanged;
|
||||
|
||||
/// <summary>
|
||||
/// 打开页面并保留返回记录。
|
||||
/// </summary>
|
||||
TViewModel NavigateTo<TViewModel>() where TViewModel : ViewModelBase;
|
||||
|
||||
/// <summary>
|
||||
/// 切换顶层页面并清空返回记录。
|
||||
/// </summary>
|
||||
TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase;
|
||||
|
||||
void GoBack();
|
||||
bool CanGoBack { get; }
|
||||
}
|
||||
@@ -22,13 +22,44 @@ public class NavigationService : INavigationService
|
||||
{
|
||||
var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
|
||||
|
||||
if (_navigationStack.TryPeek(out var current))
|
||||
if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel))
|
||||
{
|
||||
_ = current.OnDeactivatedAsync();
|
||||
// 当前页面无需重复激活。
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
if (_navigationStack.TryPeek(out current))
|
||||
{
|
||||
_ = SafeDeactivateAsync(current);
|
||||
}
|
||||
|
||||
_navigationStack.Push(viewModel);
|
||||
_ = viewModel.OnActivatedAsync();
|
||||
_ = SafeActivateAsync(viewModel);
|
||||
|
||||
NavigationChanged?.Invoke(this, viewModel);
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase
|
||||
{
|
||||
var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
|
||||
|
||||
if (_navigationStack.Count == 1 && ReferenceEquals(_navigationStack.Peek(), viewModel))
|
||||
{
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
while (_navigationStack.TryPop(out var previous))
|
||||
{
|
||||
if (!ReferenceEquals(previous, viewModel))
|
||||
{
|
||||
_ = SafeDeactivateAsync(previous);
|
||||
}
|
||||
}
|
||||
|
||||
_navigationStack.Push(viewModel);
|
||||
_ = SafeActivateAsync(viewModel);
|
||||
|
||||
NavigationChanged?.Invoke(this, viewModel);
|
||||
return viewModel;
|
||||
@@ -39,12 +70,39 @@ public class NavigationService : INavigationService
|
||||
if (!CanGoBack) return;
|
||||
|
||||
var current = _navigationStack.Pop();
|
||||
_ = current.OnDeactivatedAsync();
|
||||
_ = SafeDeactivateAsync(current);
|
||||
|
||||
if (_navigationStack.TryPeek(out var previous))
|
||||
{
|
||||
_ = previous.OnActivatedAsync();
|
||||
_ = SafeActivateAsync(previous);
|
||||
NavigationChanged?.Invoke(this, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 页面激活失败时不打断导航。
|
||||
/// </summary>
|
||||
private static async Task SafeActivateAsync(ViewModelBase viewModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
await viewModel.OnActivatedAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 页面自行处理错误,避免中断导航。
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SafeDeactivateAsync(ViewModelBase viewModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
await viewModel.OnDeactivatedAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 页面自行处理错误,避免中断导航。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
@@ -20,7 +21,8 @@ public static class ServiceCollectionExtensions
|
||||
services.BeginAutoDependencyInject<IWarpHttpClient>();
|
||||
|
||||
// Configure Common services
|
||||
services.ConfigureConfiguration();
|
||||
// 桌面端使用可写的配置目录,避免只读安装位置导致保存失败。
|
||||
services.ConfigureDesktopConfiguration();
|
||||
services.ConfigureLocalization();
|
||||
services.ConfigureToolService();
|
||||
|
||||
@@ -39,11 +41,18 @@ public static class ServiceCollectionExtensions
|
||||
services.AddSingleton<IDialogService, DialogService>();
|
||||
services.AddSingleton<IThemeService, ThemeService>();
|
||||
|
||||
// 保存网易云登录状态。
|
||||
services.AddSingleton<NetEaseSessionStore>();
|
||||
|
||||
// 保存本机酷狗数据库路径。
|
||||
services.AddSingleton<KugouDatabaseStore>();
|
||||
|
||||
// Register ViewModels (Singleton to preserve state across navigation)
|
||||
services.AddSingleton<MainWindowViewModel>();
|
||||
services.AddSingleton<HomeViewModel>();
|
||||
services.AddSingleton<LyricsDownloadViewModel>();
|
||||
services.AddSingleton<AlbumDownloadViewModel>();
|
||||
services.AddSingleton<DecryptViewModel>();
|
||||
services.AddSingleton<SettingsViewModel>();
|
||||
|
||||
return services;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZonyLrcTools.Common;
|
||||
using ZonyLrcTools.Common.Album;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common.TagInfo;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.Services;
|
||||
|
||||
@@ -11,9 +18,14 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
{
|
||||
private readonly IAlbumDownloader _albumDownloader;
|
||||
private readonly IDialogService _dialogService;
|
||||
private readonly IFileScanner _fileScanner;
|
||||
private readonly ITagLoader _tagLoader;
|
||||
private readonly GlobalOptions _options;
|
||||
private readonly IUILocalizationService? _localization;
|
||||
|
||||
private CancellationTokenSource? _downloadCts;
|
||||
private readonly Dictionary<string, AlbumFileViewModel> _musicFileMap = new();
|
||||
private readonly List<MusicInfo> _scannedMusicInfos = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _selectedFolderPath;
|
||||
@@ -34,9 +46,26 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
private double _progressPercentage;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
|
||||
private bool _isDownloading;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
|
||||
private bool _isScanning;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _scanProgressCount;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _scanTotalCount;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _scanProgressPercentage;
|
||||
|
||||
// Localized strings
|
||||
public string AlbumTitle => _localization?["Album_Title"] ?? "Album Cover Download";
|
||||
public string AlbumDescription => _localization?["Album_Description"] ?? "Download album artwork for your music collection";
|
||||
@@ -46,6 +75,8 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:";
|
||||
public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download";
|
||||
public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download";
|
||||
/// <summary>扫描进度提示。</summary>
|
||||
public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
|
||||
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
|
||||
public string CommonFiles => _localization?["Common_Files"] ?? "files";
|
||||
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
|
||||
@@ -54,21 +85,27 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
public string ColumnArtist => _localization?["Column_Artist"] ?? "Artist";
|
||||
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
|
||||
|
||||
public bool CanStartDownload => !IsDownloading && !string.IsNullOrEmpty(SelectedFolderPath);
|
||||
public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0;
|
||||
|
||||
public bool HasNoFiles => MusicFiles.Count == 0;
|
||||
|
||||
public string EmptyStateText => _localization?["Album_EmptyState"] ?? "No tasks yet, please select a folder to start scanning";
|
||||
|
||||
public ObservableCollection<MusicFileViewModel> MusicFiles { get; } = new();
|
||||
public ObservableCollection<AlbumFileViewModel> MusicFiles { get; } = new();
|
||||
|
||||
public AlbumDownloadViewModel(
|
||||
IAlbumDownloader albumDownloader,
|
||||
IDialogService dialogService,
|
||||
IFileScanner fileScanner,
|
||||
ITagLoader tagLoader,
|
||||
IOptions<GlobalOptions> options,
|
||||
IUILocalizationService? localization = null)
|
||||
{
|
||||
_albumDownloader = albumDownloader;
|
||||
_dialogService = dialogService;
|
||||
_fileScanner = fileScanner;
|
||||
_tagLoader = tagLoader;
|
||||
_options = options.Value;
|
||||
_localization = localization;
|
||||
|
||||
if (_localization != null)
|
||||
@@ -79,6 +116,8 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
MusicFiles.CollectionChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(HasNoFiles));
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
StartDownloadCommand.NotifyCanExecuteChanged();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -92,6 +131,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(AlbumParallel));
|
||||
OnPropertyChanged(nameof(AlbumStartDownload));
|
||||
OnPropertyChanged(nameof(AlbumStopDownload));
|
||||
OnPropertyChanged(nameof(AlbumScanning));
|
||||
OnPropertyChanged(nameof(CommonTotal));
|
||||
OnPropertyChanged(nameof(CommonFiles));
|
||||
OnPropertyChanged(nameof(CommonSuccess));
|
||||
@@ -102,36 +142,162 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(EmptyStateText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task SelectFolderAsync()
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
|
||||
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var folder = await _dialogService.ShowFolderPickerAsync("Select Music Folder");
|
||||
var folder = await _dialogService.ShowFolderPickerAsync(
|
||||
_localization?["Album_SelectFolder"] ?? "Select Music Folder");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (string.IsNullOrEmpty(folder)) return;
|
||||
|
||||
SelectedFolderPath = folder;
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
await ScanFilesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task StartDownloadAsync()
|
||||
private bool CanSelectFolder => !IsScanning && !IsDownloading;
|
||||
|
||||
/// <summary>
|
||||
/// 扫描文件并读取音乐标签。
|
||||
/// </summary>
|
||||
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
|
||||
|
||||
IsScanning = true;
|
||||
MusicFiles.Clear();
|
||||
_musicFileMap.Clear();
|
||||
_scannedMusicInfos.Clear();
|
||||
ScanProgressCount = 0;
|
||||
ScanTotalCount = 0;
|
||||
ScanProgressPercentage = 0;
|
||||
TotalCount = 0;
|
||||
CompletedCount = 0;
|
||||
FailedCount = 0;
|
||||
ProgressPercentage = 0;
|
||||
|
||||
try
|
||||
{
|
||||
var files = (await Task.Run(
|
||||
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
|
||||
cancellationToken)).ToList();
|
||||
|
||||
if (files.Count == 0)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Info"] ?? "Info",
|
||||
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
|
||||
return;
|
||||
}
|
||||
|
||||
ScanTotalCount = files.Count;
|
||||
|
||||
using var warpTask = new WarpTask(ParallelCount);
|
||||
var scanTasks = files.Select(file =>
|
||||
warpTask.RunAsync(async () =>
|
||||
{
|
||||
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (musicInfo != null &&
|
||||
(!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist)))
|
||||
{
|
||||
var vm = new AlbumFileViewModel
|
||||
{
|
||||
FilePath = musicInfo.FilePath,
|
||||
Name = musicInfo.Name,
|
||||
Artist = musicInfo.Artist,
|
||||
StatusMessage = _localization?["Status_Pending"] ?? "Pending"
|
||||
};
|
||||
MusicFiles.Add(vm);
|
||||
_musicFileMap[musicInfo.FilePath] = vm;
|
||||
_scannedMusicInfos.Add(musicInfo);
|
||||
}
|
||||
|
||||
ScanProgressCount++;
|
||||
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
|
||||
});
|
||||
}, cancellationToken));
|
||||
|
||||
await Task.WhenAll(scanTasks);
|
||||
|
||||
TotalCount = MusicFiles.Count;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消扫描。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Error"] ?? "Error",
|
||||
ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsScanning = false;
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanStartDownload))]
|
||||
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_scannedMusicInfos.Count == 0) return;
|
||||
|
||||
IsDownloading = true;
|
||||
CompletedCount = 0;
|
||||
FailedCount = 0;
|
||||
ProgressPercentage = 0;
|
||||
TotalCount = _scannedMusicInfos.Count;
|
||||
|
||||
_downloadCts = new CancellationTokenSource();
|
||||
foreach (var vm in MusicFiles)
|
||||
{
|
||||
vm.IsProcessed = false;
|
||||
vm.IsSuccessful = false;
|
||||
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
|
||||
}
|
||||
|
||||
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
// TODO: Implement actual download logic using _albumDownloader
|
||||
await Task.Delay(1000, _downloadCts.Token); // Placeholder
|
||||
await _albumDownloader.DownloadAsync(
|
||||
_scannedMusicInfos,
|
||||
ParallelCount,
|
||||
async musicInfo =>
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (_musicFileMap.TryGetValue(musicInfo.FilePath, out var vm))
|
||||
{
|
||||
vm.IsProcessed = true;
|
||||
vm.IsSuccessful = musicInfo.IsSuccessful;
|
||||
vm.StatusMessage = musicInfo.IsSuccessful
|
||||
? _localization?["Status_Success"] ?? "Success"
|
||||
: _localization?["Status_Failed"] ?? "Failed";
|
||||
}
|
||||
|
||||
if (musicInfo.IsSuccessful)
|
||||
CompletedCount++;
|
||||
else
|
||||
FailedCount++;
|
||||
|
||||
var done = CompletedCount + FailedCount;
|
||||
ProgressPercentage = done * 100.0 / TotalCount;
|
||||
});
|
||||
},
|
||||
_downloadCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
|
||||
{
|
||||
// User cancelled
|
||||
// 用户取消下载。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Error"] ?? "Error",
|
||||
ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -147,3 +313,27 @@ public partial class AlbumDownloadViewModel : ViewModelBase
|
||||
_downloadCts?.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单个音乐文件的封面下载状态。
|
||||
/// </summary>
|
||||
public partial class AlbumFileViewModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string _filePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _artist = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isProcessed;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isSuccessful;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _statusMessage;
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.Services;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// 音乐文件解密页面。
|
||||
/// </summary>
|
||||
public partial class DecryptViewModel : ViewModelBase
|
||||
{
|
||||
private const string KggExtension = ".kgg";
|
||||
|
||||
private readonly IMusicDecryptor _musicDecryptor;
|
||||
private readonly IDialogService _dialogService;
|
||||
private readonly IUILocalizationService? _localization;
|
||||
private readonly IKugouKeyProvider? _kugouKeyProvider;
|
||||
private readonly KugouDatabaseStore? _kugouDatabaseStore;
|
||||
|
||||
private CancellationTokenSource? _decryptCts;
|
||||
private bool _isInitialized;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
|
||||
private bool _isInitializing;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _parallelCount = 2;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _totalCount;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _completedCount;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _failedCount;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _progressPercentage;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
|
||||
[NotifyPropertyChangedFor(nameof(CanClear))]
|
||||
private bool _isDecrypting;
|
||||
|
||||
/// <summary>
|
||||
/// 是否可以读取酷狗解密密钥数据库。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))]
|
||||
private bool _isKugouDatabaseAvailable;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _kugouDatabaseStatus = string.Empty;
|
||||
|
||||
// 界面文案。
|
||||
/// <summary>页面标题。</summary>
|
||||
public string DecryptTitle => _localization?["Decrypt_Title"] ?? "Music Decryption";
|
||||
/// <summary>页面说明。</summary>
|
||||
public string DecryptDescription => _localization?["Decrypt_Description"] ?? "Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats";
|
||||
/// <summary>文件选择提示。</summary>
|
||||
public string DecryptSelectFiles => _localization?["Decrypt_SelectFiles"] ?? "Select encrypted music files...";
|
||||
/// <summary>添加文件按钮文案。</summary>
|
||||
public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files...";
|
||||
/// <summary>并行任务数标签。</summary>
|
||||
public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:";
|
||||
/// <summary>开始解密按钮文案。</summary>
|
||||
public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt";
|
||||
/// <summary>停止按钮文案。</summary>
|
||||
public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop";
|
||||
/// <summary>文件列表为空时的提示。</summary>
|
||||
public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting";
|
||||
/// <summary>清空按钮文案。</summary>
|
||||
public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear";
|
||||
/// <summary>文件列表标签。</summary>
|
||||
public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files";
|
||||
/// <summary>选择数据库按钮文案。</summary>
|
||||
public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db...";
|
||||
/// <summary>数据库缺失状态文案。</summary>
|
||||
public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing";
|
||||
/// <summary>查看详情按钮文案。</summary>
|
||||
public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details";
|
||||
/// <summary>失败详情窗口标题。</summary>
|
||||
public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure";
|
||||
|
||||
/// <summary>
|
||||
/// 酷狗数据库缺失时的提示。
|
||||
/// </summary>
|
||||
public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"]
|
||||
?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)";
|
||||
|
||||
/// <summary>是否显示数据库缺失提示。</summary>
|
||||
public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable;
|
||||
|
||||
/// <summary>
|
||||
/// 已选文件数量。
|
||||
/// </summary>
|
||||
public string SelectionSummary => Files.Count == 0
|
||||
? string.Empty
|
||||
: $"{Files.Count} {CommonFiles}";
|
||||
|
||||
/// <summary>总数标签。</summary>
|
||||
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
|
||||
/// <summary>文件数量单位。</summary>
|
||||
public string CommonFiles => _localization?["Common_Files"] ?? "files";
|
||||
/// <summary>成功数量标签。</summary>
|
||||
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
|
||||
/// <summary>失败数量标签。</summary>
|
||||
public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:";
|
||||
/// <summary>文件名列标题。</summary>
|
||||
public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name";
|
||||
/// <summary>输出路径列标题。</summary>
|
||||
public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output";
|
||||
/// <summary>状态列标题。</summary>
|
||||
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
|
||||
|
||||
/// <summary>是否存在可以开始解密的文件。</summary>
|
||||
public bool CanStartDecrypt => !IsDecrypting && !IsInitializing && Files.Any(f => !f.IsBlocked);
|
||||
/// <summary>文件列表是否为空。</summary>
|
||||
public bool HasNoFiles => Files.Count == 0;
|
||||
|
||||
/// <summary>待解密文件列表。</summary>
|
||||
public ObservableCollection<DecryptFileViewModel> Files { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 创建音乐解密页面。
|
||||
/// </summary>
|
||||
public DecryptViewModel(
|
||||
IMusicDecryptor musicDecryptor,
|
||||
IDialogService dialogService,
|
||||
IUILocalizationService? localization = null,
|
||||
IKugouKeyProvider? kugouKeyProvider = null,
|
||||
KugouDatabaseStore? kugouDatabaseStore = null)
|
||||
{
|
||||
_musicDecryptor = musicDecryptor;
|
||||
_dialogService = dialogService;
|
||||
_localization = localization;
|
||||
_kugouKeyProvider = kugouKeyProvider;
|
||||
_kugouDatabaseStore = kugouDatabaseStore;
|
||||
|
||||
if (_localization != null)
|
||||
{
|
||||
_localization.LanguageChanged += OnLanguageChanged;
|
||||
}
|
||||
|
||||
Files.CollectionChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(HasNoFiles));
|
||||
OnPropertyChanged(nameof(CanStartDecrypt));
|
||||
OnPropertyChanged(nameof(SelectionSummary));
|
||||
OnPropertyChanged(nameof(CanClear));
|
||||
StartDecryptCommand.NotifyCanExecuteChanged();
|
||||
ClearFilesCommand.NotifyCanExecuteChanged();
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复已保存的数据库路径并刷新文件状态。
|
||||
/// </summary>
|
||||
public override async Task OnActivatedAsync()
|
||||
{
|
||||
if (IsDecrypting || IsInitializing) return;
|
||||
|
||||
if (!_isInitialized)
|
||||
{
|
||||
await InitializeAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
RefreshDatabaseStatus();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化酷狗数据库路径。
|
||||
/// </summary>
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (IsInitializing) return;
|
||||
|
||||
IsInitializing = true;
|
||||
try
|
||||
{
|
||||
if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
|
||||
{
|
||||
var stored = await _kugouDatabaseStore.LoadAsync(cancellationToken);
|
||||
if (!string.IsNullOrWhiteSpace(stored))
|
||||
{
|
||||
_kugouKeyProvider.SetDatabasePath(stored);
|
||||
}
|
||||
}
|
||||
|
||||
RefreshDatabaseStatus();
|
||||
_isInitialized = true;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消初始化,下次进入页面时重试。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsInitializing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshDatabaseStatus()
|
||||
{
|
||||
if (_kugouKeyProvider == null)
|
||||
{
|
||||
// 未注册密钥提供者时,由解密器报告具体错误。
|
||||
IsKugouDatabaseAvailable = true;
|
||||
KugouDatabaseStatus = string.Empty;
|
||||
return;
|
||||
}
|
||||
|
||||
var info = _kugouKeyProvider.Probe();
|
||||
IsKugouDatabaseAvailable = info.IsAvailable;
|
||||
KugouDatabaseStatus = info.Message;
|
||||
|
||||
// 数据库可用后解除未处理文件的阻止状态。
|
||||
foreach (var file in Files)
|
||||
{
|
||||
if (!IsKggFile(file.FilePath)) continue;
|
||||
|
||||
if (info.IsAvailable && file.IsBlocked)
|
||||
{
|
||||
file.IsBlocked = false;
|
||||
file.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
|
||||
}
|
||||
else if (!info.IsAvailable && !file.IsProcessed)
|
||||
{
|
||||
file.IsBlocked = true;
|
||||
file.StatusMessage = DecryptStatusMissingDb;
|
||||
}
|
||||
}
|
||||
|
||||
OnPropertyChanged(nameof(CanStartDecrypt));
|
||||
StartDecryptCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断某个文件是否依赖酷狗数据库才能解密。
|
||||
/// <remarks>
|
||||
/// 优先按魔数判断(改名成 .mp3 的 kgg 也能被识别),没有 provider 时退回扩展名。
|
||||
/// 这样「能不能解密」的判断和 Common 里的解密器是同一套口径。
|
||||
/// </remarks>
|
||||
/// </summary>
|
||||
private bool IsKggFile(string path)
|
||||
{
|
||||
if (_kugouKeyProvider != null)
|
||||
{
|
||||
return _kugouKeyProvider.IsKggFile(path);
|
||||
}
|
||||
|
||||
return string.Equals(Path.GetExtension(path), KggExtension, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||
{
|
||||
OnPropertyChanged(nameof(DecryptTitle));
|
||||
OnPropertyChanged(nameof(DecryptDescription));
|
||||
OnPropertyChanged(nameof(DecryptSelectFiles));
|
||||
OnPropertyChanged(nameof(DecryptBrowse));
|
||||
OnPropertyChanged(nameof(DecryptParallel));
|
||||
OnPropertyChanged(nameof(DecryptStart));
|
||||
OnPropertyChanged(nameof(DecryptStop));
|
||||
OnPropertyChanged(nameof(DecryptEmptyState));
|
||||
OnPropertyChanged(nameof(DecryptClear));
|
||||
OnPropertyChanged(nameof(DecryptFilesLabel));
|
||||
OnPropertyChanged(nameof(DecryptSpecifyDatabase));
|
||||
OnPropertyChanged(nameof(DecryptStatusMissingDb));
|
||||
OnPropertyChanged(nameof(DecryptViewDetail));
|
||||
OnPropertyChanged(nameof(DecryptFailureTitle));
|
||||
OnPropertyChanged(nameof(DecryptKugouRequirement));
|
||||
OnPropertyChanged(nameof(SelectionSummary));
|
||||
OnPropertyChanged(nameof(CommonTotal));
|
||||
OnPropertyChanged(nameof(CommonFiles));
|
||||
OnPropertyChanged(nameof(CommonSuccess));
|
||||
OnPropertyChanged(nameof(CommonFailed));
|
||||
OnPropertyChanged(nameof(ColumnFileName));
|
||||
OnPropertyChanged(nameof(ColumnOutputPath));
|
||||
OnPropertyChanged(nameof(ColumnStatus));
|
||||
|
||||
foreach (var file in Files)
|
||||
{
|
||||
file.ViewDetailLabel = DecryptViewDetail;
|
||||
file.StatusMessage = file.IsBlocked
|
||||
? DecryptStatusMissingDb
|
||||
: file.IsProcessed
|
||||
? file.IsSuccessful
|
||||
? _localization?["Status_Success"] ?? "Success"
|
||||
: _localization?["Status_Failed"] ?? "Failed"
|
||||
: _localization?["Status_Pending"] ?? "Pending";
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
|
||||
private async Task SelectFilesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var picked = await _dialogService.ShowFilesPickerAsync(
|
||||
DecryptSelectFiles,
|
||||
[".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm"],
|
||||
cancellationToken);
|
||||
if (picked.Count == 0) return;
|
||||
|
||||
// 同一批文件只检查一次数据库。
|
||||
RefreshDatabaseStatus();
|
||||
|
||||
foreach (var path in picked)
|
||||
{
|
||||
// 避免重复添加同一文件。
|
||||
if (Files.Any(f => string.Equals(f.FilePath, path, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var isBlocked = IsKggFile(path) && !IsKugouDatabaseAvailable;
|
||||
|
||||
var row = new DecryptFileViewModel
|
||||
{
|
||||
FilePath = path,
|
||||
FileName = Path.GetFileName(path),
|
||||
StatusMessage = isBlocked
|
||||
? DecryptStatusMissingDb
|
||||
: _localization?["Status_Pending"] ?? "Pending",
|
||||
IsBlocked = isBlocked,
|
||||
ViewDetailLabel = DecryptViewDetail
|
||||
};
|
||||
|
||||
row.ShowDetailCommand = new AsyncRelayCommand(token => ShowDetailAsync(row, token));
|
||||
Files.Add(row);
|
||||
}
|
||||
|
||||
TotalCount = Files.Count;
|
||||
OnPropertyChanged(nameof(CanStartDecrypt));
|
||||
}
|
||||
|
||||
private bool CanSelectFiles => !IsDecrypting && !IsInitializing;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
|
||||
private async Task SpecifyDatabaseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var picked = await _dialogService.ShowFilePickerAsync(
|
||||
DecryptSpecifyDatabase,
|
||||
new[] { ".db" });
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(picked))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_kugouKeyProvider?.SetDatabasePath(picked);
|
||||
RefreshDatabaseStatus();
|
||||
|
||||
if (_kugouDatabaseStore != null)
|
||||
{
|
||||
await _kugouDatabaseStore.SaveAsync(picked, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanStartDecrypt))]
|
||||
private async Task StartDecryptAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Files.Count == 0) return;
|
||||
// 缺少密钥数据库的文件不加入本次任务。
|
||||
var runnable = Files.Where(f => !f.IsBlocked).ToList();
|
||||
|
||||
IsDecrypting = true;
|
||||
CompletedCount = 0;
|
||||
FailedCount = 0;
|
||||
ProgressPercentage = 0;
|
||||
TotalCount = runnable.Count;
|
||||
|
||||
foreach (var file in Files)
|
||||
{
|
||||
file.IsProcessed = false;
|
||||
file.IsSuccessful = false;
|
||||
file.OutputPath = null;
|
||||
file.ErrorDetail = null;
|
||||
|
||||
if (!file.IsBlocked)
|
||||
{
|
||||
file.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
|
||||
}
|
||||
}
|
||||
|
||||
if (runnable.Count == 0)
|
||||
{
|
||||
IsDecrypting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_decryptCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
var token = _decryptCts.Token;
|
||||
|
||||
try
|
||||
{
|
||||
var parallel = ParallelCount <= 0 ? 1 : ParallelCount;
|
||||
|
||||
using var warpTask = new WarpTask(parallel);
|
||||
|
||||
var tasks = runnable.Select(file => warpTask.RunAsync(async () =>
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
DecryptionResult result;
|
||||
try
|
||||
{
|
||||
result = await Task.Run(() => _musicDecryptor.ConvertMusicAsync(file.FilePath, token), token);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result = DecryptionResult.Failed(ex.Message);
|
||||
}
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
file.IsProcessed = true;
|
||||
file.IsSuccessful = result.IsSuccess;
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
file.OutputPath = result.OutputFilePath;
|
||||
file.ErrorDetail = null;
|
||||
file.StatusMessage = _localization?["Status_Success"] ?? "Success";
|
||||
CompletedCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 状态列只显示摘要,完整错误在详情对话框展示。
|
||||
file.ErrorDetail = result.ErrorMessage;
|
||||
file.StatusMessage = _localization?["Status_Failed"] ?? "Failed";
|
||||
FailedCount++;
|
||||
}
|
||||
|
||||
var done = CompletedCount + FailedCount;
|
||||
ProgressPercentage = done * 100.0 / TotalCount;
|
||||
});
|
||||
}, token));
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消时,未完成的文件保持待处理状态。
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsDecrypting = false;
|
||||
_decryptCts?.Dispose();
|
||||
_decryptCts = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示文件解密失败的完整原因。
|
||||
/// </summary>
|
||||
private async Task ShowDetailAsync(DecryptFileViewModel? file, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _dialogService.ShowMessageAsync(DecryptFailureTitle, file.ErrorDetail);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void CancelDecrypt()
|
||||
{
|
||||
_decryptCts?.Cancel();
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanClear))]
|
||||
private void ClearFiles()
|
||||
{
|
||||
Files.Clear();
|
||||
TotalCount = 0;
|
||||
CompletedCount = 0;
|
||||
FailedCount = 0;
|
||||
ProgressPercentage = 0;
|
||||
OnPropertyChanged(nameof(CanStartDecrypt));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否可以清空文件列表。
|
||||
/// </summary>
|
||||
private bool CanClear => !IsDecrypting && Files.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单个文件的解密状态。
|
||||
/// </summary>
|
||||
public partial class DecryptFileViewModel : ObservableObject
|
||||
{
|
||||
/// <summary>输入文件路径。</summary>
|
||||
[ObservableProperty]
|
||||
private string _filePath = string.Empty;
|
||||
|
||||
/// <summary>输入文件名。</summary>
|
||||
[ObservableProperty]
|
||||
private string _fileName = string.Empty;
|
||||
|
||||
/// <summary>解密后的输出路径。</summary>
|
||||
[ObservableProperty]
|
||||
private string? _outputPath;
|
||||
|
||||
/// <summary>是否已完成处理。</summary>
|
||||
[ObservableProperty]
|
||||
private bool _isProcessed;
|
||||
|
||||
/// <summary>是否解密成功。</summary>
|
||||
[ObservableProperty]
|
||||
private bool _isSuccessful;
|
||||
|
||||
/// <summary>
|
||||
/// 状态列摘要,完整原因保存在 <see cref="ErrorDetail"/>。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
|
||||
private string? _statusMessage;
|
||||
|
||||
/// <summary>解密失败的完整原因。</summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
|
||||
private string? _errorDetail;
|
||||
|
||||
/// <summary>
|
||||
/// 是否因缺少酷狗数据库而无法开始解密。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _isBlocked;
|
||||
|
||||
/// <summary>
|
||||
/// 详情按钮文案。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? _viewDetailLabel;
|
||||
|
||||
/// <summary>
|
||||
/// 由父 ViewModel 在创建行时注入,用来打开失败详情对话框。
|
||||
/// </summary>
|
||||
public IAsyncRelayCommand? ShowDetailCommand { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否存在可查看的错误详情。
|
||||
/// </summary>
|
||||
public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail);
|
||||
}
|
||||
@@ -1,15 +1,106 @@
|
||||
using System.Reflection;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.Services;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// 首页与功能入口。
|
||||
/// </summary>
|
||||
public partial class HomeViewModel : ViewModelBase
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string _welcomeMessage = "Welcome to ZonyLrcTools X";
|
||||
private readonly INavigationService _navigation;
|
||||
private readonly IUILocalizationService _localization;
|
||||
|
||||
/// <summary>
|
||||
/// 创建首页。
|
||||
/// </summary>
|
||||
public HomeViewModel(INavigationService navigation, IUILocalizationService localization)
|
||||
{
|
||||
_navigation = navigation;
|
||||
_localization = localization;
|
||||
_localization.LanguageChanged += OnLanguageChanged;
|
||||
_version = ResolveVersion();
|
||||
}
|
||||
|
||||
[ObservableProperty]
|
||||
private string _description = "A cross-platform tool for downloading lyrics and album covers for your music collection.";
|
||||
private string _version;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _version = "4.0.3";
|
||||
/// <summary>欢迎语。</summary>
|
||||
public string WelcomeMessage => _localization["Home_Welcome"];
|
||||
/// <summary>应用说明。</summary>
|
||||
public string Description => _localization["Home_Description"];
|
||||
/// <summary>快捷操作标题。</summary>
|
||||
public string QuickActionsTitle => _localization["Home_QuickActions"];
|
||||
/// <summary>功能特性标题。</summary>
|
||||
public string FeaturesTitle => _localization["Home_Features"];
|
||||
/// <summary>支持格式说明。</summary>
|
||||
public string FeatureFormats => _localization["Home_FeatureFormats"];
|
||||
/// <summary>并行下载说明。</summary>
|
||||
public string FeatureParallel => _localization["Home_FeatureParallel"];
|
||||
/// <summary>编码支持说明。</summary>
|
||||
public string FeatureEncodings => _localization["Home_FeatureEncodings"];
|
||||
/// <summary>跨平台支持说明。</summary>
|
||||
public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"];
|
||||
/// <summary>版本标签。</summary>
|
||||
public string VersionLabel => _localization["Home_Version"];
|
||||
|
||||
// 功能入口文案。
|
||||
/// <summary>歌词下载入口标题。</summary>
|
||||
public string LyricsCardTitle => _localization["Home_DownloadLyrics"];
|
||||
/// <summary>歌词下载入口说明。</summary>
|
||||
public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"];
|
||||
/// <summary>封面下载入口标题。</summary>
|
||||
public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"];
|
||||
/// <summary>封面下载入口说明。</summary>
|
||||
public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"];
|
||||
/// <summary>音乐解密入口标题。</summary>
|
||||
public string DecryptCardTitle => _localization["Home_Decrypt"];
|
||||
/// <summary>音乐解密入口说明。</summary>
|
||||
public string DecryptCardDescription => _localization["Home_DecryptHint"];
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenLyrics() => _navigation.NavigateRoot<LyricsDownloadViewModel>();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenAlbum() => _navigation.NavigateRoot<AlbumDownloadViewModel>();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenDecrypt() => _navigation.NavigateRoot<DecryptViewModel>();
|
||||
|
||||
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||
{
|
||||
OnPropertyChanged(nameof(WelcomeMessage));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
OnPropertyChanged(nameof(QuickActionsTitle));
|
||||
OnPropertyChanged(nameof(FeaturesTitle));
|
||||
OnPropertyChanged(nameof(FeatureFormats));
|
||||
OnPropertyChanged(nameof(FeatureParallel));
|
||||
OnPropertyChanged(nameof(FeatureEncodings));
|
||||
OnPropertyChanged(nameof(FeatureCrossPlatform));
|
||||
OnPropertyChanged(nameof(VersionLabel));
|
||||
OnPropertyChanged(nameof(LyricsCardTitle));
|
||||
OnPropertyChanged(nameof(LyricsCardDescription));
|
||||
OnPropertyChanged(nameof(AlbumCardTitle));
|
||||
OnPropertyChanged(nameof(AlbumCardDescription));
|
||||
OnPropertyChanged(nameof(DecryptCardTitle));
|
||||
OnPropertyChanged(nameof(DecryptCardDescription));
|
||||
}
|
||||
|
||||
private static string ResolveVersion()
|
||||
{
|
||||
var assembly = typeof(HomeViewModel).Assembly;
|
||||
var informational = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(informational))
|
||||
{
|
||||
// 隐藏 SourceLink 添加的提交标识。
|
||||
var plusIndex = informational.IndexOf('+');
|
||||
return plusIndex > 0 ? informational[..plusIndex] : informational;
|
||||
}
|
||||
|
||||
return assembly.GetName().Version?.ToString(3) ?? "4.0.3";
|
||||
}
|
||||
}
|
||||
@@ -8,28 +8,74 @@ using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.IO;
|
||||
using ZonyLrcTools.Common.Infrastructure.Threading;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
using ZonyLrcTools.Common.TagInfo;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.Services;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// 歌词列表的数据来源。
|
||||
/// </summary>
|
||||
public enum LyricsScannerKind
|
||||
{
|
||||
/// <summary>扫描本地音乐文件夹。</summary>
|
||||
Local = 0,
|
||||
|
||||
/// <summary>读取歌曲与歌手信息的 CSV 文件。</summary>
|
||||
Csv = 1,
|
||||
|
||||
/// <summary>读取网易云歌单。</summary>
|
||||
NetEase = 2
|
||||
}
|
||||
|
||||
public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
{
|
||||
private const string DefaultOutputDirectoryName = "DownloadedLrc";
|
||||
private const string DefaultFileNamePattern = "{Artist} - {Name}.lrc";
|
||||
|
||||
private readonly ILyricsDownloader _lyricsDownloader;
|
||||
private readonly IDialogService _dialogService;
|
||||
private readonly IFileScanner _fileScanner;
|
||||
private readonly ITagLoader _tagLoader;
|
||||
private readonly CsvFileMusicScanner _csvFileMusicScanner;
|
||||
private readonly NetEaseMusicSongListMusicScanner _neteaseMusicScanner;
|
||||
private readonly NetEaseSessionStore _sessionStore;
|
||||
private readonly GlobalOptions _options;
|
||||
private readonly IUILocalizationService? _localization;
|
||||
|
||||
private CancellationTokenSource? _downloadCts;
|
||||
private Dictionary<string, MusicFileViewModel> _musicFileMap = new();
|
||||
private List<MusicInfo> _scannedMusicInfos = new();
|
||||
private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new();
|
||||
private readonly List<MusicInfo> _scannedMusicInfos = new();
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
private string? _selectedFolderPath;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
private string? _selectedCsvFilePath;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
private string? _songListIds;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _outputDirectory;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(IsLocalScanner))]
|
||||
[NotifyPropertyChangedFor(nameof(IsCsvScanner))]
|
||||
[NotifyPropertyChangedFor(nameof(IsNetEaseScanner))]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
private int _selectedScannerIndex;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _parallelCount = 2;
|
||||
|
||||
@@ -47,13 +93,28 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
|
||||
private bool _isDownloading;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
private bool _isScanning;
|
||||
|
||||
[ObservableProperty]
|
||||
@@ -65,10 +126,29 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
[ObservableProperty]
|
||||
private double _scanProgressPercentage;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(NetEaseAccountStatus))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
|
||||
private bool _isNetEaseLoggedIn;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
|
||||
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
|
||||
[NotifyPropertyChangedFor(nameof(CanScan))]
|
||||
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
|
||||
private bool _isAccountBusy;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _currentProcessingFile;
|
||||
|
||||
// Localized strings
|
||||
// 界面文案。
|
||||
public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download";
|
||||
public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files";
|
||||
public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder";
|
||||
@@ -78,6 +158,46 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download";
|
||||
public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download";
|
||||
public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
|
||||
/// <summary>数据来源标签。</summary>
|
||||
public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source";
|
||||
/// <summary>扫描按钮文案。</summary>
|
||||
public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan";
|
||||
/// <summary>CSV 文件标签。</summary>
|
||||
public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File";
|
||||
/// <summary>CSV 文件选择提示。</summary>
|
||||
public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file...";
|
||||
/// <summary>CSV 文件选择按钮文案。</summary>
|
||||
public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose...";
|
||||
/// <summary>网易云歌单编号标签。</summary>
|
||||
public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID";
|
||||
/// <summary>网易云歌单编号输入提示。</summary>
|
||||
public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)";
|
||||
/// <summary>输出目录标签。</summary>
|
||||
public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To";
|
||||
/// <summary>输出目录选择提示。</summary>
|
||||
public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written";
|
||||
/// <summary>输出目录选择按钮文案。</summary>
|
||||
public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose...";
|
||||
/// <summary>退出登录按钮文案。</summary>
|
||||
public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out";
|
||||
/// <summary>退出登录提示。</summary>
|
||||
public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ??
|
||||
"Forget the saved session and scan the QR code again next time.";
|
||||
/// <summary>登录按钮文案。</summary>
|
||||
public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…";
|
||||
/// <summary>登录按钮提示。</summary>
|
||||
public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ??
|
||||
"Scan a QR code now instead of waiting until the next scan.";
|
||||
|
||||
/// <summary>
|
||||
/// 当前网易云登录状态。
|
||||
/// </summary>
|
||||
public string NetEaseAccountStatus => IsNetEaseLoggedIn
|
||||
? _localization?["NetEase_LoggedIn"] ?? "Signed in. Scanning a playlist reuses this session."
|
||||
: _localization?["NetEase_NotLoggedIn"] ?? "Not signed in. Scanning a playlist will show a QR code.";
|
||||
|
||||
/// <summary>账号状态标签。</summary>
|
||||
public string NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account";
|
||||
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
|
||||
public string CommonFiles => _localization?["Common_Files"] ?? "files";
|
||||
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
|
||||
@@ -87,7 +207,21 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
public string ColumnFilePath => _localization?["Column_FilePath"] ?? "File Path";
|
||||
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
|
||||
|
||||
public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0;
|
||||
/// <summary>
|
||||
/// 按 <see cref="SelectedScannerIndex"/> 排列的数据来源名称。
|
||||
/// </summary>
|
||||
public string[] ScannerNames =>
|
||||
[
|
||||
_localization?["Scanner_Local"] ?? "Local Folder",
|
||||
_localization?["Scanner_Csv"] ?? "CSV File",
|
||||
_localization?["Scanner_NetEase"] ?? "NetEase Playlist"
|
||||
];
|
||||
|
||||
public bool IsLocalScanner => SelectedScannerIndex == (int)LyricsScannerKind.Local;
|
||||
public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv;
|
||||
public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase;
|
||||
|
||||
public bool CanStartDownload => CanEditInputs && MusicFiles.Count > 0;
|
||||
|
||||
public bool HasNoFiles => MusicFiles.Count == 0;
|
||||
|
||||
@@ -100,6 +234,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
IDialogService dialogService,
|
||||
IFileScanner fileScanner,
|
||||
ITagLoader tagLoader,
|
||||
CsvFileMusicScanner csvFileMusicScanner,
|
||||
NetEaseMusicSongListMusicScanner neteaseMusicScanner,
|
||||
NetEaseSessionStore sessionStore,
|
||||
IOptions<GlobalOptions> options,
|
||||
IUILocalizationService? localization = null)
|
||||
{
|
||||
@@ -107,18 +244,29 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
_dialogService = dialogService;
|
||||
_fileScanner = fileScanner;
|
||||
_tagLoader = tagLoader;
|
||||
_csvFileMusicScanner = csvFileMusicScanner;
|
||||
_neteaseMusicScanner = neteaseMusicScanner;
|
||||
_sessionStore = sessionStore;
|
||||
_options = options.Value;
|
||||
_localization = localization;
|
||||
|
||||
OutputDirectory = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
|
||||
DefaultOutputDirectoryName);
|
||||
|
||||
if (_localization != null)
|
||||
{
|
||||
_localization.LanguageChanged += OnLanguageChanged;
|
||||
}
|
||||
|
||||
// 扫描器为单例,页面直接复用已恢复的登录状态。
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
|
||||
MusicFiles.CollectionChanged += (_, _) =>
|
||||
{
|
||||
OnPropertyChanged(nameof(HasNoFiles));
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
StartDownloadCommand.NotifyCanExecuteChanged();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -133,6 +281,22 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(LyricsStartDownload));
|
||||
OnPropertyChanged(nameof(LyricsStopDownload));
|
||||
OnPropertyChanged(nameof(LyricsScanning));
|
||||
OnPropertyChanged(nameof(LyricsScannerLabel));
|
||||
OnPropertyChanged(nameof(LyricsScan));
|
||||
OnPropertyChanged(nameof(LyricsCsvLabel));
|
||||
OnPropertyChanged(nameof(LyricsCsvSelect));
|
||||
OnPropertyChanged(nameof(LyricsCsvBrowse));
|
||||
OnPropertyChanged(nameof(LyricsSongListLabel));
|
||||
OnPropertyChanged(nameof(LyricsSongListWatermark));
|
||||
OnPropertyChanged(nameof(LyricsOutputLabel));
|
||||
OnPropertyChanged(nameof(LyricsOutputSelect));
|
||||
OnPropertyChanged(nameof(LyricsOutputBrowse));
|
||||
OnPropertyChanged(nameof(NetEaseSignOut));
|
||||
OnPropertyChanged(nameof(NetEaseSignOutHint));
|
||||
OnPropertyChanged(nameof(NetEaseSignIn));
|
||||
OnPropertyChanged(nameof(NetEaseSignInHint));
|
||||
OnPropertyChanged(nameof(NetEaseAccountStatus));
|
||||
OnPropertyChanged(nameof(NetEaseAccountLabel));
|
||||
OnPropertyChanged(nameof(CommonTotal));
|
||||
OnPropertyChanged(nameof(CommonFiles));
|
||||
OnPropertyChanged(nameof(CommonSuccess));
|
||||
@@ -142,26 +306,329 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(ColumnFilePath));
|
||||
OnPropertyChanged(nameof(ColumnStatus));
|
||||
OnPropertyChanged(nameof(EmptyStateText));
|
||||
OnPropertyChanged(nameof(ScannerNames));
|
||||
}
|
||||
|
||||
partial void OnSelectedScannerIndexChanged(int value) => InvalidateScan();
|
||||
partial void OnSelectedCsvFilePathChanged(string? value) => InvalidateScan();
|
||||
partial void OnSongListIdsChanged(string? value) => InvalidateScan();
|
||||
partial void OnOutputDirectoryChanged(string? value) => InvalidateScan();
|
||||
|
||||
private void InvalidateScan()
|
||||
{
|
||||
if (CanEditInputs)
|
||||
{
|
||||
ResetCollections();
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
|
||||
private async Task SelectFolderAsync()
|
||||
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var folder = await _dialogService.ShowFolderPickerAsync(
|
||||
_localization?["Lyrics_SelectFolder"] ?? "Select Music Folder");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (string.IsNullOrEmpty(folder)) return;
|
||||
|
||||
SelectedFolderPath = folder;
|
||||
await ScanFilesAsync();
|
||||
await ScanFilesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
private bool CanSelectFolder => !IsScanning && !IsDownloading;
|
||||
/// <summary>
|
||||
/// 是否可以修改任务来源与输出目录。
|
||||
/// </summary>
|
||||
public bool CanEditInputs => !IsScanning && !IsDownloading && !IsAccountBusy;
|
||||
|
||||
private async Task ScanFilesAsync()
|
||||
private bool CanSelectFolder => CanEditInputs;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
|
||||
private async Task SelectCsvFileAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var file = await _dialogService.ShowFilePickerAsync(
|
||||
_localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]);
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (string.IsNullOrEmpty(file)) return;
|
||||
|
||||
SelectedCsvFilePath = file;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
|
||||
private async Task SelectOutputFolderAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var folder = await _dialogService.ShowFolderPickerAsync(
|
||||
_localization?["Lyrics_OutputSelect"] ?? "Select Output Folder");
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (string.IsNullOrEmpty(folder)) return;
|
||||
|
||||
OutputDirectory = folder;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 当前来源是否具备扫描所需的输入。
|
||||
/// </summary>
|
||||
public bool CanScan => CanEditInputs && (SelectedScannerIndex switch
|
||||
{
|
||||
(int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath),
|
||||
(int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath),
|
||||
(int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds),
|
||||
_ => false
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// 使用当前来源重新读取歌曲列表。
|
||||
/// </summary>
|
||||
[RelayCommand(CanExecute = nameof(CanScan))]
|
||||
private async Task StartScanAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
switch ((LyricsScannerKind)SelectedScannerIndex)
|
||||
{
|
||||
case LyricsScannerKind.Csv:
|
||||
await ScanCsvFileAsync(cancellationToken);
|
||||
break;
|
||||
case LyricsScannerKind.NetEase:
|
||||
await ScanNetEasePlaylistAsync(cancellationToken);
|
||||
break;
|
||||
default:
|
||||
await ScanFilesAsync(cancellationToken);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
|
||||
|
||||
ResetCollections();
|
||||
IsScanning = true;
|
||||
|
||||
try
|
||||
{
|
||||
var files = (await Task.Run(
|
||||
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
|
||||
cancellationToken)).ToList();
|
||||
|
||||
if (files.Count == 0)
|
||||
{
|
||||
await ShowNoMusicFilesAsync(cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
ScanTotalCount = files.Count;
|
||||
|
||||
using var warpTask = new WarpTask(ParallelCount);
|
||||
var scanTasks = files.Select(file =>
|
||||
warpTask.RunAsync(async () =>
|
||||
{
|
||||
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (musicInfo != null &&
|
||||
(!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist)))
|
||||
{
|
||||
AddRow(musicInfo);
|
||||
}
|
||||
|
||||
ScanProgressCount++;
|
||||
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
|
||||
});
|
||||
}, cancellationToken));
|
||||
|
||||
await Task.WhenAll(scanTasks);
|
||||
|
||||
TotalCount = MusicFiles.Count;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消扫描。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsScanning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ScanCsvFileAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(SelectedCsvFilePath)) return;
|
||||
|
||||
ResetCollections();
|
||||
IsScanning = true;
|
||||
|
||||
try
|
||||
{
|
||||
var outputDirectory = RequireOutputDirectory();
|
||||
var musicInfos = await Task.Run(() => _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
|
||||
SelectedCsvFilePath, outputDirectory, DefaultFileNamePattern, cancellationToken), cancellationToken);
|
||||
|
||||
AppendScannedMusicInfos(musicInfos);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消扫描。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsScanning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ScanNetEasePlaylistAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(SongListIds)) return;
|
||||
|
||||
ResetCollections();
|
||||
IsScanning = true;
|
||||
|
||||
try
|
||||
{
|
||||
await RestoreNetEaseSessionAsync(cancellationToken);
|
||||
|
||||
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync(cancellationToken))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
|
||||
// 扫码等待与歌单请求都要能被打断,否则 Cookie 恰好失效时这里会一直挂着。
|
||||
var musicInfos = await _neteaseMusicScanner.GetMusicInfoFromNetEaseMusicSongListAsync(
|
||||
SongListIds,
|
||||
RequireOutputDirectory(),
|
||||
DefaultFileNamePattern,
|
||||
onQrCodeReady: null,
|
||||
onStateChanged: null,
|
||||
cancellationToken: cancellationToken);
|
||||
|
||||
await PersistNetEaseSessionAsync(cancellationToken);
|
||||
|
||||
AppendScannedMusicInfos(musicInfos);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消扫描。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsScanning = false;
|
||||
|
||||
// 无论登录成功还是取消,都以扫描器中的状态为准。
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复已保存的网易云登录状态。
|
||||
/// </summary>
|
||||
private async Task RestoreNetEaseSessionAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_neteaseMusicScanner.IsLoggedIn) return;
|
||||
|
||||
var session = await _sessionStore.LoadAsync(cancellationToken);
|
||||
if (session == null) return;
|
||||
|
||||
_neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken);
|
||||
}
|
||||
|
||||
private async Task PersistNetEaseSessionAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_neteaseMusicScanner.IsLoggedIn) return;
|
||||
|
||||
await _sessionStore.SaveAsync(new NetEaseSession
|
||||
{
|
||||
Cookie = _neteaseMusicScanner.Cookie,
|
||||
CsrfToken = _neteaseMusicScanner.CsrfToken,
|
||||
SavedAtUtc = DateTimeOffset.UtcNow
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示二维码并等待登录或窗口关闭。
|
||||
/// </summary>
|
||||
private async Task<bool> LoginToNetEaseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var loginViewModel = new QrCodeLoginViewModel(_localization);
|
||||
using var loginCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
void OnCancelled(object? sender, EventArgs args) => loginCts.Cancel();
|
||||
loginViewModel.Cancelled += OnCancelled;
|
||||
|
||||
var loginTask = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var expired = false;
|
||||
var isSuccess = await _neteaseMusicScanner.LoginAsync(
|
||||
payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)),
|
||||
state =>
|
||||
{
|
||||
expired = state == NetEaseLoginState.Expired;
|
||||
Dispatcher.UIThread.Post(() => loginViewModel.SetState(state));
|
||||
},
|
||||
loginCts.Token);
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (isSuccess)
|
||||
{
|
||||
loginViewModel.Complete();
|
||||
}
|
||||
else if (!expired)
|
||||
{
|
||||
loginViewModel.SetError(_localization?["NetEase_LoginFailed"] ??
|
||||
"Login did not complete. Close this dialog and try again.");
|
||||
}
|
||||
});
|
||||
|
||||
return isSuccess;
|
||||
}
|
||||
catch (OperationCanceledException) when (loginCts.IsCancellationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await Dispatcher.UIThread.InvokeAsync(() => loginViewModel.SetError(ex.Message));
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
loginViewModel.NotifyClosed();
|
||||
loginCts.Cancel();
|
||||
await loginTask;
|
||||
loginViewModel.Cancelled -= OnCancelled;
|
||||
}
|
||||
|
||||
var isSuccess = await loginTask;
|
||||
if (isSuccess)
|
||||
{
|
||||
await PersistNetEaseSessionAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
|
||||
private void ResetCollections()
|
||||
{
|
||||
MusicFiles.Clear();
|
||||
_musicFileMap.Clear();
|
||||
_scannedMusicInfos.Clear();
|
||||
@@ -172,71 +639,73 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
CompletedCount = 0;
|
||||
FailedCount = 0;
|
||||
ProgressPercentage = 0;
|
||||
|
||||
try
|
||||
{
|
||||
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions))
|
||||
.ToList();
|
||||
|
||||
if (files.Count == 0)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Info"] ?? "Info",
|
||||
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
|
||||
IsScanning = false;
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
return;
|
||||
}
|
||||
|
||||
ScanTotalCount = files.Count;
|
||||
|
||||
using var warpTask = new WarpTask(ParallelCount);
|
||||
var scanTasks = files.Select(file =>
|
||||
warpTask.RunAsync(async () =>
|
||||
{
|
||||
var musicInfo = await _tagLoader.LoadTagAsync(file);
|
||||
|
||||
await Dispatcher.UIThread.InvokeAsync(() =>
|
||||
{
|
||||
if (musicInfo != null &&
|
||||
(!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist)))
|
||||
{
|
||||
var vm = new MusicFileViewModel
|
||||
{
|
||||
FilePath = musicInfo.FilePath,
|
||||
Name = musicInfo.Name,
|
||||
Artist = musicInfo.Artist,
|
||||
StatusMessage = _localization?["Status_Pending"] ?? "Pending"
|
||||
};
|
||||
MusicFiles.Add(vm);
|
||||
_musicFileMap[musicInfo.FilePath] = vm;
|
||||
_scannedMusicInfos.Add(musicInfo);
|
||||
}
|
||||
|
||||
ScanProgressCount++;
|
||||
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
|
||||
});
|
||||
}));
|
||||
|
||||
await Task.WhenAll(scanTasks);
|
||||
|
||||
TotalCount = MusicFiles.Count;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Error"] ?? "Error",
|
||||
ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsScanning = false;
|
||||
OnPropertyChanged(nameof(CanStartDownload));
|
||||
}
|
||||
}
|
||||
|
||||
private void AddRow(MusicInfo musicInfo)
|
||||
{
|
||||
if (_musicFileMap.ContainsKey(musicInfo.FilePath)) return;
|
||||
|
||||
var vm = new MusicFileViewModel
|
||||
{
|
||||
FilePath = musicInfo.FilePath,
|
||||
Name = musicInfo.Name,
|
||||
Artist = musicInfo.Artist,
|
||||
StatusMessage = _localization?["Status_Pending"] ?? "Pending"
|
||||
};
|
||||
|
||||
MusicFiles.Add(vm);
|
||||
_musicFileMap[musicInfo.FilePath] = vm;
|
||||
_scannedMusicInfos.Add(musicInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将 CSV 或网易云扫描结果加入列表。
|
||||
/// </summary>
|
||||
private void AppendScannedMusicInfos(List<MusicInfo> musicInfos)
|
||||
{
|
||||
foreach (var musicInfo in musicInfos.Where(info => !string.IsNullOrEmpty(info.Name)))
|
||||
{
|
||||
AddRow(musicInfo);
|
||||
}
|
||||
|
||||
ScanTotalCount = MusicFiles.Count;
|
||||
ScanProgressCount = ScanTotalCount;
|
||||
ScanProgressPercentage = 100;
|
||||
TotalCount = MusicFiles.Count;
|
||||
}
|
||||
|
||||
private string RequireOutputDirectory()
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(OutputDirectory))
|
||||
{
|
||||
return OutputDirectory;
|
||||
}
|
||||
|
||||
var fallback = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic),
|
||||
DefaultOutputDirectoryName);
|
||||
OutputDirectory = fallback;
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private Task ShowNoMusicFilesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Info"] ?? "Info",
|
||||
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
|
||||
}
|
||||
|
||||
private Task ShowErrorAsync(string message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message);
|
||||
}
|
||||
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanStartDownload))]
|
||||
private async Task StartDownloadAsync()
|
||||
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (_scannedMusicInfos.Count == 0) return;
|
||||
|
||||
@@ -246,7 +715,6 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
ProgressPercentage = 0;
|
||||
TotalCount = _scannedMusicInfos.Count;
|
||||
|
||||
// Reset all row statuses
|
||||
foreach (var vm in MusicFiles)
|
||||
{
|
||||
vm.IsProcessed = false;
|
||||
@@ -254,7 +722,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
|
||||
}
|
||||
|
||||
_downloadCts = new CancellationTokenSource();
|
||||
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
@@ -294,9 +762,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
},
|
||||
_downloadCts.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
|
||||
{
|
||||
// User cancelled
|
||||
// 用户取消下载。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -311,6 +783,88 @@ public partial class LyricsDownloadViewModel : ViewModelBase
|
||||
{
|
||||
_downloadCts?.Cancel();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除已保存的网易云登录状态。
|
||||
/// </summary>
|
||||
[RelayCommand(CanExecute = nameof(CanSignOutNetEase))]
|
||||
private async Task SignOutNetEaseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
IsAccountBusy = true;
|
||||
try
|
||||
{
|
||||
await _sessionStore.ClearAsync(cancellationToken);
|
||||
_neteaseMusicScanner.ClearLoginState();
|
||||
await _dialogService.ShowMessageAsync(
|
||||
_localization?["Common_Info"] ?? "Info",
|
||||
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消操作。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
IsAccountBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanSignInNetEase => !IsNetEaseLoggedIn && CanEditInputs;
|
||||
private bool CanSignOutNetEase => IsNetEaseLoggedIn && CanEditInputs;
|
||||
|
||||
/// <summary>
|
||||
/// 主动发起网易云扫码登录。
|
||||
/// </summary>
|
||||
[RelayCommand(CanExecute = nameof(CanSignInNetEase))]
|
||||
private async Task SignInNetEaseAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
IsAccountBusy = true;
|
||||
try
|
||||
{
|
||||
await LoginToNetEaseAsync(cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 用户取消登录。
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
IsAccountBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 页面打开时恢复登录状态。
|
||||
/// </summary>
|
||||
public override async Task OnActivatedAsync()
|
||||
{
|
||||
if (!CanEditInputs) return;
|
||||
|
||||
IsAccountBusy = true;
|
||||
try
|
||||
{
|
||||
await RestoreNetEaseSessionAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await ShowErrorAsync(ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
|
||||
IsAccountBusy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public partial class MusicFileViewModel : ObservableObject
|
||||
|
||||
@@ -9,6 +9,7 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
private readonly IThemeService _themeService;
|
||||
private readonly IUILocalizationService _localization;
|
||||
private readonly INavigationService _navigation;
|
||||
|
||||
[ObservableProperty]
|
||||
private ViewModelBase? _currentPage;
|
||||
@@ -27,6 +28,8 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
public string NavHome => _localization["Nav_Home"];
|
||||
public string NavLyricsDownload => _localization["Nav_LyricsDownload"];
|
||||
public string NavAlbumDownload => _localization["Nav_AlbumDownload"];
|
||||
/// <summary>音乐解密导航文案。</summary>
|
||||
public string NavDecrypt => _localization["Nav_Decrypt"];
|
||||
public string NavSettings => _localization["Nav_Settings"];
|
||||
public string HomeDescription => _localization["Home_Description"];
|
||||
|
||||
@@ -37,25 +40,89 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
public MainWindowViewModel(
|
||||
IThemeService themeService,
|
||||
IUILocalizationService localization,
|
||||
HomeViewModel homeViewModel)
|
||||
INavigationService navigation)
|
||||
{
|
||||
_themeService = themeService;
|
||||
_localization = localization;
|
||||
_navigation = navigation;
|
||||
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
|
||||
_themeService.ThemeChanged += (_, _) =>
|
||||
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
|
||||
|
||||
// Subscribe to language changes
|
||||
_localization.LanguageChanged += OnLanguageChanged;
|
||||
|
||||
// Set initial page
|
||||
CurrentPage = homeViewModel;
|
||||
SelectedNavigationIndex = 0;
|
||||
// 页面切换统一由导航服务管理。
|
||||
_navigation.NavigationChanged += OnNavigationChanged;
|
||||
|
||||
NavigateToIndex(0);
|
||||
}
|
||||
|
||||
// 避免导航通知与侧栏选中状态互相触发。
|
||||
private bool _isSyncingNavigation;
|
||||
|
||||
partial void OnSelectedNavigationIndexChanged(int value)
|
||||
{
|
||||
if (_isSyncingNavigation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
NavigateToIndex(value);
|
||||
}
|
||||
|
||||
private void NavigateToIndex(int index)
|
||||
{
|
||||
// 侧栏切换不累积返回记录。
|
||||
CurrentPage = index switch
|
||||
{
|
||||
1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(),
|
||||
2 => _navigation.NavigateRoot<AlbumDownloadViewModel>(),
|
||||
3 => _navigation.NavigateRoot<DecryptViewModel>(),
|
||||
4 => _navigation.NavigateRoot<SettingsViewModel>(),
|
||||
_ => _navigation.NavigateRoot<HomeViewModel>()
|
||||
};
|
||||
}
|
||||
|
||||
private void OnNavigationChanged(object? sender, ViewModelBase viewModel)
|
||||
{
|
||||
CurrentPage = viewModel;
|
||||
|
||||
// 首页快捷入口跳转时同步侧栏选中项。
|
||||
var index = IndexOf(viewModel);
|
||||
if (index < 0 || index == SelectedNavigationIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isSyncingNavigation = true;
|
||||
try
|
||||
{
|
||||
SelectedNavigationIndex = index;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isSyncingNavigation = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int IndexOf(ViewModelBase viewModel) => viewModel switch
|
||||
{
|
||||
LyricsDownloadViewModel => 1,
|
||||
AlbumDownloadViewModel => 2,
|
||||
DecryptViewModel => 3,
|
||||
SettingsViewModel => 4,
|
||||
HomeViewModel => 0,
|
||||
_ => -1
|
||||
};
|
||||
|
||||
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||
{
|
||||
// Notify all localized properties have changed
|
||||
OnPropertyChanged(nameof(NavHome));
|
||||
OnPropertyChanged(nameof(NavLyricsDownload));
|
||||
OnPropertyChanged(nameof(NavAlbumDownload));
|
||||
OnPropertyChanged(nameof(NavDecrypt));
|
||||
OnPropertyChanged(nameof(NavSettings));
|
||||
OnPropertyChanged(nameof(HomeDescription));
|
||||
OnPropertyChanged(nameof(ThemeButtonText));
|
||||
@@ -64,9 +131,6 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
[RelayCommand]
|
||||
private void ToggleTheme()
|
||||
{
|
||||
IsDarkTheme = !IsDarkTheme;
|
||||
_themeService.SetTheme(IsDarkTheme
|
||||
? Avalonia.Styling.ThemeVariant.Dark
|
||||
: Avalonia.Styling.ThemeVariant.Light);
|
||||
_themeService.ToggleTheme();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using Avalonia.Media.Imaging;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using QRCoder;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// 网易云扫码登录对话框。
|
||||
/// </summary>
|
||||
public partial class QrCodeLoginViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUILocalizationService? _localization;
|
||||
private bool _isClosed;
|
||||
|
||||
[ObservableProperty]
|
||||
private Bitmap? _qrCodeImage;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _statusText = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _hasImage;
|
||||
|
||||
/// <summary>
|
||||
/// 请求关闭登录对话框。
|
||||
/// </summary>
|
||||
public event EventHandler? CloseRequested;
|
||||
|
||||
/// <summary>
|
||||
/// 登录完成前关闭对话框时触发。
|
||||
/// </summary>
|
||||
public event EventHandler? Cancelled;
|
||||
|
||||
/// <summary>
|
||||
/// 是否已登录成功。
|
||||
/// </summary>
|
||||
public bool IsCompleted { get; private set; }
|
||||
|
||||
/// <summary>登录窗口标题。</summary>
|
||||
public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music";
|
||||
/// <summary>扫码登录提示。</summary>
|
||||
public string LoginTip => _localization?["NetEase_LoginTip"] ?? "Scan the QR code with the NetEase Cloud Music app on your phone.";
|
||||
/// <summary>取消按钮文案。</summary>
|
||||
public string CancelText => _localization?["Common_Cancel"] ?? "Cancel";
|
||||
|
||||
/// <summary>
|
||||
/// 创建扫码登录对话框状态。
|
||||
/// </summary>
|
||||
public QrCodeLoginViewModel(IUILocalizationService? localization = null)
|
||||
{
|
||||
_localization = localization;
|
||||
_statusText = WaitText;
|
||||
}
|
||||
|
||||
private string WaitText => _localization?["NetEase_LoginWaiting"] ?? "Waiting for you to scan...";
|
||||
private string ScannedText => _localization?["NetEase_LoginScanned"] ?? "Scanned, please confirm on your phone.";
|
||||
private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in.";
|
||||
|
||||
/// <summary>
|
||||
/// 显示扫描器提供的二维码。
|
||||
/// </summary>
|
||||
public void SetPayload(NetEaseQrCodePayload payload)
|
||||
{
|
||||
if (_isClosed) return;
|
||||
|
||||
var previousImage = QrCodeImage;
|
||||
QrCodeImage = RenderQrCode(payload.Content);
|
||||
HasImage = QrCodeImage != null;
|
||||
previousImage?.Dispose();
|
||||
StatusText = HasImage
|
||||
? WaitText
|
||||
: _localization?["NetEase_LoginFailed"] ?? "Login did not complete. Close this dialog and try again.";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新扫码登录状态。
|
||||
/// </summary>
|
||||
public void SetState(NetEaseLoginState state)
|
||||
{
|
||||
if (_isClosed) return;
|
||||
|
||||
StatusText = state switch
|
||||
{
|
||||
NetEaseLoginState.ScanConfirmed => ScannedText,
|
||||
NetEaseLoginState.Succeeded => SuccessText,
|
||||
NetEaseLoginState.Expired => _localization?["NetEase_LoginExpired"] ?? "The QR code expired. Close this dialog and try again.",
|
||||
_ => WaitText
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 显示登录错误。
|
||||
/// </summary>
|
||||
public void SetError(string message)
|
||||
{
|
||||
if (_isClosed) return;
|
||||
|
||||
StatusText = message;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记登录完成并关闭对话框。
|
||||
/// </summary>
|
||||
public void Complete()
|
||||
{
|
||||
if (_isClosed) return;
|
||||
|
||||
IsCompleted = true;
|
||||
RequestClose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 请求关闭对话框。
|
||||
/// </summary>
|
||||
public void RequestClose()
|
||||
{
|
||||
CloseRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 窗口关闭后停止登录并释放二维码。
|
||||
/// </summary>
|
||||
public void NotifyClosed()
|
||||
{
|
||||
if (_isClosed) return;
|
||||
|
||||
_isClosed = true;
|
||||
var image = QrCodeImage;
|
||||
QrCodeImage = null;
|
||||
HasImage = false;
|
||||
image?.Dispose();
|
||||
|
||||
if (!IsCompleted)
|
||||
{
|
||||
Cancelled?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private static Bitmap? RenderQrCode(string content)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var generator = new QRCodeGenerator();
|
||||
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
|
||||
using var qrCode = new PngByteQRCode(data);
|
||||
using var stream = new MemoryStream(qrCode.GetGraphic(12));
|
||||
return new Bitmap(stream);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 二维码无法生成时,由界面显示登录失败提示。
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,20 @@ using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Microsoft.Extensions.Options;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
/// <summary>设置页面及自动保存状态。</summary>
|
||||
public partial class SettingsViewModel : ViewModelBase
|
||||
{
|
||||
private readonly GlobalOptions _globalOptions;
|
||||
private readonly ISettingsStore _settingsStore;
|
||||
private readonly IUILocalizationService? _localizationService;
|
||||
private bool _isLoading = true; // Prevent saving during initial load
|
||||
private readonly GlobalOptions _globalOptions;
|
||||
private bool _isLoading = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _followSystemLanguage = true;
|
||||
@@ -32,7 +33,7 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
private string _proxyIp = "127.0.0.1";
|
||||
|
||||
[ObservableProperty]
|
||||
private int _proxyPort = 7890;
|
||||
private int _proxyPort = 4780;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isTranslationEnabled;
|
||||
@@ -46,18 +47,40 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
[ObservableProperty]
|
||||
private string _selectedEncoding = "utf-8";
|
||||
|
||||
// Localized strings
|
||||
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
|
||||
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
|
||||
public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System";
|
||||
public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese";
|
||||
public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English";
|
||||
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
|
||||
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
|
||||
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
|
||||
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
|
||||
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
|
||||
[ObservableProperty]
|
||||
private bool _isOnlyOutputTranslation;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _selectedLineBreakIndex;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isBlockWordEnabled;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _blockWordFilePath = "BlockWords.json";
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isRomanOutputEnabled;
|
||||
|
||||
/// <summary>是否显示高级设置。</summary>
|
||||
[ObservableProperty]
|
||||
private bool _isAdvancedVisible;
|
||||
|
||||
// 显示配置位置及上次保存结果。
|
||||
[ObservableProperty]
|
||||
private string _storageHint = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(ShowSaveSuccess))]
|
||||
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
|
||||
private string _saveStatusText = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(ShowSaveSuccess))]
|
||||
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
|
||||
private bool _hasSaveError;
|
||||
|
||||
/// <summary>可选择的歌词编码。</summary>
|
||||
public ObservableCollection<string> AvailableEncodings { get; } = new()
|
||||
{
|
||||
"utf-8",
|
||||
@@ -66,14 +89,119 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
"gbk"
|
||||
};
|
||||
|
||||
/// <summary>预设换行符,与显示列表顺序一致。</summary>
|
||||
private static readonly string[] LineBreaks =
|
||||
{
|
||||
LineBreakType.Unix,
|
||||
LineBreakType.Windows,
|
||||
LineBreakType.MacOs
|
||||
};
|
||||
|
||||
/// <summary>换行符的显示名称。</summary>
|
||||
public ObservableCollection<string> LineBreakDisplayNames { get; } = new()
|
||||
{
|
||||
"LF (Unix)",
|
||||
"CRLF (Windows)",
|
||||
"CR (macOS)"
|
||||
};
|
||||
|
||||
private string CurrentLineBreak => SelectedLineBreakIndex >= 0 && SelectedLineBreakIndex < LineBreaks.Length
|
||||
? LineBreaks[SelectedLineBreakIndex]
|
||||
: _globalOptions.Provider?.Lyric?.Config?.LineBreak ?? LineBreakType.Unix;
|
||||
|
||||
/// <summary>歌词提供者及搜索顺序。</summary>
|
||||
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new();
|
||||
|
||||
public SettingsViewModel(IOptions<GlobalOptions> options, IUILocalizationService? localizationService = null)
|
||||
{
|
||||
_globalOptions = options.Value;
|
||||
_localizationService = localizationService;
|
||||
/// <summary>标签提供者及加载顺序。</summary>
|
||||
public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new();
|
||||
|
||||
// Subscribe to language changes
|
||||
// 本地化文本。
|
||||
/// <summary>设置标题的本地化文本。</summary>
|
||||
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
|
||||
/// <summary>语言设置标题的本地化文本。</summary>
|
||||
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
|
||||
/// <summary>跟随系统语言的本地化文本。</summary>
|
||||
public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System";
|
||||
/// <summary>中文选项的本地化文本。</summary>
|
||||
public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese";
|
||||
/// <summary>英文选项的本地化文本。</summary>
|
||||
public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English";
|
||||
/// <summary>代理设置标题的本地化文本。</summary>
|
||||
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
|
||||
/// <summary>启用代理的本地化文本。</summary>
|
||||
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
|
||||
/// <summary>代理地址的本地化文本。</summary>
|
||||
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
|
||||
/// <summary>代理端口的本地化文本。</summary>
|
||||
public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port";
|
||||
/// <summary>歌词提供者标题的本地化文本。</summary>
|
||||
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
|
||||
/// <summary>恢复默认值的本地化文本。</summary>
|
||||
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
|
||||
|
||||
/// <summary>基本设置标题的本地化文本。</summary>
|
||||
public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics";
|
||||
/// <summary>高级设置标题的本地化文本。</summary>
|
||||
public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced";
|
||||
/// <summary>高级选项开关的本地化文本。</summary>
|
||||
public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options";
|
||||
/// <summary>歌词设置标题的本地化文本。</summary>
|
||||
public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics";
|
||||
/// <summary>翻译开关的本地化文本。</summary>
|
||||
public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics";
|
||||
/// <summary>合并双语歌词开关的本地化文本。</summary>
|
||||
public string SettingsOneLineMode => _localizationService?["Settings_OneLineMode"] ?? "One-line mode (original + translation on same line)";
|
||||
/// <summary>仅输出翻译开关的本地化文本。</summary>
|
||||
public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only";
|
||||
/// <summary>跳过已有文件开关的本地化文本。</summary>
|
||||
public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files";
|
||||
/// <summary>编码选项的本地化文本。</summary>
|
||||
public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:";
|
||||
/// <summary>换行符选项的本地化文本。</summary>
|
||||
public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:";
|
||||
/// <summary>罗马音开关的本地化文本。</summary>
|
||||
public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)";
|
||||
/// <summary>屏蔽词设置标题的本地化文本。</summary>
|
||||
public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary";
|
||||
/// <summary>屏蔽词开关的本地化文本。</summary>
|
||||
public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary";
|
||||
/// <summary>屏蔽词路径的本地化文本。</summary>
|
||||
public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the working directory)";
|
||||
/// <summary>标签提供者标题的本地化文本。</summary>
|
||||
public string SettingsTagProvider => _localizationService?["Settings_TagProvider"] ?? "Tag Provider";
|
||||
/// <summary>优先级标题的本地化文本。</summary>
|
||||
public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: ";
|
||||
/// <summary>上移按钮的本地化文本。</summary>
|
||||
public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up";
|
||||
/// <summary>下移按钮的本地化文本。</summary>
|
||||
public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down";
|
||||
/// <summary>提供者顺序说明的本地化文本。</summary>
|
||||
public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"]
|
||||
?? "The list order is the search order. Use the arrows to change which source is tried first.";
|
||||
/// <summary>设置保存位置的本地化文本。</summary>
|
||||
public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file";
|
||||
/// <summary>保存成功的本地化文本。</summary>
|
||||
public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved";
|
||||
/// <summary>保存失败的本地化文本。</summary>
|
||||
public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings";
|
||||
/// <summary>代理重启提示的本地化文本。</summary>
|
||||
public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"]
|
||||
?? "Proxy changes take effect the next time the app starts.";
|
||||
|
||||
/// <summary>是否显示保存成功提示。</summary>
|
||||
public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
|
||||
|
||||
/// <summary>是否显示保存失败提示。</summary>
|
||||
public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
|
||||
|
||||
/// <summary>创建设置页面。</summary>
|
||||
public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null)
|
||||
{
|
||||
_settingsStore = settingsStore;
|
||||
_localizationService = localizationService;
|
||||
_globalOptions = settingsStore.Options;
|
||||
|
||||
// 跟随应用语言切换更新界面。
|
||||
if (_localizationService != null)
|
||||
{
|
||||
_localizationService.LanguageChanged += OnLanguageChanged;
|
||||
@@ -81,7 +209,8 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
|
||||
LoadSettings();
|
||||
LoadLanguageSettings();
|
||||
_isLoading = false; // Allow saving after initial load
|
||||
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
|
||||
_isLoading = false;
|
||||
}
|
||||
|
||||
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||
@@ -94,8 +223,33 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
OnPropertyChanged(nameof(SettingsProxy));
|
||||
OnPropertyChanged(nameof(SettingsProxyEnable));
|
||||
OnPropertyChanged(nameof(SettingsProxyAddress));
|
||||
OnPropertyChanged(nameof(SettingsProxyPort));
|
||||
OnPropertyChanged(nameof(SettingsLyricsProvider));
|
||||
OnPropertyChanged(nameof(SettingsReset));
|
||||
OnPropertyChanged(nameof(SettingsBasicSection));
|
||||
OnPropertyChanged(nameof(SettingsAdvancedSection));
|
||||
OnPropertyChanged(nameof(SettingsShowAdvanced));
|
||||
OnPropertyChanged(nameof(SettingsLyricsSection));
|
||||
OnPropertyChanged(nameof(SettingsEnableTranslation));
|
||||
OnPropertyChanged(nameof(SettingsOneLineMode));
|
||||
OnPropertyChanged(nameof(SettingsOnlyTranslation));
|
||||
OnPropertyChanged(nameof(SettingsSkipExisting));
|
||||
OnPropertyChanged(nameof(SettingsFileEncoding));
|
||||
OnPropertyChanged(nameof(SettingsLineBreak));
|
||||
OnPropertyChanged(nameof(SettingsRomanOutput));
|
||||
OnPropertyChanged(nameof(SettingsBlockWordSection));
|
||||
OnPropertyChanged(nameof(SettingsBlockWordEnable));
|
||||
OnPropertyChanged(nameof(SettingsBlockWordPath));
|
||||
OnPropertyChanged(nameof(SettingsTagProvider));
|
||||
OnPropertyChanged(nameof(SettingsPriority));
|
||||
OnPropertyChanged(nameof(SettingsMoveUp));
|
||||
OnPropertyChanged(nameof(SettingsMoveDown));
|
||||
OnPropertyChanged(nameof(SettingsProviderOrderHint));
|
||||
OnPropertyChanged(nameof(SettingsStorage));
|
||||
OnPropertyChanged(nameof(SettingsSaved));
|
||||
OnPropertyChanged(nameof(SettingsSaveFailed));
|
||||
OnPropertyChanged(nameof(SettingsProxyRestartHint));
|
||||
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
|
||||
}
|
||||
|
||||
private void LoadLanguageSettings()
|
||||
@@ -109,7 +263,7 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
{
|
||||
if (value)
|
||||
{
|
||||
// Auto-detect system language
|
||||
// 使用操作系统语言。
|
||||
var systemCulture = CultureInfo.InstalledUICulture.Name;
|
||||
ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US");
|
||||
}
|
||||
@@ -141,6 +295,11 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
partial void OnIsOneLineModeChanged(bool value) => SaveSettingsIfNotLoading();
|
||||
partial void OnSkipExistingLyricsChanged(bool value) => SaveSettingsIfNotLoading();
|
||||
partial void OnSelectedEncodingChanged(string value) => SaveSettingsIfNotLoading();
|
||||
partial void OnIsOnlyOutputTranslationChanged(bool value) => SaveSettingsIfNotLoading();
|
||||
partial void OnSelectedLineBreakIndexChanged(int value) => SaveSettingsIfNotLoading();
|
||||
partial void OnIsBlockWordEnabledChanged(bool value) => SaveSettingsIfNotLoading();
|
||||
partial void OnBlockWordFilePathChanged(string value) => SaveSettingsIfNotLoading();
|
||||
partial void OnIsRomanOutputEnabledChanged(bool value) => SaveSettingsIfNotLoading();
|
||||
|
||||
private void ApplyLanguage(string cultureName)
|
||||
{
|
||||
@@ -149,20 +308,23 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
|
||||
private void SaveSettingsIfNotLoading()
|
||||
{
|
||||
if (!_isLoading)
|
||||
if (_isLoading)
|
||||
{
|
||||
SaveSettingsToFile();
|
||||
return;
|
||||
}
|
||||
|
||||
WriteSettingsToOptions();
|
||||
_ = SaveSettingsAsync();
|
||||
}
|
||||
|
||||
private void LoadSettings()
|
||||
{
|
||||
// Load network settings
|
||||
// 加载代理设置。
|
||||
IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false;
|
||||
ProxyIp = _globalOptions.NetworkOptions?.Ip ?? "127.0.0.1";
|
||||
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 7890;
|
||||
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 4780;
|
||||
|
||||
// Load lyrics settings
|
||||
// 加载歌词设置,保留未列入预设的有效编码。
|
||||
var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
|
||||
if (lyricsConfig != null)
|
||||
{
|
||||
@@ -170,84 +332,469 @@ public partial class SettingsViewModel : ViewModelBase
|
||||
IsOneLineMode = lyricsConfig.IsOneLine;
|
||||
SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles;
|
||||
SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8";
|
||||
if (!AvailableEncodings.Contains(SelectedEncoding))
|
||||
{
|
||||
AvailableEncodings.Add(SelectedEncoding);
|
||||
}
|
||||
IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation;
|
||||
SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak);
|
||||
}
|
||||
|
||||
// Load lyrics providers
|
||||
// 加载屏蔽词设置。
|
||||
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
|
||||
if (blockWord != null)
|
||||
{
|
||||
IsBlockWordEnabled = blockWord.IsEnable;
|
||||
BlockWordFilePath = string.IsNullOrWhiteSpace(blockWord.FilePath)
|
||||
? "BlockWords.json"
|
||||
: blockWord.FilePath;
|
||||
}
|
||||
|
||||
// 罗马音开关保存在网易云提供者的扩展设置中。
|
||||
var netEase = _globalOptions.Provider?.Lyric?.Plugin?
|
||||
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
|
||||
if (netEase?.Additional != null &&
|
||||
netEase.Additional.TryGetValue("isEnableRomanOutput", out var romanValue))
|
||||
{
|
||||
IsRomanOutputEnabled = string.Equals(romanValue, "true", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// 启用的提供者按优先级排列,禁用项放到末尾。
|
||||
var tagProviders = _globalOptions.Provider?.Tag?.Plugin;
|
||||
if (tagProviders != null)
|
||||
{
|
||||
foreach (var provider in tagProviders.Where(p => p.Priority != -1).OrderBy(p => p.Priority))
|
||||
{
|
||||
AddTagProviderRow(provider.Name, true);
|
||||
}
|
||||
|
||||
// 禁用项不参与搜索。
|
||||
foreach (var provider in tagProviders.Where(p => p.Priority == -1))
|
||||
{
|
||||
AddTagProviderRow(provider.Name, false);
|
||||
}
|
||||
|
||||
NormalizeProviderOrder(TagProviders);
|
||||
}
|
||||
|
||||
// 歌词提供者与标签提供者采用相同排序规则。
|
||||
var providers = _globalOptions.Provider?.Lyric?.Plugin;
|
||||
if (providers != null)
|
||||
{
|
||||
foreach (var provider in providers.OrderBy(p => p.Priority))
|
||||
foreach (var provider in providers.Where(p => p.Priority != -1).OrderBy(p => p.Priority))
|
||||
{
|
||||
LyricsProviders.Add(new LyricsProviderSettingViewModel
|
||||
{
|
||||
Name = provider.Name ?? "Unknown",
|
||||
Priority = provider.Priority,
|
||||
IsEnabled = provider.Priority != -1
|
||||
});
|
||||
AddLyricsProviderRow(provider.Name, true);
|
||||
}
|
||||
|
||||
foreach (var provider in providers.Where(p => p.Priority == -1))
|
||||
{
|
||||
AddLyricsProviderRow(provider.Name, false);
|
||||
}
|
||||
|
||||
NormalizeProviderOrder(LyricsProviders);
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveSettingsToFile()
|
||||
private void AddTagProviderRow(string? name, bool isEnabled)
|
||||
{
|
||||
var row = new TagInfoProviderSettingViewModel
|
||||
{
|
||||
Name = name ?? "Unknown",
|
||||
IsEnabled = isEnabled
|
||||
};
|
||||
|
||||
// 创建行后绑定移动命令。
|
||||
row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, -1));
|
||||
row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, 1));
|
||||
|
||||
// 将行内编辑接入自动保存。
|
||||
row.PropertyChanged += OnProviderRowChanged;
|
||||
TagProviders.Add(row);
|
||||
}
|
||||
|
||||
private void AddLyricsProviderRow(string? name, bool isEnabled)
|
||||
{
|
||||
var row = new LyricsProviderSettingViewModel
|
||||
{
|
||||
Name = name ?? "Unknown",
|
||||
IsEnabled = isEnabled
|
||||
};
|
||||
|
||||
row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, -1));
|
||||
row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, 1));
|
||||
|
||||
row.PropertyChanged += OnProviderRowChanged;
|
||||
LyricsProviders.Add(row);
|
||||
}
|
||||
|
||||
/// <summary>提供者启用状态改变后重新排序并保存。</summary>
|
||||
private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||
{
|
||||
if (_isLoading || _isNormalizing)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.PropertyName is nameof(LyricsProviderSettingViewModel.IsEnabled)
|
||||
or nameof(TagInfoProviderSettingViewModel.IsEnabled))
|
||||
{
|
||||
_isNormalizing = true;
|
||||
try
|
||||
{
|
||||
if (sender is LyricsProviderSettingViewModel) NormalizeProviderOrder(LyricsProviders);
|
||||
else if (sender is TagInfoProviderSettingViewModel) NormalizeProviderOrder(TagProviders);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isNormalizing = false;
|
||||
}
|
||||
|
||||
SaveSettingsIfNotLoading();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.PropertyName is nameof(LyricsProviderSettingViewModel.Priority)
|
||||
or nameof(TagInfoProviderSettingViewModel.Priority))
|
||||
{
|
||||
SaveSettingsIfNotLoading();
|
||||
}
|
||||
}
|
||||
|
||||
private bool _isNormalizing;
|
||||
|
||||
/// <summary>启用项在前,优先级按可见顺序从一开始。</summary>
|
||||
private void NormalizeProviderOrder<T>(ObservableCollection<T> rows) where T : class, IProviderRowViewModel
|
||||
{
|
||||
var ordered = rows.Where(r => r.IsEnabled).Concat(rows.Where(r => !r.IsEnabled)).ToList();
|
||||
|
||||
for (var target = 0; target < ordered.Count; target++)
|
||||
{
|
||||
var current = rows.IndexOf(ordered[target]);
|
||||
if (current != target)
|
||||
{
|
||||
rows.Move(current, target);
|
||||
}
|
||||
}
|
||||
|
||||
var enabledCount = ordered.Count(r => r.IsEnabled);
|
||||
for (var i = 0; i < ordered.Count; i++)
|
||||
{
|
||||
var row = ordered[i];
|
||||
|
||||
// 禁用项统一使用 -1。
|
||||
row.Priority = i < enabledCount ? i + 1 : -1;
|
||||
row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—";
|
||||
row.CanMoveUp = i > 0 && i < enabledCount;
|
||||
row.CanMoveDown = i + 1 < enabledCount;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>在启用项范围内移动提供者。</summary>
|
||||
private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset)
|
||||
where T : class, IProviderRowViewModel
|
||||
{
|
||||
var index = rows.IndexOf(row);
|
||||
var target = index + offset;
|
||||
if (index < 0 || target < 0 || target >= rows.Count || !row.IsEnabled || !rows[target].IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isNormalizing = true;
|
||||
try
|
||||
{
|
||||
// Update GlobalOptions with current values
|
||||
if (_globalOptions.NetworkOptions != null)
|
||||
{
|
||||
_globalOptions.NetworkOptions.IsEnable = IsProxyEnabled;
|
||||
_globalOptions.NetworkOptions.Ip = ProxyIp;
|
||||
_globalOptions.NetworkOptions.Port = ProxyPort;
|
||||
}
|
||||
|
||||
if (_globalOptions.Provider?.Lyric?.Config != null)
|
||||
{
|
||||
_globalOptions.Provider.Lyric.Config.IsEnableTranslation = IsTranslationEnabled;
|
||||
_globalOptions.Provider.Lyric.Config.IsOneLine = IsOneLineMode;
|
||||
_globalOptions.Provider.Lyric.Config.IsSkipExistLyricFiles = SkipExistingLyrics;
|
||||
_globalOptions.Provider.Lyric.Config.FileEncoding = SelectedEncoding;
|
||||
}
|
||||
|
||||
// Serialize and save to file
|
||||
var serializer = new SerializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.Build();
|
||||
|
||||
var yaml = serializer.Serialize(_globalOptions);
|
||||
var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.yaml");
|
||||
File.WriteAllText(configPath, yaml);
|
||||
rows.Move(index, target);
|
||||
NormalizeProviderOrder(rows);
|
||||
}
|
||||
catch (Exception ex)
|
||||
finally
|
||||
{
|
||||
// Log error but don't crash - settings save is best effort
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}");
|
||||
_isNormalizing = false;
|
||||
}
|
||||
|
||||
SaveSettingsIfNotLoading();
|
||||
}
|
||||
|
||||
private static int ResolveLineBreakIndex(string? value)
|
||||
{
|
||||
for (var i = 0; i < LineBreaks.Length; i++)
|
||||
{
|
||||
if (string.Equals(LineBreaks[i], value, StringComparison.Ordinal))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void WriteSettingsToOptions()
|
||||
{
|
||||
if (_globalOptions.NetworkOptions != null)
|
||||
{
|
||||
_globalOptions.NetworkOptions.IsEnable = IsProxyEnabled;
|
||||
_globalOptions.NetworkOptions.Ip = ProxyIp;
|
||||
_globalOptions.NetworkOptions.Port = ProxyPort;
|
||||
}
|
||||
|
||||
var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
|
||||
if (lyricsConfig != null)
|
||||
{
|
||||
lyricsConfig.IsEnableTranslation = IsTranslationEnabled;
|
||||
lyricsConfig.IsOneLine = IsOneLineMode;
|
||||
lyricsConfig.IsSkipExistLyricFiles = SkipExistingLyrics;
|
||||
lyricsConfig.FileEncoding = SelectedEncoding;
|
||||
lyricsConfig.IsOnlyOutputTranslation = IsOnlyOutputTranslation;
|
||||
lyricsConfig.LineBreak = CurrentLineBreak;
|
||||
}
|
||||
|
||||
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
|
||||
if (blockWord != null)
|
||||
{
|
||||
blockWord.IsEnable = IsBlockWordEnabled;
|
||||
blockWord.FilePath = BlockWordFilePath;
|
||||
}
|
||||
|
||||
var netEase = _globalOptions.Provider?.Lyric?.Plugin?
|
||||
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
|
||||
if (netEase != null)
|
||||
{
|
||||
netEase.Additional ??= new Dictionary<string, string>();
|
||||
netEase.Additional["isEnableRomanOutput"] = IsRomanOutputEnabled ? "true" : "false";
|
||||
}
|
||||
|
||||
// 同步启用状态及搜索顺序。
|
||||
ApplyProviderSelection(_globalOptions.Provider?.Lyric?.Plugin, LyricsProviders);
|
||||
ApplyProviderSelection(_globalOptions.Provider?.Tag?.Plugin, TagProviders);
|
||||
}
|
||||
|
||||
/// <summary>将歌词提供者的界面顺序写入共享配置。</summary>
|
||||
private static void ApplyProviderSelection(
|
||||
IEnumerable<LyricsProviderOptions>? options,
|
||||
IEnumerable<LyricsProviderSettingViewModel> viewModels)
|
||||
{
|
||||
if (options == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var optionList = options.ToList();
|
||||
var order = 1;
|
||||
|
||||
foreach (var row in viewModels)
|
||||
{
|
||||
var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (option == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
option.Priority = row.IsEnabled ? order++ : -1;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ResetToDefaults()
|
||||
private static void ApplyProviderSelection(
|
||||
IEnumerable<TagInfoProviderOptions>? options,
|
||||
IEnumerable<TagInfoProviderSettingViewModel> viewModels)
|
||||
{
|
||||
_isLoading = true; // Prevent multiple saves during reset
|
||||
if (options == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var optionList = options.ToList();
|
||||
var order = 1;
|
||||
|
||||
foreach (var row in viewModels)
|
||||
{
|
||||
var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (option == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
option.Priority = row.IsEnabled ? order++ : -1;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveSettingsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
// 合并连续输入,但配置在内存中立即生效。
|
||||
var pending = Interlocked.Increment(ref _saveRequestId);
|
||||
await Task.Delay(SaveDebounceMilliseconds, cancellationToken).ConfigureAwait(true);
|
||||
|
||||
if (pending != Volatile.Read(ref _saveRequestId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
|
||||
if (pending != Volatile.Read(ref _saveRequestId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
HasSaveError = !result.IsSuccess;
|
||||
SaveStatusText = result.IsSuccess
|
||||
? $"{SettingsSaved}: {result.FilePath}"
|
||||
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
|
||||
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
|
||||
}
|
||||
|
||||
private int _saveRequestId;
|
||||
private const int SaveDebounceMilliseconds = 400;
|
||||
|
||||
[RelayCommand]
|
||||
private async Task ResetToDefaultsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
Interlocked.Increment(ref _saveRequestId);
|
||||
_isLoading = true;
|
||||
IsProxyEnabled = false;
|
||||
ProxyIp = "127.0.0.1";
|
||||
ProxyPort = 7890;
|
||||
IsTranslationEnabled = false;
|
||||
IsOneLineMode = false;
|
||||
SkipExistingLyrics = true;
|
||||
ProxyPort = 4780;
|
||||
IsTranslationEnabled = true;
|
||||
IsOneLineMode = true;
|
||||
SkipExistingLyrics = false;
|
||||
IsOnlyOutputTranslation = false;
|
||||
SelectedEncoding = "utf-8";
|
||||
SelectedLineBreakIndex = 0;
|
||||
IsBlockWordEnabled = false;
|
||||
BlockWordFilePath = "BlockWords.json";
|
||||
IsRomanOutputEnabled = false;
|
||||
|
||||
// 恢复随程序附带的默认顺序,额外提供者保留在末尾。
|
||||
RestoreProviderOrder(LyricsProviders, ["NetEase", "QQ", "KuGou", "KuWo"], row => row.Name);
|
||||
RestoreProviderOrder(TagProviders, ["Taglib", "FileName"], row => row.Name);
|
||||
foreach (var row in LyricsProviders)
|
||||
{
|
||||
row.IsEnabled = true;
|
||||
}
|
||||
|
||||
foreach (var row in TagProviders)
|
||||
{
|
||||
row.IsEnabled = true;
|
||||
}
|
||||
|
||||
NormalizeProviderOrder(LyricsProviders);
|
||||
NormalizeProviderOrder(TagProviders);
|
||||
|
||||
_isLoading = false;
|
||||
SaveSettingsToFile(); // Save once after all resets
|
||||
|
||||
// 所有默认值恢复后只保存一次。
|
||||
WriteSettingsToOptions();
|
||||
var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
|
||||
HasSaveError = !result.IsSuccess;
|
||||
SaveStatusText = result.IsSuccess
|
||||
? $"{SettingsSaved}: {result.FilePath}"
|
||||
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
|
||||
}
|
||||
|
||||
private static void RestoreProviderOrder<T>(ObservableCollection<T> rows, string[] names, Func<T, string> getName)
|
||||
where T : class
|
||||
{
|
||||
var target = 0;
|
||||
foreach (var name in names)
|
||||
{
|
||||
var row = rows.FirstOrDefault(row => string.Equals(getName(row), name, StringComparison.OrdinalIgnoreCase));
|
||||
if (row is not null)
|
||||
{
|
||||
rows.Move(rows.IndexOf(row), target++);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public partial class LyricsProviderSettingViewModel : ObservableObject
|
||||
/// <summary>可排序的提供者设置行。</summary>
|
||||
public interface IProviderRowViewModel
|
||||
{
|
||||
/// <summary>是否启用。</summary>
|
||||
bool IsEnabled { get; set; }
|
||||
|
||||
/// <summary>搜索优先级,禁用时为 -1。</summary>
|
||||
int Priority { get; set; }
|
||||
|
||||
/// <summary>界面显示的顺序。</summary>
|
||||
string PriorityLabel { get; set; }
|
||||
|
||||
/// <summary>是否可以向上移动。</summary>
|
||||
bool CanMoveUp { get; set; }
|
||||
|
||||
/// <summary>是否可以向下移动。</summary>
|
||||
bool CanMoveDown { get; set; }
|
||||
|
||||
/// <summary>禁用时降低行透明度。</summary>
|
||||
double RowOpacity { get; }
|
||||
|
||||
/// <summary>向上移动命令。</summary>
|
||||
IRelayCommand MoveUpCommand { get; }
|
||||
|
||||
/// <summary>向下移动命令。</summary>
|
||||
IRelayCommand MoveDownCommand { get; }
|
||||
}
|
||||
|
||||
/// <summary>歌词提供者设置行。</summary>
|
||||
public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string _name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(RowOpacity))]
|
||||
private bool _isEnabled;
|
||||
|
||||
/// <summary>搜索优先级,禁用时为 -1。</summary>
|
||||
[ObservableProperty]
|
||||
private int _priority;
|
||||
|
||||
/// <summary>显示的顺序,禁用时显示横线。</summary>
|
||||
[ObservableProperty]
|
||||
private string _priorityLabel = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _canMoveUp;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _canMoveDown;
|
||||
|
||||
/// <inheritdoc />
|
||||
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
|
||||
}
|
||||
|
||||
/// <summary>标签提供者设置行。</summary>
|
||||
public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string _name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(RowOpacity))]
|
||||
private bool _isEnabled;
|
||||
|
||||
/// <inheritdoc cref="LyricsProviderSettingViewModel.Priority" />
|
||||
[ObservableProperty]
|
||||
private int _priority;
|
||||
|
||||
/// <inheritdoc cref="LyricsProviderSettingViewModel.PriorityLabel" />
|
||||
[ObservableProperty]
|
||||
private string _priorityLabel = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _canMoveUp;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _canMoveDown;
|
||||
|
||||
/// <inheritdoc />
|
||||
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
|
||||
}
|
||||
@@ -28,10 +28,10 @@
|
||||
HorizontalAlignment="Right"
|
||||
Spacing="8">
|
||||
<Button x:Name="CancelButton"
|
||||
MinWidth="80"
|
||||
MinWidth="88"
|
||||
Click="OnCancelClick" />
|
||||
<Button x:Name="ConfirmButton"
|
||||
MinWidth="80"
|
||||
MinWidth="88"
|
||||
Classes="accent"
|
||||
Click="OnConfirmClick" />
|
||||
</StackPanel>
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="ZonyLrcTools.Desktop.Views.Dialogs.MessageDialog"
|
||||
Title=""
|
||||
Width="400"
|
||||
Height="200"
|
||||
Width="480"
|
||||
MaxHeight="520"
|
||||
CanResize="False"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
SizeToContent="Height">
|
||||
|
||||
<Grid Margin="24" RowDefinitions="Auto,*,Auto">
|
||||
<Grid Margin="24" RowDefinitions="Auto,Auto,Auto">
|
||||
<!-- Title -->
|
||||
<TextBlock Grid.Row="0"
|
||||
x:Name="TitleText"
|
||||
@@ -16,17 +16,29 @@
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,0,12" />
|
||||
|
||||
<!-- Message -->
|
||||
<TextBlock Grid.Row="1"
|
||||
x:Name="MessageText"
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,0,0,20" />
|
||||
<!-- 正文可选中并复制。 -->
|
||||
<TextBox Grid.Row="1"
|
||||
x:Name="MessageText"
|
||||
IsReadOnly="True"
|
||||
AcceptsReturn="True"
|
||||
TextWrapping="Wrap"
|
||||
MaxHeight="380"
|
||||
BorderThickness="0"
|
||||
Background="Transparent"
|
||||
Padding="0"
|
||||
Margin="0,0,0,20" />
|
||||
|
||||
<!-- OK Button -->
|
||||
<Button Grid.Row="2"
|
||||
x:Name="OkButton"
|
||||
HorizontalAlignment="Right"
|
||||
MinWidth="80"
|
||||
Click="OnOkClick" />
|
||||
<!-- Buttons -->
|
||||
<StackPanel Grid.Row="2"
|
||||
Orientation="Horizontal"
|
||||
HorizontalAlignment="Right"
|
||||
Spacing="8">
|
||||
<Button x:Name="CopyButton"
|
||||
MinWidth="88"
|
||||
Click="OnCopyClick" />
|
||||
<Button x:Name="OkButton"
|
||||
MinWidth="88"
|
||||
Click="OnOkClick" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -20,6 +20,18 @@ public partial class MessageDialog : Window
|
||||
|
||||
var localization = App.Services?.GetService<IUILocalizationService>();
|
||||
OkButton.Content = localization?["Common_OK"] ?? "OK";
|
||||
CopyButton.Content = localization?["Common_Copy"] ?? "Copy";
|
||||
}
|
||||
|
||||
private async void OnCopyClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
|
||||
if (clipboard == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await clipboard.SetTextAsync(MessageText.Text ?? string.Empty);
|
||||
}
|
||||
|
||||
private void OnOkClick(object? sender, RoutedEventArgs e)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels"
|
||||
x:Class="ZonyLrcTools.Desktop.Views.Dialogs.QrCodeLoginDialog"
|
||||
x:DataType="vm:QrCodeLoginViewModel"
|
||||
Width="380"
|
||||
SizeToContent="Height"
|
||||
CanResize="False"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<StackPanel Margin="24" Spacing="16">
|
||||
<TextBlock Text="{Binding LoginTitle}"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
TextWrapping="Wrap" />
|
||||
|
||||
<TextBlock Text="{Binding LoginTip}"
|
||||
FontSize="12"
|
||||
Opacity="0.65"
|
||||
TextWrapping="Wrap" />
|
||||
|
||||
<!-- 固定二维码区域尺寸,避免加载时窗口跳动。 -->
|
||||
<Border Width="240" Height="240"
|
||||
HorizontalAlignment="Center"
|
||||
Background="White"
|
||||
CornerRadius="8"
|
||||
Padding="8">
|
||||
<Panel>
|
||||
<Image Source="{Binding QrCodeImage}"
|
||||
Stretch="Uniform"
|
||||
IsVisible="{Binding HasImage}" />
|
||||
|
||||
<TextBlock Text="..."
|
||||
FontSize="24"
|
||||
Opacity="0.3"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
IsVisible="{Binding !HasImage}" />
|
||||
</Panel>
|
||||
</Border>
|
||||
|
||||
<TextBlock Text="{Binding StatusText}"
|
||||
FontSize="13"
|
||||
HorizontalAlignment="Center"
|
||||
TextWrapping="Wrap"
|
||||
TextAlignment="Center" />
|
||||
|
||||
<Button Content="{Binding CancelText}"
|
||||
HorizontalAlignment="Right"
|
||||
MinWidth="88"
|
||||
Click="OnCancelClick" />
|
||||
</StackPanel>
|
||||
|
||||
</Window>
|
||||
@@ -0,0 +1,56 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Views.Dialogs;
|
||||
|
||||
/// <summary>
|
||||
/// 网易云扫码登录窗口。
|
||||
/// </summary>
|
||||
public partial class QrCodeLoginDialog : Window
|
||||
{
|
||||
private QrCodeLoginViewModel? _viewModel;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化登录窗口。
|
||||
/// </summary>
|
||||
public QrCodeLoginDialog()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用指定登录状态创建窗口。
|
||||
/// </summary>
|
||||
public QrCodeLoginDialog(QrCodeLoginViewModel viewModel) : this()
|
||||
{
|
||||
_viewModel = viewModel;
|
||||
DataContext = viewModel;
|
||||
Title = viewModel.LoginTitle;
|
||||
|
||||
viewModel.CloseRequested += OnCloseRequested;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
private void OnCloseRequested(object? sender, EventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
if (_viewModel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_viewModel.CloseRequested -= OnCloseRequested;
|
||||
_viewModel.NotifyClosed();
|
||||
_viewModel = null;
|
||||
}
|
||||
|
||||
private void OnCancelClick(object? sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
}
|
||||
@@ -92,8 +92,7 @@
|
||||
<!-- Navigation Menu -->
|
||||
<ListBox Classes="nav-list"
|
||||
SelectedIndex="{Binding SelectedNavigationIndex}"
|
||||
Margin="0,8,0,0"
|
||||
SelectionChanged="OnNavigationSelectionChanged">
|
||||
Margin="0,8,0,0">
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
@@ -130,6 +129,18 @@
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</ListBoxItem>
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
Background="{DynamicResource AppAccentBrush}"
|
||||
Margin="0,2"
|
||||
IsVisible="{Binding $parent[ListBoxItem].IsSelected}" />
|
||||
<PathIcon Data="{StaticResource LockIcon}"
|
||||
Width="16" Height="16" />
|
||||
<TextBlock Text="{Binding NavDecrypt}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</ListBoxItem>
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
@@ -161,6 +172,9 @@
|
||||
<DataTemplate DataType="vm:AlbumDownloadViewModel">
|
||||
<pages:AlbumDownloadPage />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="vm:DecryptViewModel">
|
||||
<pages:DecryptPage />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="vm:SettingsViewModel">
|
||||
<pages:SettingsPage />
|
||||
</DataTemplate>
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using Avalonia.Controls;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Views;
|
||||
|
||||
@@ -10,29 +8,4 @@ public partial class MainWindow : Window
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void OnNavigationSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not MainWindowViewModel viewModel) return;
|
||||
if (sender is not ListBox listBox) return;
|
||||
|
||||
var services = App.Services;
|
||||
if (services == null) return;
|
||||
|
||||
switch (listBox.SelectedIndex)
|
||||
{
|
||||
case 0:
|
||||
viewModel.CurrentPage = services.GetRequiredService<HomeViewModel>();
|
||||
break;
|
||||
case 1:
|
||||
viewModel.CurrentPage = services.GetRequiredService<LyricsDownloadViewModel>();
|
||||
break;
|
||||
case 2:
|
||||
viewModel.CurrentPage = services.GetRequiredService<AlbumDownloadViewModel>();
|
||||
break;
|
||||
case 3:
|
||||
viewModel.CurrentPage = services.GetRequiredService<SettingsViewModel>();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@
|
||||
<Button Grid.Row="0" Grid.Column="2"
|
||||
Content="{Binding AlbumBrowse}"
|
||||
Command="{Binding SelectFolderCommand}"
|
||||
MinWidth="80"
|
||||
MinWidth="88"
|
||||
HorizontalAlignment="Stretch" />
|
||||
|
||||
<!-- Separator -->
|
||||
@@ -70,8 +70,9 @@
|
||||
Orientation="Horizontal" Spacing="8">
|
||||
<Button Command="{Binding StartDownloadCommand}"
|
||||
IsVisible="{Binding !IsDownloading}"
|
||||
IsEnabled="{Binding CanStartDownload}"
|
||||
Classes="accent"
|
||||
MinWidth="120">
|
||||
MinWidth="132">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<PathIcon Data="{StaticResource DownloadIcon}"
|
||||
Width="14" Height="14" />
|
||||
@@ -82,10 +83,25 @@
|
||||
<Button Command="{Binding CancelDownloadCommand}"
|
||||
Content="{Binding AlbumStopDownload}"
|
||||
IsVisible="{Binding IsDownloading}"
|
||||
MinWidth="100" />
|
||||
MinWidth="108" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 3: Progress -->
|
||||
<!-- Row 3a: Scan progress -->
|
||||
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
|
||||
IsVisible="{Binding IsScanning}"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<ProgressBar Value="{Binding ScanProgressPercentage}"
|
||||
Maximum="100" Height="6" />
|
||||
<TextBlock HorizontalAlignment="Center" FontSize="12" Opacity="0.7">
|
||||
<Run Text="{Binding AlbumScanning}" />
|
||||
<Run Text=" " />
|
||||
<Run Text="{Binding ScanProgressCount}" />
|
||||
<Run Text=" / " />
|
||||
<Run Text="{Binding ScanTotalCount}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 3b: Download progress -->
|
||||
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
|
||||
IsVisible="{Binding IsDownloading}"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
@@ -113,15 +129,15 @@
|
||||
BorderThickness="0"
|
||||
Background="Transparent">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn x:DataType="vm:MusicFileViewModel"
|
||||
<DataGridTextColumn x:DataType="vm:AlbumFileViewModel"
|
||||
Header="{loc:Localize Column_SongName}"
|
||||
Binding="{Binding Name}"
|
||||
Width="*" />
|
||||
<DataGridTextColumn x:DataType="vm:MusicFileViewModel"
|
||||
<DataGridTextColumn x:DataType="vm:AlbumFileViewModel"
|
||||
Header="{loc:Localize Column_Artist}"
|
||||
Binding="{Binding Artist}"
|
||||
Width="200" />
|
||||
<DataGridTextColumn x:DataType="vm:MusicFileViewModel"
|
||||
<DataGridTextColumn x:DataType="vm:AlbumFileViewModel"
|
||||
Header="{loc:Localize Column_Status}"
|
||||
Binding="{Binding StatusMessage}"
|
||||
Width="120" />
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels"
|
||||
xmlns:loc="using:ZonyLrcTools.Desktop.Infrastructure.Localization"
|
||||
x:Class="ZonyLrcTools.Desktop.Views.Pages.DecryptPage"
|
||||
x:DataType="vm:DecryptViewModel">
|
||||
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
|
||||
<!-- Title -->
|
||||
<StackPanel Grid.Row="0" Margin="0,0,0,20">
|
||||
<TextBlock Text="{Binding DecryptTitle}"
|
||||
FontSize="24"
|
||||
FontWeight="Bold" />
|
||||
<TextBlock Text="{Binding DecryptDescription}"
|
||||
FontSize="13"
|
||||
Opacity="0.6"
|
||||
Margin="0,4,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Requirement strip: kgg needs the KuGou key database, say so before anything is pressed -->
|
||||
<Border Grid.Row="1"
|
||||
IsVisible="{Binding ShowDatabaseWarning}"
|
||||
Background="{DynamicResource CardBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource WarningColorBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Padding="16,12"
|
||||
Margin="0,0,0,16">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<PathIcon Grid.Column="0"
|
||||
Data="{StaticResource AlertIcon}"
|
||||
Width="16" Height="16"
|
||||
Foreground="{DynamicResource WarningColorBrush}"
|
||||
VerticalAlignment="Top"
|
||||
Margin="0,2,12,0" />
|
||||
<StackPanel Grid.Column="1" Spacing="4">
|
||||
<TextBlock Text="{Binding DecryptKugouRequirement}"
|
||||
FontSize="13"
|
||||
TextWrapping="Wrap" />
|
||||
<TextBlock Text="{Binding KugouDatabaseStatus}"
|
||||
FontSize="11"
|
||||
Opacity="0.6"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding DecryptSpecifyDatabase}"
|
||||
Command="{Binding SpecifyDatabaseCommand}"
|
||||
MinWidth="150"
|
||||
VerticalAlignment="Center"
|
||||
Margin="12,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Card 1: Form Controls -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="8"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24,20"
|
||||
Margin="0,0,0,16">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*,Auto">
|
||||
<!-- Row 0: File selection summary -->
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="{Binding DecryptFilesLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Row="0" Grid.Column="1"
|
||||
Text="{Binding SelectionSummary}"
|
||||
Watermark="{Binding DecryptSelectFiles}"
|
||||
IsReadOnly="True"
|
||||
Margin="16,0" />
|
||||
<StackPanel Grid.Row="0" Grid.Column="2"
|
||||
Orientation="Horizontal" Spacing="8">
|
||||
<Button Content="{Binding DecryptBrowse}"
|
||||
Command="{Binding SelectFilesCommand}"
|
||||
MinWidth="108" />
|
||||
<Button Content="{Binding DecryptClear}"
|
||||
Command="{Binding ClearFilesCommand}"
|
||||
MinWidth="88" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Separator -->
|
||||
<Border Grid.Row="1" Grid.ColumnSpan="3"
|
||||
Height="1"
|
||||
Background="{DynamicResource SeparatorBrush}"
|
||||
Opacity="0.5"
|
||||
Margin="0,16" />
|
||||
|
||||
<!-- Row 2: Parallel Count + Start Button -->
|
||||
<TextBlock Grid.Row="2" Grid.Column="0"
|
||||
Text="{Binding DecryptParallel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<NumericUpDown Grid.Row="2" Grid.Column="1"
|
||||
Value="{Binding ParallelCount}"
|
||||
Minimum="1"
|
||||
Maximum="32"
|
||||
Increment="1"
|
||||
Width="100"
|
||||
FormatString="0"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Margin="16,0" />
|
||||
<StackPanel Grid.Row="2" Grid.Column="2"
|
||||
Orientation="Horizontal" Spacing="8">
|
||||
<Button Command="{Binding StartDecryptCommand}"
|
||||
IsVisible="{Binding !IsDecrypting}"
|
||||
IsEnabled="{Binding CanStartDecrypt}"
|
||||
Classes="accent"
|
||||
MinWidth="132">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<PathIcon Data="{StaticResource DownloadIcon}"
|
||||
Width="14" Height="14" />
|
||||
<TextBlock Text="{Binding DecryptStart}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Command="{Binding CancelDecryptCommand}"
|
||||
Content="{Binding DecryptStop}"
|
||||
IsVisible="{Binding IsDecrypting}"
|
||||
MinWidth="108" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 3: Progress -->
|
||||
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
|
||||
IsVisible="{Binding IsDecrypting}"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<ProgressBar Value="{Binding ProgressPercentage}"
|
||||
Maximum="100" Height="6" />
|
||||
<TextBlock HorizontalAlignment="Center" FontSize="12" Opacity="0.7">
|
||||
<Run Text="{Binding CompletedCount}" />
|
||||
<Run Text=" / " />
|
||||
<Run Text="{Binding TotalCount}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Card 2: File List with Empty State -->
|
||||
<Panel Grid.Row="3">
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="8"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
ClipToBounds="True">
|
||||
<DataGrid ItemsSource="{Binding Files}"
|
||||
AutoGenerateColumns="False"
|
||||
IsReadOnly="True"
|
||||
CanUserResizeColumns="True"
|
||||
GridLinesVisibility="Horizontal"
|
||||
BorderThickness="0"
|
||||
Background="Transparent">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTemplateColumn x:DataType="vm:DecryptFileViewModel"
|
||||
Header="{loc:Localize Column_FileName}"
|
||||
Width="*">
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate x:DataType="vm:DecryptFileViewModel">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6"
|
||||
VerticalAlignment="Center">
|
||||
<PathIcon Data="{StaticResource AlertIcon}"
|
||||
Width="12" Height="12"
|
||||
Foreground="{DynamicResource ErrorColorBrush}"
|
||||
IsVisible="{Binding IsBlocked}"
|
||||
ToolTip.Tip="{Binding StatusMessage}" />
|
||||
<TextBlock Text="{Binding FileName}"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
|
||||
<DataGridTextColumn x:DataType="vm:DecryptFileViewModel"
|
||||
Header="{loc:Localize Column_OutputPath}"
|
||||
Binding="{Binding OutputPath}"
|
||||
Width="280" />
|
||||
|
||||
<DataGridTemplateColumn x:DataType="vm:DecryptFileViewModel"
|
||||
Header="{loc:Localize Column_Status}"
|
||||
Width="220">
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate x:DataType="vm:DecryptFileViewModel">
|
||||
<!-- Status stays a short label; the full reason goes to the
|
||||
tooltip and to the detail dialog, because the missing
|
||||
database message is several hundred characters long. -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="6"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip.Tip="{Binding ErrorDetail}">
|
||||
<TextBlock Text="{Binding StatusMessage}"
|
||||
VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<Button Content="{Binding ViewDetailLabel}"
|
||||
Command="{Binding ShowDetailCommand}"
|
||||
IsVisible="{Binding HasErrorDetail}"
|
||||
Classes="icon"
|
||||
Padding="4,0"
|
||||
FontSize="11"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</Border>
|
||||
|
||||
<!-- Empty State Overlay -->
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="0,0,8,8"
|
||||
Margin="0,36,0,0"
|
||||
IsVisible="{Binding HasNoFiles}"
|
||||
IsHitTestVisible="False">
|
||||
<StackPanel VerticalAlignment="Center"
|
||||
HorizontalAlignment="Center"
|
||||
Spacing="16">
|
||||
<Border Background="{DynamicResource ContentAreaBrush}"
|
||||
CornerRadius="4"
|
||||
Width="50" Height="40"
|
||||
HorizontalAlignment="Center">
|
||||
<PathIcon Data="{StaticResource MusicNoteIcon}"
|
||||
Width="24" Height="24"
|
||||
Opacity="0.3" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding DecryptEmptyState}"
|
||||
Opacity="0.4"
|
||||
FontSize="13"
|
||||
HorizontalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Panel>
|
||||
|
||||
<!-- Card 3: Status Bar -->
|
||||
<Border Grid.Row="4"
|
||||
Background="{DynamicResource CardBackgroundBrush}"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24,12"
|
||||
Margin="0,16,0,0"
|
||||
CornerRadius="8">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal" Spacing="4">
|
||||
<TextBlock Text="{Binding CommonTotal}" FontSize="13" FontWeight="Medium" />
|
||||
<TextBlock Text="{Binding TotalCount}" FontWeight="Bold" FontSize="13" />
|
||||
<TextBlock Text="{Binding CommonFiles}" FontSize="13" Opacity="0.7" />
|
||||
</StackPanel>
|
||||
|
||||
<Panel Grid.Column="1" />
|
||||
|
||||
<StackPanel Grid.Column="2" Orientation="Horizontal" Spacing="6" Margin="0,0,24,0">
|
||||
<Border Width="4" Height="16" CornerRadius="2"
|
||||
Background="{DynamicResource SuccessColorBrush}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding CommonSuccess}" FontSize="13" />
|
||||
<TextBlock Text="{Binding CompletedCount}"
|
||||
FontWeight="Bold" FontSize="13"
|
||||
Foreground="{DynamicResource SuccessColorBrush}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Column="3" Orientation="Horizontal" Spacing="6">
|
||||
<Border Width="4" Height="16" CornerRadius="2"
|
||||
Background="{DynamicResource ErrorColorBrush}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Text="{Binding CommonFailed}" FontSize="13" />
|
||||
<TextBlock Text="{Binding FailedCount}"
|
||||
FontWeight="Bold" FontSize="13"
|
||||
Foreground="{DynamicResource ErrorColorBrush}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
</UserControl>
|
||||
@@ -0,0 +1,17 @@
|
||||
using Avalonia.Controls;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Views.Pages;
|
||||
|
||||
/// <summary>
|
||||
/// 音乐解密页面。
|
||||
/// </summary>
|
||||
public partial class DecryptPage : UserControl
|
||||
{
|
||||
/// <summary>
|
||||
/// 初始化音乐解密页面。
|
||||
/// </summary>
|
||||
public DecryptPage()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
@@ -17,38 +17,77 @@
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Quick Actions -->
|
||||
<!-- Quick Actions: every card navigates for real -->
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="8"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24">
|
||||
<StackPanel Spacing="16">
|
||||
<TextBlock Text="Quick Actions"
|
||||
<TextBlock Text="{Binding QuickActionsTitle}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<WrapPanel Orientation="Horizontal">
|
||||
<Button Margin="0,0,16,16"
|
||||
Padding="24,16"
|
||||
CornerRadius="8">
|
||||
CornerRadius="8"
|
||||
MinWidth="240"
|
||||
Command="{Binding OpenLyricsCommand}">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Download Lyrics"
|
||||
FontWeight="SemiBold" />
|
||||
<TextBlock Text="Batch download lyrics for your music"
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<PathIcon Data="{StaticResource MusicNoteIcon}"
|
||||
Width="16" Height="16"
|
||||
Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding LyricsCardTitle}"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding LyricsCardDescription}"
|
||||
FontSize="12"
|
||||
Opacity="0.7" />
|
||||
Opacity="0.7"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Margin="0,0,16,16"
|
||||
Padding="24,16"
|
||||
CornerRadius="8">
|
||||
CornerRadius="8"
|
||||
MinWidth="240"
|
||||
Command="{Binding OpenAlbumCommand}">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="Download Album Covers"
|
||||
FontWeight="SemiBold" />
|
||||
<TextBlock Text="Get album artwork for your collection"
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<PathIcon Data="{StaticResource ImageIcon}"
|
||||
Width="16" Height="16"
|
||||
Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding AlbumCardTitle}"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding AlbumCardDescription}"
|
||||
FontSize="12"
|
||||
Opacity="0.7" />
|
||||
Opacity="0.7"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button Margin="0,0,16,16"
|
||||
Padding="24,16"
|
||||
CornerRadius="8"
|
||||
MinWidth="240"
|
||||
Command="{Binding OpenDecryptCommand}">
|
||||
<StackPanel Spacing="8">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<PathIcon Data="{StaticResource LockIcon}"
|
||||
Width="16" Height="16"
|
||||
Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding DecryptCardTitle}"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding DecryptCardDescription}"
|
||||
FontSize="12"
|
||||
Opacity="0.7"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</WrapPanel>
|
||||
@@ -61,36 +100,35 @@
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24">
|
||||
<StackPanel Spacing="16">
|
||||
<TextBlock Text="Features"
|
||||
<TextBlock Text="{Binding FeaturesTitle}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<ItemsControl>
|
||||
<ItemsControl.Items>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="Multiple lyrics sources: NetEase, QQ Music, KuGou, KuWo" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="Batch processing with parallel downloads" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="Support for translation lyrics" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="Cross-platform: Windows, macOS, Linux" />
|
||||
</StackPanel>
|
||||
</ItemsControl.Items>
|
||||
</ItemsControl>
|
||||
<StackPanel Spacing="8">
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding FeatureFormats}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding FeatureParallel}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding FeatureEncodings}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8" Margin="0,4">
|
||||
<TextBlock Text="*" FontWeight="Bold" Foreground="{DynamicResource AppAccentBrush}" />
|
||||
<TextBlock Text="{Binding FeatureCrossPlatform}" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Version Info -->
|
||||
<TextBlock Opacity="0.5" FontSize="12">
|
||||
<Run Text="Version " />
|
||||
<Run Text="{Binding VersionLabel}" />
|
||||
<Run Text=" " />
|
||||
<Run Text="{Binding Version}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
|
||||
@@ -24,71 +24,182 @@
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24,20"
|
||||
Margin="0,0,0,16">
|
||||
<Grid RowDefinitions="Auto,Auto,Auto,Auto" ColumnDefinitions="Auto,*,Auto"
|
||||
>
|
||||
<!-- Row 0: Folder Selection -->
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="{Binding LyricsFolderLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Row="0" Grid.Column="1"
|
||||
Text="{Binding SelectedFolderPath}"
|
||||
Watermark="{Binding LyricsSelectFolder}"
|
||||
IsReadOnly="True"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Row="0" Grid.Column="2"
|
||||
Content="{Binding LyricsBrowse}"
|
||||
Command="{Binding SelectFolderCommand}"
|
||||
MinWidth="80"
|
||||
HorizontalAlignment="Stretch" />
|
||||
<StackPanel Spacing="0">
|
||||
|
||||
<!-- Separator -->
|
||||
<Border Grid.Row="1" Grid.ColumnSpan="3"
|
||||
Height="1"
|
||||
<!-- Source selector -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsScannerLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<ComboBox Grid.Column="1"
|
||||
ItemsSource="{Binding ScannerNames}"
|
||||
SelectedIndex="{Binding SelectedScannerIndex}"
|
||||
IsEnabled="{Binding CanEditInputs}"
|
||||
MinWidth="200"
|
||||
HorizontalAlignment="Left"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding LyricsScan}"
|
||||
Command="{Binding StartScanCommand}"
|
||||
IsEnabled="{Binding CanScan}"
|
||||
MinWidth="88" />
|
||||
</Grid>
|
||||
|
||||
<Border Height="1"
|
||||
Background="{DynamicResource SeparatorBrush}"
|
||||
Opacity="0.5"
|
||||
Margin="0,16" />
|
||||
|
||||
<!-- Row 2: Parallel Count + Download Button -->
|
||||
<TextBlock Grid.Row="2" Grid.Column="0"
|
||||
Text="{Binding LyricsParallel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<NumericUpDown Grid.Row="2" Grid.Column="1"
|
||||
Value="{Binding ParallelCount}"
|
||||
Minimum="1"
|
||||
Maximum="32"
|
||||
Increment="1"
|
||||
Width="100"
|
||||
FormatString="0"
|
||||
HorizontalAlignment="Left"
|
||||
<!-- Input row: switches with the selected scanner -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto" IsVisible="{Binding IsLocalScanner}">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsFolderLabel}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="16,0" />
|
||||
<StackPanel Grid.Row="2" Grid.Column="2"
|
||||
Orientation="Horizontal" Spacing="8">
|
||||
<Button Command="{Binding StartDownloadCommand}"
|
||||
IsVisible="{Binding !IsDownloading}"
|
||||
IsEnabled="{Binding CanStartDownload}"
|
||||
Classes="accent"
|
||||
MinWidth="120">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<PathIcon Data="{StaticResource DownloadIcon}"
|
||||
Width="14" Height="14" />
|
||||
<TextBlock Text="{Binding LyricsStartDownload}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Command="{Binding CancelDownloadCommand}"
|
||||
Content="{Binding LyricsStopDownload}"
|
||||
IsVisible="{Binding IsDownloading}"
|
||||
MinWidth="100" />
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SelectedFolderPath}"
|
||||
Watermark="{Binding LyricsSelectFolder}"
|
||||
IsReadOnly="True"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding LyricsBrowse}"
|
||||
Command="{Binding SelectFolderCommand}"
|
||||
MinWidth="88"
|
||||
HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
|
||||
<Grid ColumnDefinitions="Auto,*,Auto" IsVisible="{Binding IsCsvScanner}">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsCsvLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SelectedCsvFilePath}"
|
||||
Watermark="{Binding LyricsCsvSelect}"
|
||||
IsReadOnly="True"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding LyricsCsvBrowse}"
|
||||
Command="{Binding SelectCsvFileCommand}"
|
||||
MinWidth="88"
|
||||
HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
|
||||
<StackPanel Spacing="8" IsVisible="{Binding IsNetEaseScanner}">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsSongListLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding SongListIds}"
|
||||
IsEnabled="{Binding CanEditInputs}"
|
||||
Watermark="{Binding LyricsSongListWatermark}"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Column="2"
|
||||
Classes="accent"
|
||||
Content="{Binding NetEaseSignIn}"
|
||||
Command="{Binding SignInNetEaseCommand}"
|
||||
ToolTip.Tip="{Binding NetEaseSignInHint}"
|
||||
IsVisible="{Binding !IsNetEaseLoggedIn}"
|
||||
MinWidth="88" />
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding NetEaseSignOut}"
|
||||
Command="{Binding SignOutNetEaseCommand}"
|
||||
ToolTip.Tip="{Binding NetEaseSignOutHint}"
|
||||
IsVisible="{Binding IsNetEaseLoggedIn}"
|
||||
MinWidth="88" />
|
||||
</Grid>
|
||||
|
||||
<!-- 显示当前网易云登录状态。 -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<PathIcon Grid.Column="0"
|
||||
Data="{StaticResource AccountIcon}"
|
||||
Width="13"
|
||||
Height="13"
|
||||
VerticalAlignment="Center"
|
||||
Opacity="0.55" />
|
||||
<TextBlock Grid.Column="1"
|
||||
Text="{Binding NetEaseAccountStatus}"
|
||||
Margin="8,0,0,0"
|
||||
FontSize="12"
|
||||
Opacity="0.6"
|
||||
TextWrapping="Wrap"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Row 3: Progress (spans all columns) -->
|
||||
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
|
||||
IsVisible="{Binding IsScanning}"
|
||||
<!-- Output directory (only meaningful for csv / netease, but harmless for local) -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto"
|
||||
Margin="0,12,0,0"
|
||||
IsVisible="{Binding !IsLocalScanner}">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsOutputLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding OutputDirectory}"
|
||||
Watermark="{Binding LyricsOutputSelect}"
|
||||
IsReadOnly="True"
|
||||
Margin="16,0" />
|
||||
<Button Grid.Column="2"
|
||||
Content="{Binding LyricsOutputBrowse}"
|
||||
Command="{Binding SelectOutputFolderCommand}"
|
||||
MinWidth="88"
|
||||
HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
|
||||
<Border Height="1"
|
||||
Background="{DynamicResource SeparatorBrush}"
|
||||
Opacity="0.5"
|
||||
Margin="0,16" />
|
||||
|
||||
<!-- Parallel count + download button -->
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding LyricsParallel}"
|
||||
VerticalAlignment="Center"
|
||||
FontSize="13"
|
||||
FontWeight="Medium" />
|
||||
<NumericUpDown Grid.Column="1"
|
||||
Value="{Binding ParallelCount}"
|
||||
Minimum="1"
|
||||
Maximum="32"
|
||||
Increment="1"
|
||||
Width="100"
|
||||
FormatString="0"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Margin="16,0" />
|
||||
<StackPanel Grid.Column="2"
|
||||
Orientation="Horizontal" Spacing="8">
|
||||
<Button Command="{Binding StartDownloadCommand}"
|
||||
IsVisible="{Binding !IsDownloading}"
|
||||
IsEnabled="{Binding CanStartDownload}"
|
||||
Classes="accent"
|
||||
MinWidth="132">
|
||||
<StackPanel Orientation="Horizontal" Spacing="6">
|
||||
<PathIcon Data="{StaticResource DownloadIcon}"
|
||||
Width="14" Height="14" />
|
||||
<TextBlock Text="{Binding LyricsStartDownload}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button Command="{Binding CancelDownloadCommand}"
|
||||
Content="{Binding LyricsStopDownload}"
|
||||
IsVisible="{Binding IsDownloading}"
|
||||
MinWidth="108" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- Scan progress -->
|
||||
<StackPanel IsVisible="{Binding IsScanning}"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<ProgressBar Value="{Binding ScanProgressPercentage}"
|
||||
Maximum="100" Height="6" />
|
||||
@@ -100,8 +211,9 @@
|
||||
<Run Text="{Binding ScanTotalCount}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Row="3" Grid.ColumnSpan="3"
|
||||
IsVisible="{Binding IsDownloading}"
|
||||
|
||||
<!-- Download progress -->
|
||||
<StackPanel IsVisible="{Binding IsDownloading}"
|
||||
Spacing="8" Margin="0,16,0,0">
|
||||
<ProgressBar Value="{Binding ProgressPercentage}"
|
||||
Maximum="100" Height="6" />
|
||||
@@ -111,7 +223,7 @@
|
||||
<Run Text="{Binding TotalCount}" />
|
||||
</TextBlock>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Card 2: File List with Empty State -->
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels"
|
||||
xmlns:loc="using:ZonyLrcTools.Desktop.Infrastructure.Localization"
|
||||
x:Class="ZonyLrcTools.Desktop.Views.Pages.SettingsPage"
|
||||
x:DataType="vm:SettingsViewModel">
|
||||
|
||||
@@ -64,6 +65,12 @@
|
||||
Minimum="1"
|
||||
Maximum="65535" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Text="{Binding SettingsProxyRestartHint}"
|
||||
FontSize="12"
|
||||
Opacity="0.55"
|
||||
TextWrapping="Wrap"
|
||||
IsVisible="{Binding IsProxyEnabled}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
@@ -73,26 +80,43 @@
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24">
|
||||
<StackPanel Spacing="16">
|
||||
<TextBlock Text="Lyrics"
|
||||
<TextBlock Text="{Binding SettingsLyricsSection}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<CheckBox Content="Enable translation lyrics"
|
||||
<CheckBox Content="{Binding SettingsEnableTranslation}"
|
||||
IsChecked="{Binding IsTranslationEnabled}" />
|
||||
|
||||
<CheckBox Content="One-line mode (original + translation on same line)"
|
||||
IsChecked="{Binding IsOneLineMode}" />
|
||||
<CheckBox Content="{Binding SettingsOneLineMode}"
|
||||
IsChecked="{Binding IsOneLineMode}"
|
||||
IsEnabled="{Binding IsTranslationEnabled}" />
|
||||
|
||||
<CheckBox Content="Skip existing lyrics files"
|
||||
<CheckBox Content="{Binding SettingsOnlyTranslation}"
|
||||
IsChecked="{Binding IsOnlyOutputTranslation}"
|
||||
IsEnabled="{Binding IsTranslationEnabled}" />
|
||||
|
||||
<CheckBox Content="{Binding SettingsSkipExisting}"
|
||||
IsChecked="{Binding SkipExistingLyrics}" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="16">
|
||||
<TextBlock Text="File Encoding:"
|
||||
VerticalAlignment="Center" />
|
||||
<ComboBox ItemsSource="{Binding AvailableEncodings}"
|
||||
<Grid ColumnDefinitions="Auto,180,Auto,180" RowDefinitions="Auto,Auto">
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="{Binding SettingsFileEncoding}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,12,0" />
|
||||
<ComboBox Grid.Row="0" Grid.Column="1"
|
||||
ItemsSource="{Binding AvailableEncodings}"
|
||||
SelectedItem="{Binding SelectedEncoding}"
|
||||
Width="150" />
|
||||
</StackPanel>
|
||||
HorizontalAlignment="Stretch" />
|
||||
|
||||
<TextBlock Grid.Row="0" Grid.Column="2"
|
||||
Text="{Binding SettingsLineBreak}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="24,0,12,0" />
|
||||
<ComboBox Grid.Row="0" Grid.Column="3"
|
||||
ItemsSource="{Binding LineBreakDisplayNames}"
|
||||
SelectedIndex="{Binding SelectedLineBreakIndex}"
|
||||
HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
@@ -102,9 +126,15 @@
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24">
|
||||
<StackPanel Spacing="16">
|
||||
<TextBlock Text="{Binding SettingsLyricsProvider}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold" />
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{Binding SettingsLyricsProvider}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold" />
|
||||
<TextBlock Text="{Binding SettingsProviderOrderHint}"
|
||||
FontSize="12"
|
||||
Opacity="0.55"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<ItemsControl ItemsSource="{Binding LyricsProviders}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
@@ -112,20 +142,35 @@
|
||||
<Border Background="{DynamicResource AppBackgroundBrush}"
|
||||
CornerRadius="4"
|
||||
Padding="12,8"
|
||||
Margin="0,4">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto">
|
||||
Margin="0,4"
|
||||
Opacity="{Binding RowOpacity}">
|
||||
<Grid ColumnDefinitions="Auto,28,*,Auto,Auto">
|
||||
<CheckBox Grid.Column="0"
|
||||
IsChecked="{Binding IsEnabled}"
|
||||
Margin="0,0,12,0" />
|
||||
<TextBlock Grid.Column="1"
|
||||
Text="{Binding PriorityLabel}"
|
||||
VerticalAlignment="Center"
|
||||
FontFamily="{DynamicResource NumericFontFamily}"
|
||||
Opacity="0.55" />
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Name}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="2"
|
||||
VerticalAlignment="Center"
|
||||
Opacity="0.5">
|
||||
<Run Text="Priority: " />
|
||||
<Run Text="{Binding Priority}" />
|
||||
</TextBlock>
|
||||
<Button Grid.Column="3"
|
||||
Command="{Binding MoveUpCommand}"
|
||||
IsEnabled="{Binding CanMoveUp}"
|
||||
Classes="icon"
|
||||
Margin="0,0,4,0"
|
||||
ToolTip.Tip="{loc:Localize Settings_MoveUp}">
|
||||
<PathIcon Data="{StaticResource ChevronUpIcon}" Width="12" Height="12" />
|
||||
</Button>
|
||||
<Button Grid.Column="4"
|
||||
Command="{Binding MoveDownCommand}"
|
||||
IsEnabled="{Binding CanMoveDown}"
|
||||
Classes="icon"
|
||||
ToolTip.Tip="{loc:Localize Settings_MoveDown}">
|
||||
<PathIcon Data="{StaticResource ChevronDownIcon}" Width="12" Height="12" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
@@ -134,11 +179,124 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Actions -->
|
||||
<StackPanel Orientation="Horizontal" Spacing="16" HorizontalAlignment="Right">
|
||||
<Button Content="{Binding SettingsReset}"
|
||||
Command="{Binding ResetToDefaultsCommand}" />
|
||||
</StackPanel>
|
||||
<!-- Advanced Settings (collapsed by default) -->
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="8"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24">
|
||||
<StackPanel Spacing="16">
|
||||
<ToggleSwitch IsChecked="{Binding IsAdvancedVisible}"
|
||||
Content="{Binding SettingsShowAdvanced}"
|
||||
OnContent="{Binding SettingsAdvancedSection}"
|
||||
OffContent="{Binding SettingsShowAdvanced}" />
|
||||
|
||||
<StackPanel Spacing="16" IsVisible="{Binding IsAdvancedVisible}">
|
||||
<Border Height="1" Background="{DynamicResource SeparatorBrush}" Opacity="0.5" />
|
||||
|
||||
<!-- Romanized output -->
|
||||
<CheckBox Content="{Binding SettingsRomanOutput}"
|
||||
IsChecked="{Binding IsRomanOutputEnabled}" />
|
||||
|
||||
<!-- Block word dictionary -->
|
||||
<TextBlock Text="{Binding SettingsBlockWordSection}"
|
||||
FontSize="15"
|
||||
FontWeight="Medium" />
|
||||
|
||||
<CheckBox Content="{Binding SettingsBlockWordEnable}"
|
||||
IsChecked="{Binding IsBlockWordEnabled}" />
|
||||
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="{Binding SettingsBlockWordPath}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,12,0" />
|
||||
<TextBox Grid.Column="1"
|
||||
Text="{Binding BlockWordFilePath}"
|
||||
IsEnabled="{Binding IsBlockWordEnabled}" />
|
||||
</Grid>
|
||||
|
||||
<!-- Tag providers -->
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Text="{Binding SettingsTagProvider}"
|
||||
FontSize="15"
|
||||
FontWeight="Medium" />
|
||||
<TextBlock Text="{Binding SettingsProviderOrderHint}"
|
||||
FontSize="12"
|
||||
Opacity="0.55"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<ItemsControl ItemsSource="{Binding TagProviders}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate x:DataType="vm:TagInfoProviderSettingViewModel">
|
||||
<Border Background="{DynamicResource AppBackgroundBrush}"
|
||||
CornerRadius="4"
|
||||
Padding="12,8"
|
||||
Margin="0,4"
|
||||
Opacity="{Binding RowOpacity}">
|
||||
<Grid ColumnDefinitions="Auto,28,*,Auto,Auto">
|
||||
<CheckBox Grid.Column="0"
|
||||
IsChecked="{Binding IsEnabled}"
|
||||
Margin="0,0,12,0" />
|
||||
<TextBlock Grid.Column="1"
|
||||
Text="{Binding PriorityLabel}"
|
||||
VerticalAlignment="Center"
|
||||
Opacity="0.55" />
|
||||
<TextBlock Grid.Column="2"
|
||||
Text="{Binding Name}"
|
||||
VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3"
|
||||
Command="{Binding MoveUpCommand}"
|
||||
IsEnabled="{Binding CanMoveUp}"
|
||||
Classes="icon"
|
||||
Margin="0,0,4,0"
|
||||
ToolTip.Tip="{loc:Localize Settings_MoveUp}">
|
||||
<PathIcon Data="{StaticResource ChevronUpIcon}" Width="12" Height="12" />
|
||||
</Button>
|
||||
<Button Grid.Column="4"
|
||||
Command="{Binding MoveDownCommand}"
|
||||
IsEnabled="{Binding CanMoveDown}"
|
||||
Classes="icon"
|
||||
ToolTip.Tip="{loc:Localize Settings_MoveDown}">
|
||||
<PathIcon Data="{StaticResource ChevronDownIcon}" Width="12" Height="12" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Actions + status -->
|
||||
<Border Background="{DynamicResource CardBackgroundBrush}"
|
||||
CornerRadius="8"
|
||||
BoxShadow="0 2 8 0 #0D000000"
|
||||
Padding="24,14">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding StorageHint}"
|
||||
FontSize="12"
|
||||
Opacity="0.55"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding SaveStatusText}"
|
||||
FontSize="12"
|
||||
Foreground="{DynamicResource SuccessColorBrush}"
|
||||
IsVisible="{Binding ShowSaveSuccess}" />
|
||||
<TextBlock Text="{Binding SaveStatusText}"
|
||||
FontSize="12"
|
||||
Foreground="{DynamicResource ErrorColorBrush}"
|
||||
IsVisible="{Binding ShowSaveFailure}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<Button Grid.Column="1"
|
||||
Content="{Binding SettingsReset}"
|
||||
Command="{Binding ResetToDefaultsCommand}"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" />
|
||||
<PackageReference Include="Avalonia.Controls.DataGrid" />
|
||||
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
|
||||
<PackageReference Include="Tmds.DBus.Protocol" />
|
||||
<!-- MVVM -->
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||
<!-- DI & Hosting -->
|
||||
@@ -30,6 +31,24 @@
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" />
|
||||
<!-- Localization -->
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" />
|
||||
<!-- 网易云扫码登录所需的二维码生成器 -->
|
||||
<PackageReference Include="QRCoder" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- 指定运行平台时默认裁剪,可通过 -p:PublishTrimmed=false 关闭。
|
||||
反射注入、序列化和无障碍访问所需程序集由 ILLink.Descriptors.xml 保留。 -->
|
||||
<PropertyGroup Condition="'$(RuntimeIdentifier)' != '' AND '$(PublishTrimmed)' == ''">
|
||||
<PublishTrimmed>true</PublishTrimmed>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(PublishTrimmed)' == 'true'">
|
||||
<TrimMode>partial</TrimMode>
|
||||
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||
<TrimmerSingleWarn>false</TrimmerSingleWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup Condition="'$(PublishTrimmed)' == 'true'">
|
||||
<TrimmerRootDescriptor Include="ILLink.Descriptors.xml" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common;
|
||||
using ZonyLrcTools.Common.Album;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Extensions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Lyrics;
|
||||
|
||||
namespace ZonyLrcTools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 下载结果、取消与文件保护的回归测试。
|
||||
/// </summary>
|
||||
public sealed class CoreDownloadRegressionTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
private readonly RecordingLogger _logger = new();
|
||||
|
||||
/// <summary>
|
||||
/// 创建独立的输出目录。
|
||||
/// </summary>
|
||||
public CoreDownloadRegressionTests()
|
||||
{
|
||||
Directory.CreateDirectory(_directory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首个来源无歌词时继续查找后续来源。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_EmptyProviderFallsBackAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = CreateLyricsDownloader(
|
||||
new TestLyricsProvider("empty", () => new LyricsItemCollection(new GlobalLyricsConfigOptions())),
|
||||
new TestLyricsProvider("available", CreateLyrics));
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.Contains("可用歌词", await File.ReadAllTextAsync(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 来源失败后仍可使用后续来源。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_FailedProviderFallsBackAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var failure = new InvalidOperationException("来源不可用");
|
||||
var downloader = CreateLyricsDownloader(
|
||||
new TestLyricsProvider("failed", () => throw failure),
|
||||
new TestLyricsProvider("available", CreateLyrics));
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.Contains("可用歌词", await File.ReadAllTextAsync(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
Assert.Contains(failure, _logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取消发生在来源返回之前时保留原歌词。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_CancellationPreservesExistingFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var lyricsPath = Path.ChangeExtension(info.FilePath, ".lrc");
|
||||
await File.WriteAllTextAsync(lyricsPath, "原歌词");
|
||||
var downloader = CreateLyricsDownloader(new TestLyricsProvider("cancel", () =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return CreateLyrics();
|
||||
}));
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([info], cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.Equal("原歌词", await File.ReadAllTextAsync(lyricsPath));
|
||||
Assert.Empty(Directory.GetFiles(_directory, "*.tmp"));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 没有启用来源时不能将歌曲标记为纯音乐。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Lyrics_NoProvidersReportsFailureAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = CreateLyricsDownloader();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => downloader.DownloadAsync([info], callback: _ =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return Task.CompletedTask;
|
||||
}, cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.False(info.IsPruneMusic);
|
||||
Assert.False(File.Exists(Path.ChangeExtension(info.FilePath, ".lrc")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已有封面不依赖网络结果,也不会被覆盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_ExistingFileIsSuccessfulWithoutProviderRequestAsync()
|
||||
{
|
||||
var info = CreateMusicInfo();
|
||||
var albumPath = Path.ChangeExtension(info.FilePath, ".png");
|
||||
await File.WriteAllBytesAsync(albumPath, [1, 2, 3]);
|
||||
var downloader = new AlbumDownloader(
|
||||
[new TestAlbumProvider(() => throw new InvalidOperationException("不应请求来源"))], _logger);
|
||||
|
||||
await downloader.DownloadAsync([info]);
|
||||
|
||||
Assert.True(info.IsSuccessful);
|
||||
Assert.Equal(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(albumPath));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 来源返回时已取消则不创建封面。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_CancellationDoesNotPublishFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var info = CreateMusicInfo();
|
||||
var downloader = new AlbumDownloader([new TestAlbumProvider(() =>
|
||||
{
|
||||
cancellation.Cancel();
|
||||
return [1, 2, 3];
|
||||
})], _logger);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([info], cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(info.IsSuccessful);
|
||||
Assert.Empty(Directory.GetFiles(_directory));
|
||||
Assert.Empty(_logger.Exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 无来源时仍应遵守预先取消的令牌。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Album_NoProvidersHonorsCancellationAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
var downloader = new AlbumDownloader([], _logger);
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
downloader.DownloadAsync([CreateMusicInfo()], cancellationToken: cancellation.Token));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 日志辅助方法保留异常对象且不重新抛出业务错误。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Logger_PreservesErrorCodeException()
|
||||
{
|
||||
var exception = new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding);
|
||||
|
||||
_logger.LogWarningInfo(exception);
|
||||
|
||||
Assert.Same(exception, Assert.Single(_logger.Exceptions));
|
||||
}
|
||||
|
||||
private MusicInfo CreateMusicInfo() => new(Path.Combine(_directory, "歌曲.mp3"), "歌曲", "歌手");
|
||||
|
||||
private static LyricsItemCollection CreateLyrics() => new(new GlobalLyricsConfigOptions())
|
||||
{
|
||||
new(0, 1, "可用歌词")
|
||||
};
|
||||
|
||||
private LyricsDownloader CreateLyricsDownloader(params TestLyricsProvider[] providers)
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions(),
|
||||
Plugin = providers.Select((provider, index) => new LyricsProviderOptions
|
||||
{
|
||||
Name = provider.DownloaderName,
|
||||
Priority = index
|
||||
}).ToArray()
|
||||
}
|
||||
}
|
||||
};
|
||||
return new LyricsDownloader(providers, Options.Create(options), _logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除测试生成的输出。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private sealed class TestLyricsProvider(string name, Func<LyricsItemCollection> download) : ILyricsProvider
|
||||
{
|
||||
public string DownloaderName => name;
|
||||
|
||||
public ValueTask<LyricsItemCollection> DownloadAsync(string songName, string artist, long? duration = null)
|
||||
=> ValueTask.FromResult(download());
|
||||
}
|
||||
|
||||
private sealed class TestAlbumProvider(Func<byte[]> download) : IAlbumProvider
|
||||
{
|
||||
public string DownloaderName => InternalAlbumProviderNames.NetEase;
|
||||
|
||||
public ValueTask<byte[]> DownloadAsync(string songName, string artist) => ValueTask.FromResult(download());
|
||||
}
|
||||
|
||||
private sealed class RecordingLogger : IWarpLogger
|
||||
{
|
||||
public List<Exception> Exceptions { get; } = [];
|
||||
|
||||
public Task DebugAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task InfoAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task WarnAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
public Task ErrorAsync(string message, Exception? exception = null) => RecordAsync(exception);
|
||||
|
||||
private Task RecordAsync(Exception? exception)
|
||||
{
|
||||
if (exception != null)
|
||||
{
|
||||
Exceptions.Add(exception);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 扫码登录对话框的状态与关闭行为测试。
|
||||
/// </summary>
|
||||
public class DesktopInteractionQrCodeLoginTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 重复收到窗口关闭通知时只取消一次登录。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NotifyClosed_CancelsLoginOnlyOnce()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var cancellationCount = 0;
|
||||
viewModel.Cancelled += (_, _) => cancellationCount++;
|
||||
|
||||
viewModel.NotifyClosed();
|
||||
viewModel.NotifyClosed();
|
||||
|
||||
Assert.Equal(1, cancellationCount);
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 登录成功导致的窗口关闭不应触发取消。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Complete_ClosesDialogWithoutCancellingLogin()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var cancellationCount = 0;
|
||||
var closeRequestCount = 0;
|
||||
viewModel.Cancelled += (_, _) => cancellationCount++;
|
||||
viewModel.CloseRequested += (_, _) =>
|
||||
{
|
||||
closeRequestCount++;
|
||||
viewModel.NotifyClosed();
|
||||
};
|
||||
|
||||
viewModel.Complete();
|
||||
|
||||
Assert.True(viewModel.IsCompleted);
|
||||
Assert.Equal(1, closeRequestCount);
|
||||
Assert.Equal(0, cancellationCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已关闭的窗口不再接受迟到的登录结果。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NotifyClosed_IgnoresLateLoginCallbacks()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
var statusBeforeClosing = viewModel.StatusText;
|
||||
var closeRequestCount = 0;
|
||||
viewModel.CloseRequested += (_, _) => closeRequestCount++;
|
||||
viewModel.NotifyClosed();
|
||||
|
||||
viewModel.SetState(NetEaseLoginState.Succeeded);
|
||||
viewModel.SetError("迟到的网络错误");
|
||||
viewModel.Complete();
|
||||
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
Assert.Equal(statusBeforeClosing, viewModel.StatusText);
|
||||
Assert.Equal(0, closeRequestCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 二维码过期后不应继续显示等待扫码。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SetState_ExpiredStopsShowingWaitingStatus()
|
||||
{
|
||||
var viewModel = new QrCodeLoginViewModel();
|
||||
viewModel.SetState(NetEaseLoginState.Waiting);
|
||||
var waitingStatus = viewModel.StatusText;
|
||||
|
||||
viewModel.SetState(NetEaseLoginState.Expired);
|
||||
|
||||
Assert.NotEqual(waitingStatus, viewModel.StatusText);
|
||||
Assert.False(viewModel.IsCompleted);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using YamlDotNet.RepresentationModel;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure;
|
||||
|
||||
/// <summary>设置文件无损修改的回归测试。</summary>
|
||||
public sealed class DesktopSettingsPersistenceTests
|
||||
{
|
||||
/// <summary>会话与数据库路径使用生成的 JSON 元数据往返,敏感会话文件限制权限。</summary>
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task RoundTripsStateUsingGeneratedMetadataAsync(bool isSession)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
var path = Path.Combine(directory, "state.json");
|
||||
try
|
||||
{
|
||||
var assembly = typeof(NetEaseSession).Assembly;
|
||||
var contextType = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateJsonContext")!;
|
||||
var context = (JsonSerializerContext)contextType.GetProperty("Default")!.GetValue(null)!;
|
||||
var value = isSession
|
||||
? (object)new NetEaseSession { Cookie = "test-cookie", CsrfToken = "test-token" }
|
||||
: new KugouDatabaseSetting { DatabasePath = "/music/My Database.db" };
|
||||
var typeInfo = context.GetTypeInfo(value.GetType())!;
|
||||
var writer = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateFile")!;
|
||||
var method = writer.GetMethod("WriteAsync", BindingFlags.Static | BindingFlags.NonPublic)!
|
||||
.MakeGenericMethod(value.GetType());
|
||||
await (Task)method.Invoke(null, new object[]
|
||||
{
|
||||
path, value, typeInfo, isSession, CancellationToken.None
|
||||
})!;
|
||||
|
||||
var loaded = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path), typeInfo);
|
||||
if (isSession)
|
||||
{
|
||||
var session = loaded.ShouldBeOfType<NetEaseSession>();
|
||||
session.Cookie.ShouldBe("test-cookie");
|
||||
session.CsrfToken.ShouldBe("test-token");
|
||||
}
|
||||
else
|
||||
{
|
||||
loaded.ShouldBeOfType<KugouDatabaseSetting>().DatabasePath.ShouldBe("/music/My Database.db");
|
||||
}
|
||||
if (isSession && !OperatingSystem.IsWindows())
|
||||
{
|
||||
File.GetUnixFileMode(path).ShouldBe(UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
Directory.GetFiles(directory, "*.tmp").ShouldBeEmpty();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>更改其他设置不能覆盖手工配置的换行符。</summary>
|
||||
[Fact]
|
||||
public void KeepsCustomLineBreakWhenChangingProxy()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions { LineBreak = string.Empty, FileEncoding = "ascii" },
|
||||
Plugin = Array.Empty<LyricsProviderOptions>()
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
viewModel.IsProxyEnabled = true;
|
||||
options.Provider.Lyric.Config.LineBreak.ShouldBe(string.Empty);
|
||||
viewModel.AvailableEncodings.ShouldContain("ascii");
|
||||
}
|
||||
|
||||
/// <summary>恢复默认值同时恢复下载器顺序。</summary>
|
||||
[Fact]
|
||||
public async Task ResetRestoresProviderOrderAsync()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions(),
|
||||
Plugin = new[]
|
||||
{
|
||||
new LyricsProviderOptions { Name = "QQ", Priority = 1 },
|
||||
new LyricsProviderOptions { Name = "NetEase", Priority = -1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
await viewModel.ResetToDefaultsCommand.ExecuteAsync(null);
|
||||
viewModel.LyricsProviders[0].Name.ShouldBe("NetEase");
|
||||
viewModel.LyricsProviders[0].Priority.ShouldBe(1);
|
||||
viewModel.LyricsProviders[0].IsEnabled.ShouldBeTrue();
|
||||
viewModel.ProxyPort.ShouldBe(4780);
|
||||
}
|
||||
|
||||
private sealed class MemorySettingsStore(GlobalOptions options) : ISettingsStore
|
||||
{
|
||||
public GlobalOptions Options { get; } = options;
|
||||
public string ConfigFilePath => "unused.yaml";
|
||||
public Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(SettingsSaveResult.Success(ConfigFilePath));
|
||||
}
|
||||
|
||||
/// <summary>合法的 YAML 写法不应导致未知字段和注释丢失。</summary>
|
||||
[Theory]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost, port: 80}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nprovider:\n tag:\n blockWord:\n filePath: My Words.json # dictionary\ncustom: keep\n", "provider.tag.blockWord.filePath", "New Words.json")]
|
||||
[InlineData("# keep\nnetworkOptions:\n isEnable: false\n ip: localhost\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {ip: localhost,}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
public async Task PatchesValidYamlWithoutDiscardingUnmanagedValuesAsync(string yaml, string key, string value)
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(path, yaml);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
var result = await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { [key] = value }, CancellationToken.None
|
||||
})!;
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.ShouldContain("# keep");
|
||||
var stream = new YamlStream();
|
||||
stream.Load(new StringReader(result!));
|
||||
var mapping = (YamlMappingNode)stream.Documents[0].RootNode;
|
||||
((YamlScalarNode)mapping.Children[new YamlScalarNode("custom")]).Value.ShouldBe("keep");
|
||||
var node = (YamlNode)mapping;
|
||||
foreach (var part in key.Split('.'))
|
||||
{
|
||||
node = ((YamlMappingNode)node).Children[new YamlScalarNode(part)];
|
||||
}
|
||||
((YamlScalarNode)node).Value.ShouldBe(value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>无效文件必须保留,不能用内存配置覆盖。</summary>
|
||||
[Fact]
|
||||
public async Task RefusesMalformedYamlAsync()
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
const string original = "networkOptions: [broken\n# keep";
|
||||
await File.WriteAllTextAsync(path, original);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
await Should.ThrowAsync<Exception>(async () => await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { ["networkOptions.port"] = "8080" }, CancellationToken.None
|
||||
})!);
|
||||
(await File.ReadAllTextAsync(path)).ShouldBe(original);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用合成加密 SQLite 数据验证密钥读取,不依赖真实酷狗数据库。
|
||||
/// </summary>
|
||||
public sealed class KggDatabaseRegressionTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-db-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 通过 SQLite 查询完整的合成加密数据库,并保持原文件不变。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ReadEncryptionKeys_ReadsEncryptedDatabaseWithoutChangingSource()
|
||||
{
|
||||
var path = CreateEncryptedDatabase("keys;test.db");
|
||||
var original = File.ReadAllBytes(path);
|
||||
|
||||
var keys = KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason);
|
||||
|
||||
Assert.Null(failureReason);
|
||||
Assert.Equal("synthetic-ekey", keys["audio-hash"]);
|
||||
Assert.Equal(original, File.ReadAllBytes(path));
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 区分大小写的文件系统上,切换路径大小写必须重新加载数据库。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SetDatabasePath_ReloadsDistinctCaseSensitivePath()
|
||||
{
|
||||
var lowerPath = Path.Combine(_directory, "keys.db");
|
||||
var upperPath = Path.Combine(_directory, "KEYS.db");
|
||||
File.WriteAllText(lowerPath, "invalid database");
|
||||
if (File.Exists(upperPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CreateEncryptedDatabase("KEYS.db");
|
||||
var provider = new KugouKeyProvider();
|
||||
provider.SetDatabasePath(lowerPath);
|
||||
Assert.False(provider.Probe().IsAvailable);
|
||||
|
||||
provider.SetDatabasePath(upperPath);
|
||||
|
||||
Assert.True(provider.Probe().IsAvailable);
|
||||
Assert.Equal("synthetic-ekey", provider.FindKey("audio-hash"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateEncryptedDatabase(string name)
|
||||
{
|
||||
var path = Path.Combine(_directory, name);
|
||||
var connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString();
|
||||
using (var connection = new SqliteConnection(connectionString))
|
||||
{
|
||||
connection.Open();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA page_size=1024; CREATE TABLE ShareFileItems (EncryptionKeyId TEXT, EncryptionKey TEXT);"
|
||||
+ "INSERT INTO ShareFileItems VALUES ('audio-hash', 'synthetic-ekey');";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
using var aes = Aes.Create();
|
||||
var derivation = new byte[24];
|
||||
for (var page = 1; page <= bytes.Length / 1024; page++)
|
||||
{
|
||||
Convert.FromHexString("1D613145B247BF7F3D189672144FE4BF").CopyTo(derivation, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(16), (uint)page);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(20), 0x546C4173);
|
||||
aes.Key = MD5.HashData(derivation);
|
||||
var value = (uint)page + 1;
|
||||
for (var index = 0; index < 16; index += 4)
|
||||
{
|
||||
value = unchecked(0x9EF4 * value - 0x7FFFFF07 * (value / 0xCE26));
|
||||
if ((value & 0x80000000) != 0)
|
||||
{
|
||||
value = unchecked(value + 0x7FFFFF07);
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(index), value);
|
||||
}
|
||||
|
||||
var iv = MD5.HashData(derivation.AsSpan(0, 16));
|
||||
var offset = (page - 1) * 1024;
|
||||
if (page == 1)
|
||||
{
|
||||
var header = bytes.AsSpan(16, 8).ToArray();
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(16, 1008), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, 16);
|
||||
encrypted.AsSpan(0, 8).CopyTo(bytes.AsSpan(8));
|
||||
header.CopyTo(bytes, 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(offset, 1024), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, offset);
|
||||
}
|
||||
}
|
||||
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用独立合成数据验证 KGG 解密边界,不代表真实客户端样本。
|
||||
/// </summary>
|
||||
public sealed class KggRegressionTests : IDisposable
|
||||
{
|
||||
private const string Ekey = "AQIDBAUGBwg0ENpQsPOCXXtClrT99x6WMpfYT1U/+p8=";
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 无填充 Base64 的末组三个字符不能丢掉第二个字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_UnpaddedEkey_PreservesEveryKeyByte()
|
||||
{
|
||||
var result = EkeyDecoder.Decode(Ekey.TrimEnd('='), out var invalidCount);
|
||||
|
||||
Assert.Equal(Enumerable.Range(1, 16).Select(value => (byte)value), result);
|
||||
Assert.Equal(0, invalidCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 填充之后还有数据的 Base64 是损坏密钥,不能静默忽略。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_RejectsDataAfterPadding()
|
||||
{
|
||||
Assert.Empty(EkeyDecoder.Decode(Ekey + "AAAA"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// QMC 查表算法使用相同位移量左右移位,不是循环移位。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void MapCipher_UsesReferenceMask()
|
||||
{
|
||||
var cipher = Qmc2Cipher.Create([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
var data = new byte[8];
|
||||
|
||||
cipher!.Decrypt(data, 0);
|
||||
|
||||
Assert.Equal(new byte[] { 29, 65, 192, 65, 29, 65, 192, 65 }, data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合成密文必须还原为预先确定的音频字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_DecryptsSyntheticFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("fLaCtest-payload"u8.ToArray(), File.ReadAllBytes(result.OutputFilePath!));
|
||||
Assert.Single(Directory.GetFiles(_directory, "*.flac"));
|
||||
Assert.Empty(Directory.GetFiles(_directory, "*.part"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同名文件不论长度是否相同,都不能覆盖或冒充本次成功结果。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(16)]
|
||||
[InlineData(3)]
|
||||
public async Task ConvertAsync_PreservesExistingOutput(int length)
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var output = Path.ChangeExtension(input, ".flac");
|
||||
var original = Enumerable.Repeat((byte)0x42, length).ToArray();
|
||||
File.WriteAllBytes(output, original);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(original, File.ReadAllBytes(output));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 旧版 KGM 与 KGG 魔数相同,不能将旧格式误送到 KGG 解密器。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(2u)]
|
||||
[InlineData(3u)]
|
||||
public void IsKggFile_DoesNotCaptureLegacyKgm(uint version)
|
||||
{
|
||||
var path = CreateKgg();
|
||||
var data = File.ReadAllBytes(path);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), version);
|
||||
File.WriteAllBytes(path, data);
|
||||
|
||||
Assert.False(KggMusicDecryptor.IsKggFile(path));
|
||||
Assert.False(new KugouKeyProvider().IsKggFile(path));
|
||||
Assert.Null(new KugouKeyProvider().ReadAudioHash(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不能覆盖另一个任务或程序的临时文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_PreservesUnownedPartialFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var partialPath = Path.ChangeExtension(input, ".flac") + ".part";
|
||||
File.WriteAllText(partialPath, "other conversion");
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("other conversion", File.ReadAllText(partialPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 音频偏移不能指向头部或文件末尾之外。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(0u)]
|
||||
[InlineData(1023u)]
|
||||
[InlineData(uint.MaxValue)]
|
||||
public async Task ConvertAsync_RejectsInvalidAudioOffset(uint offset)
|
||||
{
|
||||
var input = CreateKgg(offset);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 损坏的音频头不能默认为 MP3 并报告成功。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_RejectsUnknownAudioHeader()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var bytes = File.ReadAllBytes(input);
|
||||
bytes[1024] ^= 0xFF;
|
||||
File.WriteAllBytes(input, bytes);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找密钥期间取消后,不应继续发布输出文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_CancellationDoesNotPublishOutput()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
KggMusicDecryptor.ConvertAsync(input, new KeyProvider(cancellation.Cancel), cancellation.Token));
|
||||
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateKgg(uint offset = 1024)
|
||||
{
|
||||
var encryptedAudio = Convert.FromHexString("59CEA1024B24B3F612F2A138532EA1E6");
|
||||
var data = new byte[1024 + encryptedAudio.Length];
|
||||
Convert.FromHexString("7CD532EB86027F4BA8AFA68E0FFF9914").CopyTo(data, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x10), offset);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), 5);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x44), 32);
|
||||
"0123456789abcdef0123456789abcdef"u8.CopyTo(data.AsSpan(0x48));
|
||||
encryptedAudio.CopyTo(data, 1024);
|
||||
var path = Path.Combine(_directory, "song.kgg");
|
||||
File.WriteAllBytes(path, data);
|
||||
return path;
|
||||
}
|
||||
|
||||
private sealed class KeyProvider(Action? onFind = null) : IKugouKeyProvider
|
||||
{
|
||||
public string DatabasePath => "synthetic-key-source";
|
||||
public void SetDatabasePath(string? path) => throw new NotSupportedException();
|
||||
public KugouDatabaseInfo Probe() => new(true, DatabasePath, 1, "合成密钥");
|
||||
public void Invalidate() => throw new NotSupportedException();
|
||||
public bool IsKggFile(string filePath) => throw new NotSupportedException();
|
||||
public string? ReadAudioHash(string filePath) => throw new NotSupportedException();
|
||||
public string? FindKey(string audioHash)
|
||||
{
|
||||
onFind?.Invoke();
|
||||
return audioHash == "0123456789abcdef0123456789abcdef" ? Ekey : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.IO;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
@@ -7,16 +8,31 @@ using ZonyLrcTools.Common.MusicDecryption;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用真实 NCM 样本验证解密。
|
||||
/// </summary>
|
||||
public class NcmMusicDecryptorTests : TestBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 每次使用独立目录,避免历史输出影响解密结果。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertMusicAsync_Test()
|
||||
public async Task ConvertMusicAsync_DecryptsNcmAsync()
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(Directory.GetCurrentDirectory(), "MusicFiles", "Loren Gray - Queen.ncm");
|
||||
var directory = Directory.CreateTempSubdirectory("zony-ncm-tests-").FullName;
|
||||
try
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(directory, "Loren Gray - Queen.ncm");
|
||||
File.Copy(Path.Combine(AppContext.BaseDirectory, "MusicFiles", "Loren Gray - Queen.ncm"), ncmFilePath);
|
||||
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.Network;
|
||||
|
||||
/// <summary>
|
||||
/// 验证等待服务器响应时可以取消请求。
|
||||
/// </summary>
|
||||
public class WarpHttpCancellationTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 服务端未响应时,取消操作应及时结束请求。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task CancelsPendingRequestAsync(bool isPost)
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var endpoint = (IPEndPoint)listener.LocalEndpoint;
|
||||
var url = $"http://127.0.0.1:{endpoint.Port}/";
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var client = new DefaultWarpHttpClient(new LocalClientFactory());
|
||||
var request = SendRequestAsync(client, url, isPost, cancellation.Token);
|
||||
|
||||
using var connection = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
cancellation.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => request.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
}
|
||||
|
||||
private static async Task SendRequestAsync(IWarpHttpClient client, string url, bool isPost,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (isPost)
|
||||
{
|
||||
using var response = await client.PostReturnHttpResponseAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await client.GetAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LocalClientFactory : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name)
|
||||
{
|
||||
return new HttpClient(new SocketsHttpHandler { UseProxy = false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
|
||||
namespace ZonyLrcTools.Tests.MusicScanner;
|
||||
|
||||
/// <summary>
|
||||
/// CSV 换行符与取消行为的回归测试。
|
||||
/// </summary>
|
||||
public sealed class CsvNewlineRegressionTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 各平台导出的 CSV 均可读取并去除字段两端空白。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("\n")]
|
||||
[InlineData("\r\n")]
|
||||
[InlineData("\r")]
|
||||
public async Task Scan_AcceptsPlatformNewlinesAsync(string newline)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, "songs.csv");
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(path,
|
||||
$"Name,Artist{newline} Song One , Artist One {newline}{newline}Song Two,Artist Two{newline}",
|
||||
new UTF8Encoding(true));
|
||||
var scanner = new CsvFileMusicScanner();
|
||||
|
||||
var songs = await scanner.GetMusicInfoFromCsvFileAsync(path, directory, "{Artist} - {Name}.lrc");
|
||||
|
||||
Assert.Equal(2, songs.Count);
|
||||
Assert.Equal("Song One", songs[0].Name);
|
||||
Assert.Equal("Artist One", songs[0].Artist);
|
||||
Assert.Equal(Path.Combine(directory, "Artist Two - Song Two.lrc"), songs[1].FilePath);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 已取消的扫描不再访问文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Scan_PreCanceledDoesNotReadFileAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
cancellation.Cancel();
|
||||
var scanner = new CsvFileMusicScanner();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => scanner.GetMusicInfoFromCsvFileAsync(
|
||||
Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), "missing.csv"),
|
||||
Path.GetTempPath(), "{Name}.lrc", cancellation.Token));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#nullable enable
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.Infrastructure.Exceptions;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Common.MusicScanner;
|
||||
|
||||
namespace ZonyLrcTools.Tests.MusicScanner;
|
||||
|
||||
/// <summary>
|
||||
/// 网易云登录状态、并发与 HTTP 错误的回归测试。
|
||||
/// </summary>
|
||||
public sealed class NetEaseSessionRegressionTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 登录成功回调只能在 Cookie 保存后发出。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_SuccessCallbackSeesCommittedSessionAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : SuccessResponse()));
|
||||
var scanner = CreateScanner(handler);
|
||||
var observedLogin = false;
|
||||
|
||||
var success = await scanner.LoginAsync(_ => { }, state =>
|
||||
{
|
||||
if (state == NetEaseLoginState.Succeeded)
|
||||
{
|
||||
observedLogin = scanner.IsLoggedIn && scanner.CsrfToken == "csrf-value";
|
||||
}
|
||||
});
|
||||
|
||||
Assert.True(success);
|
||||
Assert.True(observedLogin);
|
||||
Assert.Contains("MUSIC_U=session-value", scanner.Cookie);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 并发登录复用已经建立的会话,不生成互相干扰的二维码。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ConcurrentRequestsUseOneQrSessionAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var keyRequests = 0;
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
Interlocked.Increment(ref keyRequests);
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
var first = scanner.LoginAsync(_ => { });
|
||||
var second = scanner.LoginAsync(_ => { });
|
||||
releaseKey.SetResult();
|
||||
var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.All(results, result => Assert.True(result));
|
||||
Assert.Equal(1, keyRequests);
|
||||
Assert.True(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清除登录后,迟到的扫码结果不能恢复已退出的会话。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ClearStateRejectsPendingResultAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { });
|
||||
|
||||
scanner.ClearLoginState();
|
||||
releaseKey.SetResult();
|
||||
var success = await login.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.False(success);
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
Assert.Empty(scanner.CsrfToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 恢复的会话不能被旧扫码请求覆盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_RestoreStateRejectsPendingResultAsync()
|
||||
{
|
||||
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (request, cancellationToken) =>
|
||||
{
|
||||
if (IsKeyRequest(request))
|
||||
{
|
||||
await releaseKey.Task.WaitAsync(cancellationToken);
|
||||
return KeyResponse();
|
||||
}
|
||||
|
||||
return SuccessResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { });
|
||||
|
||||
scanner.RestoreLoginState("MUSIC_U=restored", "restored-csrf");
|
||||
releaseKey.SetResult();
|
||||
await login.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
Assert.Equal("MUSIC_U=restored", scanner.Cookie);
|
||||
Assert.Equal("restored-csrf", scanner.CsrfToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// HTTP 失败不能被响应中的成功业务码掩盖。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_HttpFailureIsNotSuccessfulAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) =>
|
||||
{
|
||||
var response = IsKeyRequest(request) ? KeyResponse() : SuccessResponse();
|
||||
response.StatusCode = HttpStatusCode.ServiceUnavailable;
|
||||
return Task.FromResult(response);
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
await Assert.ThrowsAsync<HttpRequestException>(() => scanner.LoginAsync(_ => { }));
|
||||
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 非扫码状态业务码应失败,而不是永久等待扫码。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("{\"code\":500}")]
|
||||
[InlineData("{\"code\":803}")]
|
||||
public async Task Login_InvalidPollResponseFailsAsync(string body)
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : JsonResponse(body)));
|
||||
var scanner = CreateScanner(handler);
|
||||
|
||||
await Assert.ThrowsAsync<ErrorCodeException>(() =>
|
||||
scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token));
|
||||
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 二维码过期时结束登录并通知调用方。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_ExpiredQrReturnsFalseAsync()
|
||||
{
|
||||
using var handler = new TestHandler((request, _) => Task.FromResult(
|
||||
IsKeyRequest(request) ? KeyResponse() : JsonResponse("{\"code\":800}")));
|
||||
var scanner = CreateScanner(handler);
|
||||
var lastState = NetEaseLoginState.Waiting;
|
||||
|
||||
var success = await scanner.LoginAsync(_ => { }, state => lastState = state);
|
||||
|
||||
Assert.False(success);
|
||||
Assert.Equal(NetEaseLoginState.Expired, lastState);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭扫码窗口可以取消正在等待的 HTTP 请求。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_CancellationReachesHttpRequestAsync()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var handler = new TestHandler(async (_, cancellationToken) =>
|
||||
{
|
||||
started.SetResult();
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken);
|
||||
return KeyResponse();
|
||||
});
|
||||
var scanner = CreateScanner(handler);
|
||||
var login = scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token);
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
cancellation.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => login.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
Assert.False(scanner.IsLoggedIn);
|
||||
}
|
||||
|
||||
private static NetEaseMusicSongListMusicScanner CreateScanner(HttpMessageHandler handler)
|
||||
=> new(new DefaultWarpHttpClient(new TestClientFactory(handler)),
|
||||
NullLogger<NetEaseMusicSongListMusicScanner>.Instance);
|
||||
|
||||
private static bool IsKeyRequest(HttpRequestMessage request)
|
||||
=> request.RequestUri!.AbsolutePath.EndsWith("/unikey", StringComparison.Ordinal);
|
||||
|
||||
private static HttpResponseMessage KeyResponse() => JsonResponse("{\"code\":200,\"unikey\":\"qr-key\"}");
|
||||
|
||||
private static HttpResponseMessage SuccessResponse()
|
||||
{
|
||||
var response = JsonResponse("{\"code\":803}");
|
||||
response.Headers.TryAddWithoutValidation("Set-Cookie", new[]
|
||||
{
|
||||
"MUSIC_U=session-value; Path=/; Domain=music.163.com; HttpOnly",
|
||||
"__csrf=csrf-value; Path=/; Domain=music.163.com"
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
private static HttpResponseMessage JsonResponse(string body)
|
||||
=> new(HttpStatusCode.OK) { Content = new StringContent(body) };
|
||||
|
||||
private sealed class TestClientFactory(HttpMessageHandler handler) : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
|
||||
}
|
||||
|
||||
private sealed class TestHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> send)
|
||||
: HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
=> send(request, cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ZonyLrcTools.Cli\ZonyLrcTools.Cli.csproj" />
|
||||
<ProjectReference Include="..\..\src\ZonyLrcTools.Desktop\ZonyLrcTools.Desktop.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
+14
-4
@@ -1,7 +1,17 @@
|
||||
New Features: None
|
||||
Breaking Changes: None
|
||||
Enhancement: None
|
||||
New Features:
|
||||
- [#172] Complete the Avalonia desktop workflow and add KGG decryption using a matching KuGou database.
|
||||
|
||||
Breaking Changes:
|
||||
- Existing decrypted audio is preserved and reported as an output conflict instead of being overwritten or reported as newly decrypted.
|
||||
|
||||
Enhancement:
|
||||
- Align new C# code with Chinese XML documentation, UTC naming and cancellation-token conventions.
|
||||
- Preserve user YAML fields/comments and restrict Unix login-session permissions.
|
||||
- Include third-party notices in distributions and update Tmds.DBus.Protocol to the security-fixed 0.21.3 backport.
|
||||
|
||||
Fixed Bugs:
|
||||
|
||||
- [#167] Handle macOS code signing issues. (处理 macOS 代码签名问题。)
|
||||
- [#167] Handle macOS code signing issues. (处理 macOS 代码签名问题。)
|
||||
- [#172] Correct KGG/KGM detection, QMC2 map decoding, unpadded ekey decoding and concurrent output handling.
|
||||
- [#172] Keep decrypted key databases in memory; prevent canceled downloads from publishing partial files.
|
||||
- [#172] Fix QR login races, stale scan results, desktop task threading and trimmed session serialization.
|
||||
Reference in new issue
Block a user