fix(desktop): 修正解密、配置和任务生命周期问题

修复 KGG/KGM 识别、密钥解码及输出文件保护;改进配置无损保存、登录会话安全和取消处理。统一新增 C# 代码风格,补齐发布许可声明及文档,并增加针对性回归测试。
This commit is contained in:
real-zony committed 2026-11-09 18:13:55 -08:00
1 parent 7379571e2d
commit 8912a79168
64 files changed
+2747 -1142

No files matched your search

+9 -8
View File
@@ -61,15 +61,9 @@ jobs:
working-directory: ./src/ZonyLrcTools.Desktop working-directory: ./src/ZonyLrcTools.Desktop
run: | run: |
dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true -p:UseAppHost=true -p:DebugType=none --self-contained true dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true -p:UseAppHost=true -p:DebugType=none --self-contained true
New-Item -ItemType Directory -Force -Path ./TempFiles | Out-Null if ($LASTEXITCODE -ne 0) { throw '桌面端发布失败' }
Compress-Archive -Path ./bin/Release/net10.0/win-x64/publish/* -DestinationPath ./TempFiles/ZonyLrcTools.Desktop_win-x64_${{ steps.date.outputs.date }}.zip -Force
shell: pwsh shell: pwsh
# Microsoft.Data.Sqlite 的原生库不会被打进单文件 exe,漏了它 .kgg 解密会在运行时直接失败。 # 单文件发布仍需附带 SQLite 原生库、配置模板及第三方许可声明。
# 这里在打包后做一次校验,让 CI 在发布环节而不是在用户机器上暴露问题。
#
# 顺带盯着裁剪有没有真的生效:项目默认开了 PublishTrimmed,但裁剪可以被环境变量、
# 命令行参数或者一次 csproj 手滑静默关掉,而关掉之后唯一的症状就是包变大 55 MB。
# 用一个宽阈值(90 MB)而不是精确值,是因为框架版本升级会让体积小幅波动。
- name: Verify Desktop publish output - name: Verify Desktop publish output
working-directory: ./src/ZonyLrcTools.Desktop working-directory: ./src/ZonyLrcTools.Desktop
run: | run: |
@@ -79,6 +73,7 @@ jobs:
if (-not (Test-Path $exe)) { throw "缺少主程序: $exe" } if (-not (Test-Path $exe)) { throw "缺少主程序: $exe" }
if (-not (Test-Path $sqlite)) { throw "缺少 SQLite 原生库: $sqlite(.kgg 解密依赖它)" } 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 '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) $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" Write-Host "publish 目录校验通过:$((Get-ChildItem $publish -File).Count) 个文件,共 $totalMb MB"
@@ -86,6 +81,12 @@ jobs:
throw "publish 目录有 $totalMb MB,超过 90 MB 上限;这通常意味着 PublishTrimmed 被关掉了" throw "publish 目录有 $totalMb MB,超过 90 MB 上限;这通常意味着 PublishTrimmed 被关掉了"
} }
shell: pwsh 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 - name: Upload artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
+2
View File
@@ -51,6 +51,8 @@
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" /> <PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" /> <PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" />
<PackageVersion Include="Avalonia.Controls.DataGrid" 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 --> <!-- MVVM -->
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" /> <PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<!-- Localization --> <!-- Localization -->
+15 -1
View File
@@ -8,7 +8,7 @@ English | [简体中文](./docs/zh_CN.md)
# Introduction # 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. 🚧 The current version is under development.
🚧 If you want to see working code, please switch to the dev branch. 🚧 If you want to see working code, please switch to the dev branch.
@@ -31,6 +31,20 @@ ZonyLrcTools.Cli --help
# Usage # 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. 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 # Donation
[爱发电](https://afdian.net/a/zony-lrc-tools) [爱发电](https://afdian.net/a/zony-lrc-tools)
+19 -1
View File
@@ -8,7 +8,7 @@ English | [简体中文](./zh_CN.md)
# Introduction # 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. 🚧 The current version is under development.
🚧 If you want to see working code, please switch to the dev branch. 🚧 If you want to see working code, please switch to the dev branch.
@@ -31,6 +31,24 @@ ZonyLrcTools.Cli --help
# Usage # 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. 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 # Donation
[爱发电](https://afdian.net/a/zony-lrc-tools) [爱发电](https://afdian.net/a/zony-lrc-tools)
+19 -1
View File
@@ -8,7 +8,7 @@
# 简介 # 简介
ZonyLrcToolX 4 是一个基于 CEF 的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。 ZonyLrcToolX 4 是一个提供 .NET 10 CLI 和 Avalonia 桌面界面的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。
🚧 当前版本正在开发当中。 🚧 当前版本正在开发当中。
🚧 如果你想查看可以工作的代码,请切换到 dev 分支。 🚧 如果你想查看可以工作的代码,请切换到 dev 分支。
@@ -32,6 +32,24 @@ ZonyLrcTools.Cli --help
软件的具体使用方法已经迁移到了全新的文档站点,请跳转到 [https://docs.myzony.com](https://docs.myzony.com),里面包含完整的说明文档。 软件的具体使用方法已经迁移到了全新的文档站点,请跳转到 [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) [爱发电](https://afdian.net/a/zony-lrc-tools)
@@ -41,14 +41,14 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
{ {
_logger.LogInformation("开始扫描文件夹,请稍等..."); _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) .SelectMany(f => f.FilePaths)
.ToList(); .ToList();
_logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。"); _logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。");
// WarpTask.Dispose 会取消令牌并同步等待所有槽位释放,漏掉 using 就会 // 等待转换结束后释放并发控制资源。
// 泄漏 CTS/Semaphore,并让终结器线程去做阻塞等待。
using var wrapTask = new WarpTask(4); using var wrapTask = new WarpTask(4);
var tasks = files.Select(path => wrapTask.RunAsync(async () => var tasks = files.Select(path => wrapTask.RunAsync(async () =>
{ {
@@ -1,16 +1,17 @@
using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.DependencyInject;
using ZonyLrcTools.Common.Infrastructure.Exceptions; using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Extensions; using ZonyLrcTools.Common.Infrastructure.Extensions;
using ZonyLrcTools.Common.Infrastructure.IO;
using ZonyLrcTools.Common.Infrastructure.Logging; using ZonyLrcTools.Common.Infrastructure.Logging;
using ZonyLrcTools.Common.Infrastructure.Threading; using ZonyLrcTools.Common.Infrastructure.Threading;
namespace ZonyLrcTools.Common.Album; namespace ZonyLrcTools.Common.Album;
/// <inheritdoc />
public class AlbumDownloader : IAlbumDownloader, ISingletonDependency public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
{ {
private readonly IEnumerable<IAlbumProvider> _albumProviders; private readonly IEnumerable<IAlbumProvider> _albumProviders;
/// <inheritdoc />
public IEnumerable<IAlbumProvider> AvailableProviders => new Lazy<IEnumerable<IAlbumProvider>>(() => public IEnumerable<IAlbumProvider> AvailableProviders => new Lazy<IEnumerable<IAlbumProvider>>(() =>
{ {
return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase); return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
@@ -18,6 +19,9 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
private readonly IWarpLogger _logger; private readonly IWarpLogger _logger;
/// <summary>
/// 创建专辑封面下载器。
/// </summary>
public AlbumDownloader(IEnumerable<IAlbumProvider> albumProviders, public AlbumDownloader(IEnumerable<IAlbumProvider> albumProviders,
IWarpLogger logger) IWarpLogger logger)
{ {
@@ -25,38 +29,19 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
_logger = logger; _logger = logger;
} }
/// <inheritdoc />
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos, public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
int parallelCount = 2, int parallelCount = 2,
Func<MusicInfo, Task>? callback = null, Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
await _logger.InfoAsync("开始下载专辑图像数据...");
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
if (provider == null)
{
// 没有任何可用的专辑图像源,全部标记为失败并回调,避免调用方一直等待。
foreach (var info in needDownloadMusicInfos) foreach (var info in needDownloadMusicInfos)
{ {
info.IsSuccessful = false; info.IsSuccessful = false;
if (callback == null)
{
continue;
} }
try cancellationToken.ThrowIfCancellationRequested();
{ var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
await callback(info);
}
catch (Exception ex)
{
await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。");
}
}
return;
}
if (parallelCount <= 0) if (parallelCount <= 0)
{ {
@@ -72,59 +57,81 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
var album = await provider.DownloadAsync(info.Name, info.Artist); var filePath = Path.ChangeExtension(info.FilePath, ".png");
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
if (album.Length <= 0)
{
info.IsSuccessful = false;
return;
}
// 已存在同名图像视为成功,不重复覆盖用户已有的封面。
if (File.Exists(filePath)) if (File.Exists(filePath))
{ {
info.IsSuccessful = true; info.IsSuccessful = true;
return; return;
} }
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album); if (provider == null)
info.IsSuccessful = true;
_logger.LogSuccessful(info);
}
catch (ErrorCodeException ex)
{ {
info.IsSuccessful = false; return;
_logger.LogWarningInfo(ex);
} }
catch (OperationCanceledException)
var album = await provider.DownloadAsync(info.Name, info.Artist);
cancellationToken.ThrowIfCancellationRequested();
if (album.Length == 0)
{ {
info.IsSuccessful = false; return;
} }
catch (Exception ex)
var temporaryPath = $"{filePath}.{Guid.NewGuid():N}.tmp";
try
{ {
info.IsSuccessful = false; await File.WriteAllBytesAsync(temporaryPath, album, cancellationToken);
await _logger.ErrorAsync($"下载专辑图像时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。"); 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 finally
{ {
// 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。
if (callback != null) if (callback != null)
{ {
try try
{ {
await callback(info); await callback(info);
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex) catch (Exception ex)
{ {
await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。"); await _logger.WarnAsync("处理专辑下载回调失败。", ex);
} }
} }
} }
}, cancellationToken), cancellationToken)); }, cancellationToken), cancellationToken));
await Task.WhenAll(warpTaskList); await Task.WhenAll(warpTaskList);
cancellationToken.ThrowIfCancellationRequested();
await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。"); await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。");
} }
@@ -1,5 +1,8 @@
namespace ZonyLrcTools.Common.Album; namespace ZonyLrcTools.Common.Album;
/// <summary>
/// 下载歌曲对应的专辑封面。
/// </summary>
public interface IAlbumDownloader public interface IAlbumDownloader
{ {
/// <summary> /// <summary>
@@ -14,5 +17,8 @@ public interface IAlbumDownloader
Func<MusicInfo, Task>? callback = null, Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
/// <summary>
/// 可用的专辑封面来源。
/// </summary>
IEnumerable<IAlbumProvider> AvailableProviders { get; } IEnumerable<IAlbumProvider> AvailableProviders { get; }
} }
@@ -1,6 +1,4 @@
using System.Text;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ZonyLrcTools.Common.Infrastructure.Exceptions; using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Logging; using ZonyLrcTools.Common.Infrastructure.Logging;
@@ -19,26 +17,19 @@ namespace ZonyLrcTools.Common.Infrastructure.Extensions
/// <param name="e">异常实例,可为空。</param> /// <param name="e">异常实例,可为空。</param>
public static void LogWarningWithErrorCode(this IWarpLogger logger, int errorCode, Exception? e = null) 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> /// <summary>
/// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。 /// 记录错误码与异常,不重新抛出业务异常。
/// <remarks>
/// 这个方法只负责记录,<b>不会抛出异常</b>。调用点全部位于 catch 块内,
/// 若在此处重新抛出,异常会穿透调用方的 catch 并终止整批任务
/// (例如一首歌的编码配置有误会导致整批歌词下载中断)。
/// 需要向上传播错误时,请由调用方显式决定,而不是让日志方法代劳。
/// </remarks>
/// </summary> /// </summary>
/// <param name="logger">日志记录器的实例。</param> /// <param name="logger">日志记录器的实例。</param>
/// <param name="exception">错误码异常实例。</param> /// <param name="exception">错误码异常实例。</param>
public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception) public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception)
{ {
var sb = new StringBuilder(); logger.WarnAsync(
sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}"); $"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}",
sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}"); exception).GetAwaiter().GetResult();
logger.WarnAsync(sb.ToString()).GetAwaiter().GetResult();
} }
/// <summary> /// <summary>
@@ -18,59 +18,73 @@ namespace ZonyLrcTools.Common.Infrastructure.Network
_httpClientFactory = httpClientFactory; _httpClientFactory = httpClientFactory;
} }
/// <inheritdoc />
public async ValueTask<string> PostAsync(string url, public async ValueTask<string> PostAsync(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null) Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{ {
using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption); using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption,
var responseContentString = await responseMessage.Content.ReadAsStringAsync(); cancellationToken: cancellationToken);
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
return ValidateHttpResponse(responseMessage, parameters, responseContentString); return ValidateHttpResponse(responseMessage, parameters, responseContentString);
} }
/// <inheritdoc />
public async ValueTask<TResponse> PostAsync<TResponse>(string url, public async ValueTask<TResponse> PostAsync<TResponse>(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, 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); return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
} }
/// <inheritdoc />
public async ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url, public async ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null) Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{ {
var parametersStr = isQueryStringParam ? BuildQueryString(parameters) : BuildJsonBodyString(parameters); 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); requestMessage.Content = new StringContent(parametersStr);
requestOption?.Invoke(requestMessage); 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, public async ValueTask<string> GetAsync(string url,
object? parameters = null, object? parameters = null,
Action<HttpRequestMessage>? requestOption = null) Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{ {
var requestParamsStr = BuildQueryString(parameters); 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); requestOption?.Invoke(requestMsg);
using var responseMessage = await BuildHttpClient().SendAsync(requestMsg); using var client = BuildHttpClient();
var responseContentString = await responseMessage.Content.ReadAsStringAsync(); using var responseMessage = await client.SendAsync(requestMsg, cancellationToken);
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
return ValidateHttpResponse(responseMessage, parameters, responseContentString); return ValidateHttpResponse(responseMessage, parameters, responseContentString);
} }
/// <inheritdoc />
public async ValueTask<TResponse> GetAsync<TResponse>(string url, public async ValueTask<TResponse> GetAsync<TResponse>(string url,
object? parameters = null, 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); return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
} }
@@ -12,11 +12,13 @@
/// <param name="parameters">请求的参数。</param> /// <param name="parameters">请求的参数。</param>
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param> /// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
/// <param name="requestOption">请求时的配置动作。</param> /// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>服务端的响应结果。</returns> /// <returns>服务端的响应结果。</returns>
ValueTask<string> PostAsync(string url, ValueTask<string> PostAsync(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null); Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// 根据指定的配置执行 POST 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。 /// 根据指定的配置执行 POST 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
@@ -25,17 +27,28 @@
/// <param name="parameters">请求的参数。</param> /// <param name="parameters">请求的参数。</param>
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param> /// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
/// <param name="requestOption">请求时的配置动作。</param> /// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam> /// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
/// <returns>服务端的响应结果。</returns> /// <returns>服务端的响应结果。</returns>
ValueTask<TResponse> PostAsync<TResponse>(string url, ValueTask<TResponse> PostAsync<TResponse>(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, 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, ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
object? parameters = null, object? parameters = null,
bool isQueryStringParam = false, bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null); Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// 根据指定的配置执行 GET 请求,并以 <see cref="string"/> 作为返回值。 /// 根据指定的配置执行 GET 请求,并以 <see cref="string"/> 作为返回值。
@@ -43,10 +56,12 @@
/// <param name="url">请求的 URL 地址。</param> /// <param name="url">请求的 URL 地址。</param>
/// <param name="parameters">请求的参数。</param> /// <param name="parameters">请求的参数。</param>
/// <param name="requestOption">请求时的配置动作。</param> /// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>服务端的响应结果。</returns> /// <returns>服务端的响应结果。</returns>
ValueTask<string> GetAsync(string url, ValueTask<string> GetAsync(string url,
object? parameters = null, object? parameters = null,
Action<HttpRequestMessage>? requestOption = null); Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// 根据指定的配置执行 GET 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。 /// 根据指定的配置执行 GET 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
@@ -54,11 +69,13 @@
/// <param name="url">请求的 URL 地址。</param> /// <param name="url">请求的 URL 地址。</param>
/// <param name="parameters">请求的参数。</param> /// <param name="parameters">请求的参数。</param>
/// <param name="requestOption">请求时的配置动作。</param> /// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam> /// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
/// <returns>服务端的响应结果。</returns> /// <returns>服务端的响应结果。</returns>
ValueTask<TResponse> GetAsync<TResponse>( ValueTask<TResponse> GetAsync<TResponse>(
string url, string url,
object? parameters = null, object? parameters = null,
Action<HttpRequestMessage>? requestOption = null); Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
} }
} }
@@ -42,8 +42,14 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
Func<MusicInfo, Task>? callback = null, Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default) 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) if (parallelCount <= 0)
{ {
parallelCount = 1; parallelCount = 1;
@@ -54,98 +60,105 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
warpTask.RunAsync(() => warpTask.RunAsync(() =>
Task.Run(async () => Task.Run(async () =>
{ {
// 依次尝试所有可用的歌词来源,直到某一家真正返回了歌词。 try
// 某个来源返回空结果是「这家没搜到」,不是「这首歌没有歌词」,必须继续问下一家。
var isFinished = false;
var hasProviderError = false;
foreach (var lyricsProvider in AvailableProviders)
{ {
var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info); var isFinished = false;
var hasProviderError = providers.Length == 0;
foreach (var lyricsProvider in providers)
{
cancellationToken.ThrowIfCancellationRequested();
var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info, cancellationToken);
if (result == LyricsDownloadResult.Success) if (result == LyricsDownloadResult.Success)
{ {
_logger.LogSuccessful(info);
isFinished = true; isFinished = true;
break; break;
} }
if (result == LyricsDownloadResult.Failed) hasProviderError |= result == LyricsDownloadResult.Failed;
{
hasProviderError = true;
}
} }
cancellationToken.ThrowIfCancellationRequested();
if (!isFinished) if (!isFinished)
{ {
// 所有来源都没有返回歌词。若期间有来源报错,就判为失败; // 只有所有来源均返回空结果时,才按纯音乐处理。
// 否则说明各家都查无此曲,按纯音乐/未收录处理(与旧版的统计口径保持一致)。
info.IsSuccessful = !hasProviderError; info.IsSuccessful = !hasProviderError;
info.IsPruneMusic = !hasProviderError; info.IsPruneMusic = !hasProviderError;
} }
}
// 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。 finally
{
if (callback != null) if (callback != null)
{ {
try try
{ {
await callback(info); await callback(info);
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex) catch (Exception ex)
{ {
await _logger.WarnAsync($"处理歌曲下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。"); await _logger.WarnAsync("处理歌曲下载回调失败。", ex);
}
} }
} }
}, cancellationToken), cancellationToken)); }, cancellationToken), cancellationToken));
await Task.WhenAll(downloadTasks); await Task.WhenAll(downloadTasks);
cancellationToken.ThrowIfCancellationRequested();
var successfulCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: false }); var successfulCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: false });
var skippedCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: true }); var skippedCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: true });
var failedCount = needDownloadMusicInfos.Count(m => m.IsSuccessful == false); var failedCount = needDownloadMusicInfos.Count(m => m.IsSuccessful == false);
await _logger.InfoAsync($"歌词数据下载完成,成功: {successfulCount} 跳过(纯音乐): {skippedCount} 失败{failedCount}。"); 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<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info) private async Task<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info,
CancellationToken cancellationToken = default)
{ {
try try
{ {
cancellationToken.ThrowIfCancellationRequested();
var lyrics = await provider.DownloadAsync(info.Name, info.Artist); var lyrics = await provider.DownloadAsync(info.Name, info.Artist);
cancellationToken.ThrowIfCancellationRequested();
// 该来源没有搜到歌词,交给调用方去问下一家,不能在这里判定整首歌完成。 // 空结果只表示当前来源未找到歌词,继续尝试其他来源。
if (lyrics.IsPruneMusic) if (lyrics.IsPruneMusic)
{ {
return LyricsDownloadResult.Empty; return LyricsDownloadResult.Empty;
} }
// 先把歌词编码成字节,再动磁盘。编码配置有误时(例如 fileEncoding 写成了不存在的名字) // 编码成功后再创建文件,避免配置错误破坏原歌词。
// 这一步就会抛错,此时文件还没被创建,不会留下 0 字节的空壳。
var content = Utf8ToSelectedEncoding(lyrics); var content = Utf8ToSelectedEncoding(lyrics);
var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, var newLyricsFilePath = Path.ChangeExtension(info.FilePath, ".lrc");
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc"); var temporaryPath = $"{newLyricsFilePath}.{Guid.NewGuid():N}.tmp";
try
if (File.Exists(newLyricsFilePath))
{ {
File.Delete(newLyricsFilePath); await File.WriteAllBytesAsync(temporaryPath, content, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
File.Move(temporaryPath, newLyricsFilePath, overwrite: true);
} }
finally
// Write lyrics to file.
await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write))
{ {
await fileStream.WriteAsync(content); File.Delete(temporaryPath);
await fileStream.FlushAsync();
} }
info.IsSuccessful = true; info.IsSuccessful = true;
info.IsPruneMusic = false; info.IsPruneMusic = false;
return LyricsDownloadResult.Success; return LyricsDownloadResult.Success;
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (ErrorCodeException ex) catch (ErrorCodeException ex)
{ {
// 失败标记必须放在记录日志之前:LoggerHelper 即便将来再改动行为,
// 也不能让「失败」的歌曲以默认的 IsSuccessful = true 冒出去。
info.IsSuccessful = false; info.IsSuccessful = false;
info.IsPruneMusic = false; info.IsPruneMusic = false;
_logger.LogWarningInfo(ex); _logger.LogWarningInfo(ex);
@@ -155,7 +168,7 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
{ {
info.IsSuccessful = false; info.IsSuccessful = false;
info.IsPruneMusic = false; info.IsPruneMusic = false;
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。"); await _logger.WarnAsync("当前歌词来源下载失败,将尝试其他来源。", ex);
return LyricsDownloadResult.Failed; return LyricsDownloadResult.Failed;
} }
} }
@@ -194,7 +207,8 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
return Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(_options.Provider.Lyric.Config.FileEncoding), lyrics.GetUtf8Bytes()); 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(); var failedSongList = musicInfos.Where(m => m.IsSuccessful == false).ToImmutableList();
if (!failedSongList.Any()) if (!failedSongList.Any())
@@ -210,6 +224,6 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
failedSongFiles.AppendLine($"{failedSongFile.Name},{failedSongFile.Artist},{failedSongFile.FilePath}"); failedSongFiles.AppendLine($"{failedSongFile.Name},{failedSongFile.Artist},{failedSongFile.FilePath}");
} }
await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString()); await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString(), cancellationToken);
} }
} }
@@ -11,12 +11,16 @@ namespace ZonyLrcTools.Common.MusicDecryption
private readonly IWarpLogger _warpLogger; private readonly IWarpLogger _warpLogger;
private readonly IKugouKeyProvider? _kugouKeyProvider; private readonly IKugouKeyProvider? _kugouKeyProvider;
/// <summary>
/// 创建音乐解密器。
/// </summary>
public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null) public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null)
{ {
_warpLogger = warpLogger; _warpLogger = warpLogger;
_kugouKeyProvider = kugouKeyProvider; _kugouKeyProvider = kugouKeyProvider;
} }
/// <inheritdoc />
public async Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default) public async Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default)
{ {
try try
@@ -36,12 +40,46 @@ namespace ZonyLrcTools.Common.MusicDecryption
using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { }); using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { });
var outFileName = (await decrypto.DecryptAsync()).NewName; var outFileName = (await decrypto.DecryptAsync()).NewName;
cancellationToken.ThrowIfCancellationRequested();
var outFilePath = Path.Combine(Path.GetDirectoryName(filePath)!, outFileName); 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); 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 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); return DecryptionResult.Success(outFilePath);
@@ -46,7 +46,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
void Invalidate(); void Invalidate();
/// <summary> /// <summary>
/// 判断文件是否是 .kgg(按魔数,不看扩展名)。 /// 按魔数和加密版本判断文件是否为 KGG,不看扩展名。
/// </summary> /// </summary>
bool IsKggFile(string filePath); bool IsKggFile(string filePath);
@@ -15,7 +15,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary> /// <summary>
/// V2 前缀,解码后即 "QQMusic EncV2,Key:"。 /// V2 前缀,解码后即 "QQMusic EncV2,Key:"。
/// </summary> /// </summary>
private static readonly byte[] V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6"u8.ToArray(); private const string V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6";
private static readonly byte[] V2Key1 = private static readonly byte[] V2Key1 =
[ [
@@ -35,11 +35,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary> /// <summary>
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。 /// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
/// <param name="invalidCharCount">
/// Base64 段里被忽略的非法字符数量。Base64 解码本身是宽容的(会静默映射成 0),
/// 这里把它统计出来,让上层能把「密钥损坏」和「没有密钥」区分开。
/// </param>
/// </summary> /// </summary>
/// <param name="ekey">数据库中的密钥。</param>
/// <param name="invalidCharCount">Base64 中的非法字符数量,空白不计入。</param>
/// <returns>原始密钥;解码失败时为空数组。</returns> /// <returns>原始密钥;解码失败时为空数组。</returns>
public static byte[] Decode(string ekey, out int invalidCharCount) public static byte[] Decode(string ekey, out int invalidCharCount)
{ {
@@ -49,10 +47,10 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return []; return [];
} }
var raw = Encoding.Latin1.GetBytes(ekey); if (ekey.StartsWith(V2Prefix, StringComparison.Ordinal))
if (raw.Length >= V2Prefix.Length && raw.AsSpan(0, V2Prefix.Length).SequenceEqual(V2Prefix))
{ {
var inner = TcTea.CbcDecrypt(raw[V2Prefix.Length..], TcTea.ToRoundKeys(V2Key1)); var raw = Encoding.Latin1.GetBytes(ekey[V2Prefix.Length..]);
var inner = TcTea.CbcDecrypt(raw, TcTea.ToRoundKeys(V2Key1));
if (inner.Length == 0) if (inner.Length == 0)
{ {
return []; return [];
@@ -72,7 +70,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private static byte[] DecodeV1(string ekey, out int invalidCharCount) private static byte[] DecodeV1(string ekey, out int invalidCharCount)
{ {
var result = Base64Decode(Encoding.Latin1.GetBytes(ekey), out invalidCharCount); var result = Base64Decode(ekey, out invalidCharCount);
if (result.Length < 8) if (result.Length < 8)
{ {
return []; return [];
@@ -98,107 +96,52 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return output; return output;
} }
private static readonly byte[] Base64Table = private static byte[] Base64Decode(string input, out int invalidCount)
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u8.ToArray();
/// <summary>
/// 宽容的 Base64 解码,兼容 URL-safe 变体与不规范的长度。
/// <param name="invalidCount">输入中不属于 Base64 的字符数量(空白字符会被跳过,不计入)。</param>
/// </summary>
private static byte[] Base64Decode(byte[] input, out int invalidCount)
{ {
var reverse = new byte[256]; var normalized = new char[input.Length + 3];
var isKnown = new bool[256]; var length = 0;
for (var i = 0; i < Base64Table.Length; i++)
{
reverse[Base64Table[i]] = (byte)i;
isKnown[Base64Table[i]] = true;
}
// URL-safe 变体。
reverse[(byte)'-'] = 62;
reverse[(byte)'_'] = 63;
isKnown[(byte)'-'] = true;
isKnown[(byte)'_'] = true;
isKnown[(byte)'='] = true;
// 空白字符按「忽略」处理,其余未知字符计入 invalidCount,交给调用方判定为损坏。
isKnown[(byte)' '] = true;
isKnown[(byte)'\r'] = true;
isKnown[(byte)'\n'] = true;
isKnown[(byte)'\t'] = true;
invalidCount = 0; invalidCount = 0;
var cleaned = new byte[input.Length];
var cleanedLength = 0;
foreach (var value in input) foreach (var value in input)
{ {
if (value is (byte)' ' or (byte)'\r' or (byte)'\n' or (byte)'\t') if (value is ' ' or '\r' or '\n' or '\t')
{ {
continue; continue;
} }
if (!isKnown[value]) if (value is not (>= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9'
or '+' or '/' or '-' or '_' or '='))
{ {
invalidCount++; invalidCount++;
continue; continue;
} }
cleaned[cleanedLength++] = value; normalized[length++] = value switch
}
input = cleaned.AsSpan(0, cleanedLength).ToArray();
var output = new byte[(input.Length + 3) / 4 * 3];
var outOffset = 0;
// 解一组 4 个字符;返回 true 表示遇到了填充,可以结束。
bool DecodeBlock(ReadOnlySpan<byte> block)
{ {
var a = reverse[block[0]]; '-' => '+',
var b = reverse[block[1]]; '_' => '/',
var c = reverse[block[2]]; _ => value
var d = reverse[block[3]]; };
}
output[outOffset++] = (byte)((a << 2) | (b >> 4)); if (invalidCount != 0 || length == 0 || length % 4 == 1)
if (block[2] == '=')
{ {
return true; return [];
} }
output[outOffset++] = (byte)((b << 4) | (c >> 2)); // 兼容省略末尾填充的密钥,由标准解码器校验填充位置。
while (length % 4 != 0)
if (block[3] == '=')
{ {
return true; normalized[length++] = '=';
} }
output[outOffset++] = (byte)((c << 6) | d); var padding = normalized[length - 1] == '=' ? 1 : 0;
return false; if (normalized[length - 2] == '=')
}
var fullLength = input.Length - input.Length % 4;
for (var i = 0; i < fullLength; i += 4)
{ {
if (DecodeBlock(input.AsSpan(i, 4))) padding++;
{
return output.AsSpan(0, outOffset).ToArray();
}
} }
var remainder = input.Length % 4; var output = new byte[length / 4 * 3 - padding];
if (remainder != 0) return Convert.TryFromBase64Chars(normalized.AsSpan(0, length), output, out _) ? output : [];
{
var tail = new byte[4];
tail[0] = input[fullLength];
tail[1] = remainder > 1 ? input[fullLength + 1] : (byte)'=';
tail[2] = (byte)'=';
tail[3] = (byte)'=';
DecodeBlock(tail);
}
return output.AsSpan(0, outOffset).ToArray();
} }
} }
} }
@@ -29,16 +29,17 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private static byte[] Magic => KugouEkeyDatabase.KggMagic; private static byte[] Magic => KugouEkeyDatabase.KggMagic;
/// <summary> /// <summary>
/// 判断文件是否真的是 .kgg 格式(按魔数而非扩展名)。 /// 按魔数和加密版本判断是否为 KGG,避免误判共用魔数的旧版 KGM。
/// </summary> /// </summary>
public static bool IsKggFile(string filePath) public static bool IsKggFile(string filePath)
{ {
try try
{ {
using var stream = File.OpenRead(filePath); using var stream = File.OpenRead(filePath);
Span<byte> buffer = stackalloc byte[16]; Span<byte> buffer = stackalloc byte[0x18];
return stream.ReadAtLeast(buffer, 16, throwOnEndOfStream: false) == 16 return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length
&& buffer.SequenceEqual(Magic); && buffer[..Magic.Length].SequenceEqual(Magic)
&& BinaryPrimitives.ReadUInt32LittleEndian(buffer[0x14..]) == ExpectedEncodingVersion;
} }
catch catch
{ {
@@ -55,8 +56,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <returns>解密结果;失败时带有可读的错误说明。</returns> /// <returns>解密结果;失败时带有可读的错误说明。</returns>
public static async Task<DecryptionResult> ConvertAsync(string filePath, public static async Task<DecryptionResult> ConvertAsync(string filePath,
IKugouKeyProvider? keyProvider, IKugouKeyProvider? keyProvider,
CancellationToken cancellationToken) CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
if (!File.Exists(filePath)) if (!File.Exists(filePath))
{ {
return DecryptionResult.Failed($"文件不存在: {filePath}"); return DecryptionResult.Failed($"文件不存在: {filePath}");
@@ -77,6 +79,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
} }
var offsetToAudio = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10)); 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)); var encodingVersion = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14));
if (encodingVersion != ExpectedEncodingVersion) if (encodingVersion != ExpectedEncodingVersion)
{ {
@@ -93,10 +100,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
if (!HasDatabase(keyProvider)) if (!HasDatabase(keyProvider))
{ {
return DecryptionResult.Failed(KugouEkeyDatabase.BuildMissingDatabaseMessage()); return DecryptionResult.Failed(keyProvider?.Probe().Message ?? KugouEkeyDatabase.BuildMissingDatabaseMessage());
} }
var ekey = ResolveEkey(keyProvider, audioHash); var ekey = ResolveEkey(keyProvider, audioHash);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(ekey)) if (string.IsNullOrEmpty(ekey))
{ {
return DecryptionResult.Failed( return DecryptionResult.Failed(
@@ -129,6 +137,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
cipher.Decrypt(magic, 0); cipher.Decrypt(magic, 0);
var extension = DetectExtension(magic); var extension = DetectExtension(magic);
if (extension == null)
{
return DecryptionResult.Failed("解密后的音频格式无法识别,文件或密钥可能已损坏。");
}
input.Seek(offsetToAudio, SeekOrigin.Begin); input.Seek(offsetToAudio, SeekOrigin.Begin);
var outputPath = Path.Combine( var outputPath = Path.Combine(
@@ -138,25 +151,30 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
// 期望的输出字节数,用于校验写盘是否完整。 // 期望的输出字节数,用于校验写盘是否完整。
var expectedLength = input.Length - offsetToAudio; var expectedLength = input.Length - offsetToAudio;
// 目标已存在且大小正确就不再覆盖,避免重复解密白费时间。 if (File.Exists(outputPath))
// 只要大小对不上(例如上次被中途取消留下的半截文件),就重新解密覆盖。
if (File.Exists(outputPath) && new FileInfo(outputPath).Length == expectedLength)
{ {
return DecryptionResult.Success(outputPath); return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outputPath}");
} }
// 先写临时文件,成功后再改名。中途取消或被强杀都不会污染正式输出文件名。 // 每次转换独占临时文件,仅在完整写入后发布,且不覆盖已有输出。
var tempPath = outputPath + ".part"; var tempPath = outputPath + $".{Guid.NewGuid():N}.part";
var ownsTempFile = false;
try try
{ {
await using (var output = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, await using (var output = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
BufferSize, true)) BufferSize, true))
{ {
ownsTempFile = true;
var buffer = new byte[BufferSize]; var buffer = new byte[BufferSize];
long offset = 0; var offset = 0L;
int read; while (true)
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
{ {
var read = await input.ReadAsync(buffer, cancellationToken);
if (read == 0)
{
break;
}
cipher.Decrypt(buffer.AsSpan(0, read), offset); cipher.Decrypt(buffer.AsSpan(0, read), offset);
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken); await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
offset += read; offset += read;
@@ -170,12 +188,15 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
} }
} }
File.Move(tempPath, outputPath, overwrite: true); cancellationToken.ThrowIfCancellationRequested();
File.Move(tempPath, outputPath);
} }
catch finally
{
if (ownsTempFile)
{ {
TryDelete(tempPath); TryDelete(tempPath);
throw; }
} }
return DecryptionResult.Success(outputPath); return DecryptionResult.Success(outputPath);
@@ -192,13 +213,13 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
} }
catch catch
{ {
// 清理失败不影响主流程,下次解密会覆盖这个临时文件。 // 保留原始转换结果或异常。
} }
} }
private static bool HasDatabase(IKugouKeyProvider? keyProvider) private static bool HasDatabase(IKugouKeyProvider? keyProvider)
{ {
return keyProvider?.DatabasePath != null || KugouEkeyDatabase.FindDatabasePath() != null; return keyProvider != null ? keyProvider.DatabasePath != null : KugouEkeyDatabase.FindDatabasePath() != null;
} }
/// <summary> /// <summary>
@@ -221,7 +242,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return keys.TryGetValue(audioHash, out var ekey) ? ekey : null; return keys.TryGetValue(audioHash, out var ekey) ? ekey : null;
} }
private static string DetectExtension(ReadOnlySpan<byte> magic) private static string? DetectExtension(ReadOnlySpan<byte> magic)
{ {
if (magic.SequenceEqual("fLaC"u8)) if (magic.SequenceEqual("fLaC"u8))
{ {
@@ -233,7 +254,10 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return "ogg"; return "ogg";
} }
return "mp3"; return magic[..3].SequenceEqual("ID3"u8)
|| (magic[0] == 0xFF && (magic[1] & 0xE0) == 0xE0 && (magic[1] & 0x06) != 0)
? "mp3"
: null;
} }
} }
} }
@@ -4,6 +4,7 @@
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. // The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
@@ -13,7 +14,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary> /// <summary>
/// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。 /// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。
/// <remarks> /// <remarks>
/// 数据库按 4KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥 + 页号派生。 /// 数据库按 1KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥和页号派生。
/// 解密后可以读到 <c>ShareFileItems</c> 表里的 ekey,那是 .kgg 文件真正用的解密密钥。 /// 解密后可以读到 <c>ShareFileItems</c> 表里的 ekey,那是 .kgg 文件真正用的解密密钥。
/// </remarks> /// </remarks>
/// </summary> /// </summary>
@@ -106,20 +107,18 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return result; return result;
} }
// 解密后的内容写到临时文件,交给 SQLite 自己解析,避免手写记录格式。 // 直接从内存解析,避免明文密钥落盘和并发清理临时文件的竞争。
// 这里放的是明文密钥库,所以用一个专用目录并在每次进入时清理上次留下的残留: var pinned = GCHandle.Alloc(plain, GCHandleType.Pinned);
// 进程被强杀时 finally 不会执行,但下一次读取会把上一轮的明文文件删掉。
var tempDirectory = Path.Combine(Path.GetTempPath(), TemporaryDirectoryName);
var tempPath = Path.Combine(tempDirectory, $"{Guid.NewGuid():N}.db");
try try
{ {
Directory.CreateDirectory(tempDirectory); using var connection = new SqliteConnection("Data Source=:memory:;Pooling=False");
SweepStaleTempFiles(tempDirectory);
WriteFileWithFlush(tempPath, plain);
using var connection = new SqliteConnection($"Data Source={tempPath};Mode=ReadOnly");
connection.Open(); 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(); using var command = connection.CreateCommand();
command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''"; command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''";
@@ -146,54 +145,12 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
} }
finally finally
{ {
TryDeleteFile(tempPath); pinned.Free();
} }
return result; return result;
} }
private const string TemporaryDirectoryName = "zony-kgm-temp";
private static void WriteFileWithFlush(string path, byte[] content)
{
using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
stream.Write(content, 0, content.Length);
stream.Flush(true);
}
/// <summary>
/// 清掉上一次运行留下的明文临时库(正常退出时 finally 已经删过,这里只兜异常退出的底)。
/// </summary>
private static void SweepStaleTempFiles(string directory)
{
try
{
foreach (var file in Directory.EnumerateFiles(directory, "*.db"))
{
TryDeleteFile(file);
}
}
catch
{
// 目录枚举失败不影响本次读取。
}
}
private static void TryDeleteFile(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// 删不掉不影响结果,下次进入时还会再清一次。
}
}
/// <summary> /// <summary>
/// 把整个加密数据库解密成明文的 SQLite 字节流。 /// 把整个加密数据库解密成明文的 SQLite 字节流。
/// </summary> /// </summary>
@@ -201,12 +158,13 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{ {
using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read); using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var length = (int)source.Length; var sourceLength = source.Length;
if (length == 0 || length % PageSize != 0) if (sourceLength == 0 || sourceLength > Array.MaxLength || sourceLength % PageSize != 0)
{ {
return []; return [];
} }
var length = (int)sourceLength;
var pageCount = length / PageSize; var pageCount = length / PageSize;
var plain = new byte[length]; var plain = new byte[length];
var headerBuffer = new byte[8]; var headerBuffer = new byte[8];
@@ -3,8 +3,6 @@
// Copyright (c) 2024 LSR // Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. // The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{ {
/// <summary> /// <summary>
@@ -70,6 +68,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private readonly byte[] _key; private readonly byte[] _key;
/// <summary>
/// 根据短密钥生成查找表。
/// </summary>
public Qmc2MapCipher(byte[] key) public Qmc2MapCipher(byte[] key)
{ {
_key = new byte[MapKeySize]; _key = new byte[MapKeySize];
@@ -79,16 +80,18 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
var j = (int)(((long)i * i + MapIndexOffset) % length); var j = (int)(((long)i * i + MapIndexOffset) % length);
var shift = (j + 4) % 8; var shift = (j + 4) % 8;
var value = key[j]; var value = key[j];
_key[i] = (byte)((value << shift) | (value >> (8 - shift))); _key[i] = (byte)((value << shift) | (value >> shift));
} }
} }
/// <inheritdoc />
public override byte Decrypt(byte cipher, long offset) public override byte Decrypt(byte cipher, long offset)
{ {
var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary; var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary;
return (byte)(cipher ^ _key[index % MapKeySize]); return (byte)(cipher ^ _key[index % MapKeySize]);
} }
/// <inheritdoc />
public override void Decrypt(Span<byte> data, long offset) public override void Decrypt(Span<byte> data, long offset)
{ {
for (var i = 0; i < data.Length; i++) for (var i = 0; i < data.Length; i++)
@@ -119,6 +122,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private readonly byte[] _keyStream = new byte[KeyStreamSize]; private readonly byte[] _keyStream = new byte[KeyStreamSize];
private readonly uint _keyHash; private readonly uint _keyHash;
/// <summary>
/// 根据长密钥生成密钥流。
/// </summary>
public Qmc2Rc4Cipher(byte[] key) public Qmc2Rc4Cipher(byte[] key)
{ {
_key = key; _key = key;
@@ -126,6 +132,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
DeriveKeyStream(); DeriveKeyStream();
} }
/// <inheritdoc />
public override byte Decrypt(byte cipher, long offset) public override byte Decrypt(byte cipher, long offset)
{ {
if (offset < FirstSegmentSize) if (offset < FirstSegmentSize)
@@ -142,6 +149,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]); return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]);
} }
/// <inheritdoc />
public override void Decrypt(Span<byte> data, long offset) public override void Decrypt(Span<byte> data, long offset)
{ {
// 首段与常规段的算法不同,先按边界切一刀。 // 首段与常规段的算法不同,先按边界切一刀。
@@ -182,7 +190,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// </summary> /// </summary>
private static uint ComputeKeyHash(ReadOnlySpan<byte> key) private static uint ComputeKeyHash(ReadOnlySpan<byte> key)
{ {
uint hash = 1; var hash = 1u;
foreach (var item in key) foreach (var item in key)
{ {
if (item == 0) if (item == 0)
@@ -68,8 +68,8 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return []; return [];
} }
ulong iv1 = 0; var iv1 = 0UL;
ulong iv2 = 0; var iv2 = 0UL;
var inOffset = 0; var inOffset = 0;
var header = new byte[HeaderSize]; var header = new byte[HeaderSize];
@@ -16,10 +16,10 @@ namespace ZonyLrcTools.Common.MusicDecryption
private string? _manualPath; private string? _manualPath;
private string? _databasePath; private string? _databasePath;
private string? _loadedPath;
private string? _failureReason; private string? _failureReason;
private bool _isLoaded; private bool _isLoaded;
/// <inheritdoc />
public string? DatabasePath public string? DatabasePath
{ {
get get
@@ -32,12 +32,14 @@ namespace ZonyLrcTools.Common.MusicDecryption
} }
} }
/// <inheritdoc />
public void SetDatabasePath(string? path) public void SetDatabasePath(string? path)
{ {
lock (_syncRoot) lock (_syncRoot)
{ {
var normalized = string.IsNullOrWhiteSpace(path) ? null : path; var normalized = string.IsNullOrWhiteSpace(path) ? null : path;
if (string.Equals(normalized, _manualPath, StringComparison.OrdinalIgnoreCase)) if (string.Equals(normalized, _manualPath,
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{ {
// 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。 // 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。
return; return;
@@ -65,7 +67,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
{ {
var message = _manualPath != null var message = _manualPath != null
? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}" ? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}"
: Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage(); : _failureReason ?? Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage();
return new KugouDatabaseInfo(false, null, 0, message); return new KugouDatabaseInfo(false, null, 0, message);
} }
@@ -88,13 +90,14 @@ namespace ZonyLrcTools.Common.MusicDecryption
_isLoaded = false; _isLoaded = false;
_keys.Clear(); _keys.Clear();
_databasePath = null; _databasePath = null;
_loadedPath = null;
_failureReason = null; _failureReason = null;
} }
} }
public bool IsKggFile(string filePath) => ReadAudioHash(filePath) != null; /// <inheritdoc />
public bool IsKggFile(string filePath) => Kugou.KggMusicDecryptor.IsKggFile(filePath);
/// <inheritdoc />
public string? ReadAudioHash(string filePath) public string? ReadAudioHash(string filePath)
{ {
try try
@@ -111,8 +114,15 @@ namespace ZonyLrcTools.Common.MusicDecryption
return null; 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)); var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
if (hashLength == 0 || hashLength > AudioHashLength) if (hashLength != AudioHashLength)
{ {
return null; return null;
} }
@@ -125,6 +135,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
} }
} }
/// <inheritdoc />
public string? FindKey(string audioHash) public string? FindKey(string audioHash)
{ {
if (string.IsNullOrEmpty(audioHash)) if (string.IsNullOrEmpty(audioHash))
@@ -149,7 +160,6 @@ namespace ZonyLrcTools.Common.MusicDecryption
_isLoaded = true; _isLoaded = true;
_keys.Clear(); _keys.Clear();
_databasePath = null; _databasePath = null;
_loadedPath = null;
_failureReason = null; _failureReason = null;
var path = _manualPath; var path = _manualPath;
@@ -172,15 +182,10 @@ namespace ZonyLrcTools.Common.MusicDecryption
{ {
_failureReason = failureReason ?? "没有读到任何密钥"; _failureReason = failureReason ?? "没有读到任何密钥";
// 手动指定的文件读不出密钥,就不要把它当成可用数据库。
if (_manualPath != null)
{
return; return;
} }
}
_databasePath = path; _databasePath = path;
_loadedPath = path;
foreach (var pair in keys) foreach (var pair in keys)
{ {
_keys[pair.Key] = pair.Value; _keys[pair.Key] = pair.Value;
@@ -15,19 +15,19 @@ public class CsvFileMusicScanner : ITransientDependency
/// <param name="csvFilePath">CSV 文件的路径。</param> /// <param name="csvFilePath">CSV 文件的路径。</param>
/// <param name="outputDirectory">歌词文件的输出目录。</param> /// <param name="outputDirectory">歌词文件的输出目录。</param>
/// <param name="pattern">输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。</param> /// <param name="pattern">输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。</param>
/// <param name="cancellationToken">取消令牌。</param>
public async Task<List<MusicInfo>> GetMusicInfoFromCsvFileAsync(string csvFilePath, string outputDirectory, public async Task<List<MusicInfo>> GetMusicInfoFromCsvFileAsync(string csvFilePath, string outputDirectory,
string pattern) string pattern, CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
var encoding = DetectFileEncoding(csvFilePath); var encoding = DetectFileEncoding(csvFilePath);
var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding); var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding, cancellationToken);
// 不能只按 Environment.NewLine 切分:在 Windows 上读到的是 "\r\n",而用户从网盘、 // 兼容不同操作系统导出的换行符。
// 版本的表格导出、Git 里签出的 CSV 往往是 "\n",那样整个文件会被当成一行,
// 跳过表头之后就是空的,界面上表现为"解析了但一首歌都没有"。
var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
return csvFileLines.Skip(1) return csvFileLines.Skip(1)
.Where(line => line.Contains(',')) // 跳过空行与 VCS 合并产生的杂行。 .Where(line => line.Contains(','))
.Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern)) .Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern))
.ToList(); .ToList();
} }
@@ -20,16 +20,55 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
private readonly IWarpHttpClient _warpHttpClient; private readonly IWarpHttpClient _warpHttpClient;
private readonly ILogger<NetEaseMusicSongListMusicScanner> _logger; private readonly ILogger<NetEaseMusicSongListMusicScanner> _logger;
private const string Host = "https://music.163.com"; 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;
/// <summary> /// <summary>
/// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。 /// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。
/// </summary> /// </summary>
public string Cookie { get; set; } = string.Empty; public string Cookie
{
get
{
lock (_loginStateLock)
{
return _cookie;
}
}
set
{
lock (_loginStateLock)
{
_cookie = value ?? string.Empty;
_loginStateVersion++;
}
}
}
/// <summary> /// <summary>
/// 登录后的 CSRF Token,通常与 <see cref="Cookie"/> 一起持久化。 /// 登录后的 CSRF Token,通常与 <see cref="Cookie"/> 一起持久化。
/// </summary> /// </summary>
public string CsrfToken { get; set; } = string.Empty; public string CsrfToken
{
get
{
lock (_loginStateLock)
{
return _csrfToken;
}
}
set
{
lock (_loginStateLock)
{
_csrfToken = value ?? string.Empty;
_loginStateVersion++;
}
}
}
/// <summary> /// <summary>
/// 当前是否已经持有登录态。 /// 当前是否已经持有登录态。
@@ -51,8 +90,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </summary> /// </summary>
public void ClearLoginState() public void ClearLoginState()
{ {
Cookie = string.Empty; RestoreLoginState(string.Empty, string.Empty);
CsrfToken = string.Empty;
} }
/// <summary> /// <summary>
@@ -62,8 +100,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// <param name="csrfToken">与 <paramref name="cookie"/> 一起保存的 CSRF Token。</param> /// <param name="csrfToken">与 <paramref name="cookie"/> 一起保存的 CSRF Token。</param>
public void RestoreLoginState(string cookie, string csrfToken) public void RestoreLoginState(string cookie, string csrfToken)
{ {
Cookie = cookie ?? string.Empty; lock (_loginStateLock)
CsrfToken = csrfToken ?? string.Empty; {
_cookie = cookie ?? string.Empty;
_csrfToken = csrfToken ?? string.Empty;
_loginStateVersion++;
}
} }
/// <summary> /// <summary>
@@ -78,17 +120,44 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action<NetEaseLoginState>? onStateChanged = null, Action<NetEaseLoginState>? onStateChanged = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
if (IsLoggedIn) await _loginSemaphore.WaitAsync(cancellationToken);
try
{
var session = GetLoginState();
if (!string.IsNullOrEmpty(session.Cookie))
{ {
onStateChanged?.Invoke(NetEaseLoginState.Succeeded); onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
return true; return true;
} }
var loginResponse = await LoginViqQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken); var loginResponse = await LoginViaQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken);
Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty; cancellationToken.ThrowIfCancellationRequested();
CsrfToken = loginResponse.csrfToken ?? string.Empty; var cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
lock (_loginStateLock)
{
// 退出或恢复会话后,不能再提交旧二维码的登录结果。
if (session.Version != _loginStateVersion)
{
return false;
}
return IsLoggedIn; _cookie = cookie;
_csrfToken = loginResponse.csrfToken ?? string.Empty;
_loginStateVersion++;
}
if (string.IsNullOrEmpty(cookie))
{
return false;
}
onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
return true;
}
finally
{
_loginSemaphore.Release();
}
} }
/// <summary> /// <summary>
@@ -111,33 +180,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action<NetEaseLoginState>? onStateChanged = null, Action<NetEaseLoginState>? onStateChanged = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
if (string.IsNullOrEmpty(Cookie)) if (!await LoginAsync(onQrCodeReady, onStateChanged, cancellationToken))
{ {
var loginResponse = await LoginViqQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken);
Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
CsrfToken = loginResponse.csrfToken ?? string.Empty;
if (string.IsNullOrEmpty(Cookie))
{
// 登录没成(用户取消、二维码过期),直接失败,不要再拿空 Cookie 去请求歌单。
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); 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(); cancellationToken.ThrowIfCancellationRequested();
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16); var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey); var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
var response = await _warpHttpClient.PostAsync<GetMusicInfoFromNetEaseMusicSongListResponse>( 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 =>
{ {
request.Headers.Add("Cookie", Cookie); request.Headers.Add("Cookie", session.Cookie);
request.Content = new FormUrlEncodedContent(HandleRequest(new request.Content = new FormUrlEncodedContent(HandleRequest(new
{ {
csrf_token = CsrfToken, csrf_token = session.CsrfToken,
id = songId, id = songId,
n = 1000, n = 1000,
offset = 0, offset = 0,
@@ -145,7 +208,8 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
limit = 1000, limit = 1000,
}, secretKey, encSecKey)); }, secretKey, encSecKey));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}); }, cancellationToken: cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
if (response.Code != 200 || response.PlayList?.SongList == null) if (response.Code != 200 || response.PlayList?.SongList == null)
{ {
@@ -164,18 +228,25 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
} }
var musicInfoList = new List<MusicInfo>(); var musicInfoList = new List<MusicInfo>();
foreach (var songListId in songListIds.Split(';', StringSplitOptions.RemoveEmptyEntries)) foreach (var songListId in songListIds.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
_logger.LogInformation("正在获取歌单 {SongListId} 的歌曲列表。", songListId); var musicInfos = await GetMusicInfoBySongIdAsync(songListId, cancellationToken);
var musicInfos = await GetMusicInfoBySongIdAsync(songListId);
musicInfoList.AddRange(musicInfos); musicInfoList.AddRange(musicInfos);
} }
return musicInfoList; return musicInfoList;
} }
private (string Cookie, string CsrfToken, long Version) GetLoginState()
{
lock (_loginStateLock)
{
return (_cookie, _csrfToken, _loginStateVersion);
}
}
/// <summary> /// <summary>
/// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。 /// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。
/// </summary> /// </summary>
@@ -204,24 +275,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </param> /// </param>
/// <param name="onStateChanged">登录状态变化回调。</param> /// <param name="onStateChanged">登录状态变化回调。</param>
/// <param name="cancellationToken">取消令牌。</param> /// <param name="cancellationToken">取消令牌。</param>
private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync( private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViaQrCodeAsync(
Action<NetEaseQrCodePayload>? onQrCodeReady, Action<NetEaseQrCodePayload>? onQrCodeReady,
Action<NetEaseLoginState>? onStateChanged, Action<NetEaseLoginState>? onStateChanged,
CancellationToken cancellationToken) CancellationToken cancellationToken = default)
{ {
// Get unikey. using var keyResponse = await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
var qrCodeKeyJson = await (await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
{ {
type = 1 type = 1
})).Content.ReadAsStringAsync(cancellationToken); }, cancellationToken: cancellationToken);
var uniKey = JObject.Parse(qrCodeKeyJson).SelectToken("$.unikey")!.Value<string>(); var keyResponseJson = JObject.Parse(await keyResponse.Content.ReadAsStringAsync(cancellationToken));
if (string.IsNullOrEmpty(uniKey)) return (null, null); var uniKey = keyResponseJson.Value<string>("unikey");
if (keyResponseJson.Value<int?>("code") != 200 || string.IsNullOrEmpty(uniKey))
{
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
// Generate QR code. using var qrGenerator = new QRCodeGenerator();
var qrGenerator = new QRCodeGenerator();
var qrContent = $"{Host}/login?codekey={uniKey}"; var qrContent = $"{Host}/login?codekey={uniKey}";
var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L); using var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L);
var asciiQrCodeString = new AsciiQRCode(qrCodeData).GetGraphic(1, drawQuietZones: false); using var qrCode = new AsciiQRCode(qrCodeData);
var asciiQrCodeString = qrCode.GetGraphic(1, drawQuietZones: false);
if (onQrCodeReady != null) if (onQrCodeReady != null)
{ {
@@ -233,7 +307,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
_logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString); _logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString);
} }
// Wait for login success. onStateChanged?.Invoke(NetEaseLoginState.Waiting);
var lastState = NetEaseLoginState.Waiting; var lastState = NetEaseLoginState.Waiting;
while (true) while (true)
{ {
@@ -241,7 +315,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken); var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken);
if (state != lastState) if (state != lastState && state != NetEaseLoginState.Succeeded)
{ {
lastState = state; lastState = state;
onStateChanged?.Invoke(state); onStateChanged?.Invoke(state);
@@ -264,13 +338,13 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
private async Task<(NetEaseLoginState state, CookieContainer? cookieContainer)> CheckIsLoginAsync( private async Task<(NetEaseLoginState state, CookieContainer? cookieContainer)> CheckIsLoginAsync(
string uniKey, string uniKey,
CancellationToken cancellationToken) 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, key = uniKey,
type = 1 type = 1
}); }, cancellationToken: cancellationToken);
var responseString = await responseMessage.Content.ReadAsStringAsync(cancellationToken); var responseString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
var responseCode = JObject.Parse(responseString)["code"]?.Value<int>(); var responseCode = JObject.Parse(responseString)["code"]?.Value<int>();
@@ -280,17 +354,19 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
// 800 二维码过期、801 等待扫码、802 已扫码待确认、803 登录成功。 // 800 二维码过期、801 等待扫码、802 已扫码待确认、803 登录成功。
case 800: case 800:
return (NetEaseLoginState.Expired, null); return (NetEaseLoginState.Expired, null);
case 801:
return (NetEaseLoginState.Waiting, null);
case 802: case 802:
return (NetEaseLoginState.ScanConfirmed, null); return (NetEaseLoginState.ScanConfirmed, null);
case 803: case 803:
break; break;
default: default:
return (NetEaseLoginState.Waiting, null); throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
} }
if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies)) if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies))
{ {
return (NetEaseLoginState.Waiting, null); throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
} }
var cookieContainer = new CookieContainer(); var cookieContainer = new CookieContainer();
@@ -299,6 +375,11 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
cookieContainer.SetCookies(new Uri(Host), cookie); cookieContainer.SetCookies(new Uri(Host), cookie);
} }
if (cookieContainer.GetCookies(new Uri(Host)).Count == 0)
{
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
return (NetEaseLoginState.Succeeded, cookieContainer); return (NetEaseLoginState.Succeeded, cookieContainer);
} }
@@ -307,19 +388,34 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </summary> /// </summary>
/// <param name="url">需要请求的网易云音乐 API 地址。</param> /// <param name="url">需要请求的网易云音乐 API 地址。</param>
/// <param name="params">API 请求参数。</param> /// <param name="params">API 请求参数。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns> /// <returns>
/// 正常情况下会返回一个 <see cref="HttpResponseMessage"/> 对象。 /// 正常情况下会返回一个 <see cref="HttpResponseMessage"/> 对象。
/// </returns> /// </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 secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey); var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
return await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption: var response = await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption:
request => request =>
{ {
request.Content = new FormUrlEncodedContent(HandleRequest(@params, secretKey, encSecKey)); request.Content = new FormUrlEncodedContent(HandleRequest(@params, secretKey, encSecKey));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}); }, cancellationToken: cancellationToken);
try
{
response.EnsureSuccessStatusCode();
cancellationToken.ThrowIfCancellationRequested();
return response;
}
catch
{
response.Dispose();
throw;
}
} }
} }
@@ -27,4 +27,16 @@
<Compile Remove="Lyrics\Providers\Kugeci\KugeciDownloader.cs"/> <Compile Remove="Lyrics\Providers\Kugeci\KugeciDownloader.cs"/>
</ItemGroup> </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> </Project>
+2 -6
View File
@@ -7,11 +7,7 @@
<FluentTheme /> <FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/> <StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
<!-- <!-- 统一按钮尺寸与文字对齐方式。 -->
按钮排版统一:Fluent 默认的 14px/偏大内边距在中文界面里显得松散,而且
带图标的按钮和纯文字按钮高度对不齐。这里把字号、内边距、圆角、最小高度
统一成一套,让所有页面的按钮共用同一套度量。
-->
<Style Selector="Button"> <Style Selector="Button">
<Setter Property="FontSize" Value="13" /> <Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="16,6" /> <Setter Property="Padding" Value="16,6" />
@@ -33,7 +29,7 @@
<Setter Property="Height" Value="14" /> <Setter Property="Height" Value="14" />
</Style> </Style>
<!-- Compact icon-only button used by the reorder arrows in the settings list --> <!-- 设置列表中的紧凑图标按钮。 -->
<Style Selector="Button.icon"> <Style Selector="Button.icon">
<Setter Property="Background" Value="Transparent" /> <Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" /> <Setter Property="BorderThickness" Value="0" />
@@ -1,58 +1,24 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!-- 裁剪时保留通过反射、序列化及系统无障碍接口访问的程序集。 -->
Root descriptor for the trimmer, used only when PublishTrimmed is on.
Everything listed here is code the trimmer cannot see being used, because it is
reached through reflection at runtime rather than through a static call.
See the comments in ZonyLrcTools.Desktop.csproj for why each assembly is here.
-->
<linker> <linker>
<!-- <!-- 自动注入依赖扫描程序集中的服务类型。 -->
AutoDependencyInjectExtensions scans this assembly with Assembly.GetTypes() and registers
whatever implements ITransientDependency / ISingletonDependency. The trimmer cannot prove
those 20+ types are ever instantiated, so without this root a trimmed build starts fine and
then throws "No service for type ... has been registered" the moment a page asks for one.
-->
<assembly fullname="ZonyLrcTools.Common" preserve="all" /> <assembly fullname="ZonyLrcTools.Common" preserve="all" />
<!-- <!-- 保留桌面服务及界面绑定使用的类型。 -->
Same reason, plus System.Text.Json deserialisation of NetEaseSession / KugouDatabaseSetting
in NetEaseSessionStore and KugouDatabaseStore: the trimmer would drop the setters it cannot
see being called.
-->
<assembly fullname="ZonyLrcTools.Desktop" preserve="all" /> <assembly fullname="ZonyLrcTools.Desktop" preserve="all" />
<!-- <!-- Avalonia 的无障碍节点通过运行时查找创建。 -->
Avalonia resolves automation peers by name when Windows UI Automation asks for a node.
Trimming removes those peer types because nothing statically references them, and the visible
symptom is a running window whose UIA tree is empty — screen readers, Narrator and every
UI-automation script see a blank shell. Preserving the peer namespace keeps accessibility and
testability intact.
-->
<assembly fullname="Avalonia.Controls" preserve="all" /> <assembly fullname="Avalonia.Controls" preserve="all" />
<assembly fullname="Avalonia.Controls.DataGrid" preserve="all" /> <assembly fullname="Avalonia.Controls.DataGrid" preserve="all" />
<!-- <!-- Windows 无障碍提供程序还会通过 COM 激活。 -->
The UIA provider that Windows talks to lives in the Win32 backend, and it is reached through
COM activation rather than through a static reference, so it needs the same treatment as the
peers above. Without this the window still renders but Windows UI Automation enumerates zero
children, which silently breaks Narrator and every automation script.
-->
<assembly fullname="Avalonia.Win32" preserve="all" /> <assembly fullname="Avalonia.Win32" preserve="all" />
<assembly fullname="Avalonia.Base" preserve="all" /> <assembly fullname="Avalonia.Base" preserve="all" />
<!-- <!-- 保留配置映射、音频元数据、解密及 SQLite 运行时加载所需类型。 -->
The remaining libraries all build their behaviour on reflection over types the trimmer cannot
follow: YamlDotNet walks GlobalOptions by property name, Newtonsoft.Json (used by Common's
text providers) maps JSON onto model classes, TagLibSharp reads audio tags, MusicDecrypto
creates decryptors from a factory, and SQLitePCLRaw loads its provider by reflection.
These are small (a few hundred KB each) next to the framework assemblies that trimming really
does remove, so rooting them costs little and removes a whole class of "works until you use it"
failures.
-->
<assembly fullname="YamlDotNet" preserve="all" /> <assembly fullname="YamlDotNet" preserve="all" />
<assembly fullname="Newtonsoft.Json" preserve="all" /> <assembly fullname="Newtonsoft.Json" preserve="all" />
<assembly fullname="TagLibSharp" preserve="all" /> <assembly fullname="TagLibSharp" preserve="all" />
<!-- The NuGet package is MusicDecrypto.Library, but the assembly it ships is libmusicdecrypto. --> <!-- MusicDecrypto.Library 包中的程序集名为 libmusicdecrypto。 -->
<assembly fullname="libmusicdecrypto" preserve="all" /> <assembly fullname="libmusicdecrypto" preserve="all" />
<assembly fullname="QRCoder" preserve="all" /> <assembly fullname="QRCoder" preserve="all" />
<assembly fullname="SQLitePCLRaw.core" preserve="all" /> <assembly fullname="SQLitePCLRaw.core" preserve="all" />
@@ -1,14 +1,7 @@
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary> /// <summary>解析桌面应用的配置目录。</summary>
/// Resolves the directories the desktop application reads and writes at runtime. /// <remarks>优先使用便携目录;不可写时回退到当前用户的应用数据目录。</remarks>
/// </summary>
/// <remarks>
/// The application prefers a portable layout: settings live next to the executable so the
/// whole folder can be copied to a USB stick and moved between machines. If that directory
/// is read-only (installed under Program Files, or launched from a read-only mount), it falls
/// back to %AppData%\ZonyLrcTools instead of silently losing every setting the user changes.
/// </remarks>
public static class AppPaths public static class AppPaths
{ {
private const string ApplicationFolderName = "ZonyLrcTools"; private const string ApplicationFolderName = "ZonyLrcTools";
@@ -16,20 +9,13 @@ public static class AppPaths
private static readonly Lazy<string> LazyConfigDirectory = new(ResolveConfigDirectory); private static readonly Lazy<string> LazyConfigDirectory = new(ResolveConfigDirectory);
/// <summary> /// <summary>配置文件所在目录。</summary>
/// Directory that holds <c>config.yaml</c>.
/// </summary>
public static string ConfigDirectory => LazyConfigDirectory.Value; public static string ConfigDirectory => LazyConfigDirectory.Value;
/// <summary> /// <summary>配置文件的完整路径。</summary>
/// Full path of the writable <c>config.yaml</c>.
/// </summary>
public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName); public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName);
/// <summary> /// <summary>首次启动时将随程序附带的配置复制到用户目录。</summary>
/// Copy the template shipped next to the executable into the config directory when the
/// user does not have a settings file yet. Safe to call on every startup.
/// </summary>
public static void EnsureConfigFile() public static void EnsureConfigFile()
{ {
if (File.Exists(ConfigFilePath)) if (File.Exists(ConfigFilePath))
@@ -46,7 +32,7 @@ public static class AppPaths
if (string.Equals( if (string.Equals(
Path.GetFullPath(template), Path.GetFullPath(template),
Path.GetFullPath(ConfigFilePath), Path.GetFullPath(ConfigFilePath),
StringComparison.OrdinalIgnoreCase)) OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{ {
return; return;
} }
@@ -57,7 +43,7 @@ public static class AppPaths
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// A missing config file is not fatal: the options binder falls back to defaults. // 模板无法复制时由调用方处理缺失配置。
} }
} }
@@ -82,7 +68,7 @@ public static class AppPaths
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// Fall through to the portable path; reading still works even when writing does not. // 没有可写目录时仍允许读取便携目录的配置。
} }
return baseDirectory; return baseDirectory;
@@ -5,13 +5,10 @@ using ZonyLrcTools.Common.Infrastructure.DependencyInject;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary>桌面配置服务注册。</summary>
public static class ConfigurationServiceCollectionExtensions public static class ConfigurationServiceCollectionExtensions
{ {
/// <summary> /// <summary>从可写配置目录加载配置并注册设置存储。</summary>
/// Bind <see cref="GlobalOptions"/> from the writable settings file resolved by
/// <see cref="AppPaths"/>, instead of the read-only folder next to the executable that
/// <see cref="ServiceCollectionExtensions.ConfigureConfiguration"/> uses.
/// </summary>
public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services) public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services)
{ {
AppPaths.EnsureConfigFile(); AppPaths.EnsureConfigFile();
@@ -2,38 +2,28 @@ using ZonyLrcTools.Common.Configuration;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary> /// <summary>设置保存结果。</summary>
/// Result of a settings persist operation. /// <param name="IsSuccess">是否保存成功。</param>
/// </summary> /// <param name="FilePath">保存成功的文件路径。</param>
/// <param name="IsSuccess">Whether the settings were written to disk.</param> /// <param name="ErrorMessage">保存失败的原因。</param>
/// <param name="FilePath">The file that was written, when the write succeeded.</param>
/// <param name="ErrorMessage">Human readable reason when the write failed.</param>
public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage) public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage)
{ {
/// <summary>创建保存成功的结果。</summary>
public static SettingsSaveResult Success(string filePath) => new(true, filePath, null); public static SettingsSaveResult Success(string filePath) => new(true, filePath, null);
/// <summary>创建保存失败的结果。</summary>
public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage); public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage);
} }
/// <summary> /// <summary>统一管理共享配置及其持久化。</summary>
/// Single owner of the settings file: reads the bound <see cref="GlobalOptions"/> and writes it back
/// to <see cref="AppPaths.ConfigFilePath"/>.
/// </summary>
public interface ISettingsStore public interface ISettingsStore
{ {
/// <summary> /// <summary>应用共享配置,修改后对按操作读取配置的组件立即生效。</summary>
/// The live options instance shared by the whole application. Mutating it takes effect
/// immediately for components that read it per operation.
/// </summary>
GlobalOptions Options { get; } GlobalOptions Options { get; }
/// <summary> /// <summary>当前配置文件的完整路径。</summary>
/// Absolute path of the settings file currently in use.
/// </summary>
string ConfigFilePath { get; } string ConfigFilePath { get; }
/// <summary> /// <summary>保存界面管理的配置值,不覆盖无法安全修改的文件。</summary>
/// Serialize <see cref="Options"/> to YAML and replace the settings file atomically.
/// </summary>
Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default); Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default);
} }
@@ -2,33 +2,17 @@ using System.Text.Json;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary> /// <summary>保存本机手动选择的酷狗数据库路径。</summary>
/// Remembers a manually chosen Kugou database (<c>KGMusicV3.db</c>) path.
/// </summary>
/// <remarks>
/// This is machine state, not a user preference — it points at a file that happens to exist on
/// this computer. Keeping it out of <c>config.yaml</c> means the shipped configuration template
/// stays clean and CLI users never see a stray GUI-only key.
/// </remarks>
public sealed class KugouDatabaseStore public sealed class KugouDatabaseStore
{ {
private const string FileName = "kugou.database.json"; private const string FileName = "kugou.database.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
private readonly SemaphoreSlim _lock = new(1, 1); private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary> /// <summary>本机状态文件的完整路径。</summary>
/// Full path of the settings file.
/// </summary>
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
/// <summary> /// <summary>读取数据库路径;文件缺失或损坏时返回空。</summary>
/// Load the stored database path, or <c>null</c> when there is none / it cannot be read.
/// </summary>
public async Task<string?> LoadAsync(CancellationToken cancellationToken = default) public async Task<string?> LoadAsync(CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
@@ -40,13 +24,13 @@ public sealed class KugouDatabaseStore
} }
var json = await File.ReadAllTextAsync(FilePath, cancellationToken); var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
var stored = JsonSerializer.Deserialize<KugouDatabaseSetting>(json); var stored = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.KugouDatabaseSetting);
return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath; return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath;
} }
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
{ {
// A corrupt cache must never block the application; fall back to auto detection. // 缓存损坏时恢复自动查找。
return null; return null;
} }
finally finally
@@ -55,24 +39,19 @@ public sealed class KugouDatabaseStore
} }
} }
/// <summary> /// <summary>保存数据库路径。</summary>
/// Persist the chosen database path.
/// </summary>
public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default) public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
try try
{ {
Directory.CreateDirectory(AppPaths.ConfigDirectory);
var setting = new KugouDatabaseSetting { DatabasePath = databasePath }; var setting = new KugouDatabaseSetting { DatabasePath = databasePath };
var temporaryPath = FilePath + ".tmp"; await DesktopStateFile.WriteAsync(FilePath, setting,
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(setting, JsonOptions), cancellationToken); DesktopStateJsonContext.Default.KugouDatabaseSetting, ownerOnly: false, cancellationToken);
File.Move(temporaryPath, FilePath, overwrite: true);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// Losing this only costs the user one extra pick next launch. // 缓存写入失败不影响本次使用。
} }
finally finally
{ {
@@ -80,9 +59,7 @@ public sealed class KugouDatabaseStore
} }
} }
/// <summary> /// <summary>忘记手动路径,恢复自动查找。</summary>
/// Forget the stored path so auto detection takes over again.
/// </summary>
public async Task ClearAsync(CancellationToken cancellationToken = default) public async Task ClearAsync(CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
@@ -95,7 +72,7 @@ public sealed class KugouDatabaseStore
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// Nothing actionable. // 调用方仍可使用本次自动查找结果。
} }
finally finally
{ {
@@ -104,10 +81,9 @@ public sealed class KugouDatabaseStore
} }
} }
/// <summary> /// <summary>酷狗数据库路径的持久化格式。</summary>
/// The persisted shape of <see cref="KugouDatabaseStore"/>.
/// </summary>
public sealed class KugouDatabaseSetting public sealed class KugouDatabaseSetting
{ {
/// <summary>数据库的完整路径。</summary>
public string DatabasePath { get; set; } = string.Empty; public string DatabasePath { get; set; } = string.Empty;
} }
@@ -1,40 +1,24 @@
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary> /// <summary>持久化网易云登录会话。</summary>
/// Persists the NetEase Cloud Music login state (cookie + csrf token) so the QR login dialog /// <remarks>会话属于登录凭据;Unix 文件仅限当前用户读写,Windows 继承目录权限。</remarks>
/// does not reappear on every launch.
/// </summary>
/// <remarks>
/// The cookie is a bearer credential: whoever holds it is logged in as the user. It is written
/// next to the settings file with owner-only permissions where the platform supports it, and
/// the file is small and plain JSON so a user can delete it by hand to force a re-login.
/// </remarks>
public sealed class NetEaseSessionStore public sealed class NetEaseSessionStore
{ {
private const string FileName = "netease.session.json"; private const string FileName = "netease.session.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
private readonly SemaphoreSlim _lock = new(1, 1); private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary> /// <summary>会话文件的完整路径。</summary>
/// Full path of the session file.
/// </summary>
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
/// <summary> /// <summary>是否存在已保存的会话。</summary>
/// Whether a stored session exists on disk.
/// </summary>
public bool HasStoredSession => File.Exists(FilePath); public bool HasStoredSession => File.Exists(FilePath);
/// <summary> /// <summary>读取会话;文件缺失或损坏时返回空。</summary>
/// Load the stored session, or <c>null</c> when there is none / it cannot be read.
/// </summary>
public async Task<NetEaseSession?> LoadAsync(CancellationToken cancellationToken = default) public async Task<NetEaseSession?> LoadAsync(CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
@@ -44,15 +28,19 @@ public sealed class NetEaseSessionStore
{ {
return null; return null;
} }
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(FilePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
var json = await File.ReadAllTextAsync(FilePath, cancellationToken); var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
var session = JsonSerializer.Deserialize<NetEaseSession>(json); var session = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.NetEaseSession);
return string.IsNullOrEmpty(session?.Cookie) ? null : session; return string.IsNullOrEmpty(session?.Cookie) ? null : session;
} }
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
{ {
// A corrupt session cache must never block the application; treat it as "not logged in". // 损坏的缓存按未登录处理。
return null; return null;
} }
finally finally
@@ -61,23 +49,18 @@ public sealed class NetEaseSessionStore
} }
} }
/// <summary> /// <summary>保存会话。</summary>
/// Write the session to disk.
/// </summary>
public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default) public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
try try
{ {
Directory.CreateDirectory(AppPaths.ConfigDirectory); await DesktopStateFile.WriteAsync(FilePath, session,
DesktopStateJsonContext.Default.NetEaseSession, ownerOnly: true, cancellationToken);
var temporaryPath = FilePath + ".tmp";
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(session, JsonOptions), cancellationToken);
File.Move(temporaryPath, FilePath, overwrite: true);
} }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{ {
// Losing the cache only costs the user one extra scan next launch. // 缓存写入失败不影响本次会话。
} }
finally finally
{ {
@@ -85,23 +68,15 @@ public sealed class NetEaseSessionStore
} }
} }
/// <summary> /// <summary>删除已保存的会话。</summary>
/// Delete the stored session.
/// </summary>
public async Task ClearAsync(CancellationToken cancellationToken = default) public async Task ClearAsync(CancellationToken cancellationToken = default)
{ {
await _lock.WaitAsync(cancellationToken); await _lock.WaitAsync(cancellationToken);
try try
{ {
if (File.Exists(FilePath)) cancellationToken.ThrowIfCancellationRequested();
{
File.Delete(FilePath); File.Delete(FilePath);
} }
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing actionable; the in-memory state is cleared regardless.
}
finally finally
{ {
_lock.Release(); _lock.Release();
@@ -109,14 +84,58 @@ public sealed class NetEaseSessionStore
} }
} }
/// <summary> /// <summary>网易云登录凭据。</summary>
/// The bits of a NetEase login that are worth keeping between runs.
/// </summary>
public sealed class NetEaseSession public sealed class NetEaseSession
{ {
/// <summary>登录 Cookie。</summary>
public string Cookie { get; set; } = string.Empty; public string Cookie { get; set; } = string.Empty;
/// <summary>请求校验令牌。</summary>
public string CsrfToken { get; set; } = string.Empty; public string CsrfToken { get; set; } = string.Empty;
public DateTimeOffset SavedAt { get; set; } = DateTimeOffset.Now; /// <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);
}
}
} }
@@ -4,22 +4,10 @@ using YamlDotNet.Serialization.EventEmitters;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary> /// <summary>将含控制字符的文本输出为单行双引号标量。</summary>
/// Forces every control-character scalar onto a single double-quoted line.
/// </summary>
/// <remarks>
/// <para>
/// YamlDotNet renders a value such as <c>"\n"</c> as the folded block scalar <c>&gt;2</c>, which is
/// technically legal YAML but reads as garbage to anyone opening <c>config.yaml</c> by hand and
/// contradicts the documentation that describes <c>lineBreak</c> as an escape sequence.
/// </para>
/// <para>
/// This emitter only changes presentation: the value that survives a round trip is identical,
/// it just comes back as <c>lineBreak: "\n"</c> instead of a folded block.
/// </para>
/// </remarks>
public sealed class QuotedScalarEventEmitter : ChainedEventEmitter public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
{ {
/// <summary>创建标量输出器。</summary>
public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter)
{ {
} }
@@ -45,7 +33,7 @@ public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
} }
} }
// Leading or trailing whitespace is silently trimmed by the plain-scalar reader. // 保留首尾空格,避免普通标量读取时丢失。
return text.Length > 0 && (text[0] == ' ' || text[^1] == ' '); return text.Length > 0 && (text[0] == ' ' || text[^1] == ' ');
} }
} }
@@ -1,6 +1,9 @@
using System.Globalization; using System.Globalization;
using System.Text; using System.Text;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization; using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NamingConventions;
using ZonyLrcTools.Common.Configuration; using ZonyLrcTools.Common.Configuration;
@@ -8,29 +11,17 @@ using ZonyLrcTools.Common.Configuration;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <inheritdoc cref="ISettingsStore" /> /// <inheritdoc cref="ISettingsStore" />
/// <remarks> /// <remarks>只修改界面管理的值,保留其他配置和注释;无法安全修改时返回错误。</remarks>
/// <para>
/// Saving must not destroy the hand-written comments in <c>config.yaml</c>: that file is the
/// documented configuration surface of this project, and a full re-serialize flattens it into an
/// unreadable machine blob on the very first checkbox click.
/// </para>
/// <para>
/// So the store patches the values it owns in place, line by line, and only falls back to a full
/// re-serialize when the on-disk text no longer round-trips to the intended values. The patched
/// text is parsed back and compared before it is committed, so a bad patch can never overwrite a
/// working configuration.
/// </para>
/// </remarks>
public sealed class SettingsStore : ISettingsStore, IDisposable public sealed class SettingsStore : ISettingsStore, IDisposable
{ {
private const string RegeneratedHeaderText = private const string RegeneratedHeaderText = "# ZonyLrcTools X 配置文件";
"# 此文件由 ZonyLrcTools X 重新生成:原有的注释已丢失,你可以参照文档重新补充。";
private readonly ISerializer _serializer; private readonly ISerializer _serializer;
private readonly IDeserializer _deserializer; private readonly IDeserializer _deserializer;
private readonly SemaphoreSlim _writeLock = new(1, 1); private readonly SemaphoreSlim _writeLock = new(1, 1);
private bool _disposed; private bool _disposed;
/// <summary>使用应用共享配置创建设置存储。</summary>
public SettingsStore(IOptions<GlobalOptions> options) public SettingsStore(IOptions<GlobalOptions> options)
{ {
Options = options.Value; Options = options.Value;
@@ -38,7 +29,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
_serializer = new SerializerBuilder() _serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance) .WithNamingConvention(CamelCaseNamingConvention.Instance)
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
// Keep "\n" readable instead of letting YamlDotNet emit the folded block scalar ">2". // 换行符保持双引号转义形式,便于手工编辑。
.WithEventEmitter(next => new QuotedScalarEventEmitter(next)) .WithEventEmitter(next => new QuotedScalarEventEmitter(next))
.Build(); .Build();
@@ -73,12 +64,19 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
} }
// Write to a sibling temp file first so a crash mid-write cannot truncate the // 使用独立临时文件,避免多个进程互相截断写入。
// settings the user already had. var tempPath = targetPath + $".{Guid.NewGuid():N}.tmp";
var tempPath = targetPath + ".tmp"; try
{
await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken) await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
.ConfigureAwait(false); .ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
File.Move(tempPath, targetPath, overwrite: true); File.Move(tempPath, targetPath, overwrite: true);
}
finally
{
File.Delete(tempPath);
}
return SettingsSaveResult.Success(targetPath); return SettingsSaveResult.Success(targetPath);
} }
@@ -96,20 +94,11 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
} }
} }
/// <summary> /// <summary>按 YAML 节点位置修改配置;仅文件不存在时允许重新生成。</summary>
/// Rewrites only the managed scalar values in place, keeping every comment and blank line.
/// Returns <c>null</c> when the file is missing or the patched text does not read back as the
/// intended configuration.
/// </summary>
/// <remarks>
/// A managed key does not need its own line to be "correct": <c>config.yaml</c> ships with
/// <c># depth: 10</c> commented out for QQ, and the default it falls back to is exactly the
/// value the GUI wants. The round-trip check below is therefore the only gate that matters.
/// </remarks>
private async Task<string?> TryPatchInPlaceAsync( private async Task<string?> TryPatchInPlaceAsync(
string path, string path,
IReadOnlyDictionary<string, string> managed, IReadOnlyDictionary<string, string> managed,
CancellationToken cancellationToken) CancellationToken cancellationToken = default)
{ {
if (!File.Exists(path)) if (!File.Exists(path))
{ {
@@ -117,20 +106,18 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
} }
var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(original)) var patched = PatchText(original, managed);
if (!VerifyRoundTrip(patched, managed))
{ {
return null; throw new InvalidDataException("无法安全修改配置文件,请检查 YAML 内容。原文件未更改。");
} }
var patched = PatchText(original, managed); return patched;
return VerifyRoundTrip(patched, managed) ? patched : null;
} }
private string BuildFromScratch() private string BuildFromScratch()
{ {
// Materialize the same managed values the patch path would have written, so the two // 新文件使用统一的 LF 行尾。
// paths cannot disagree about what "saved" means.
// YamlDotNet 输出统一是 "\n",这里显式拼同一套行尾,避免首行注释与正文混用 CRLF/LF。
var body = _serializer.Serialize(Options); var body = _serializer.Serialize(Options);
return RegeneratedHeaderText + "\n" + body; return RegeneratedHeaderText + "\n" + body;
} }
@@ -161,7 +148,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
} }
} }
/// <summary>Reads the value of a managed path back out of a deserialized options instance.</summary> /// <summary>读取反序列化后的受管配置值。</summary>
private static string? ReadScalar(GlobalOptions options, string path) private static string? ReadScalar(GlobalOptions options, string path)
{ {
if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal)) if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal))
@@ -217,7 +204,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
"networkOptions.ip" => options.NetworkOptions?.Ip, "networkOptions.ip" => options.NetworkOptions?.Ip,
"networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture), "networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture),
"provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine), "provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine),
// Line breaks must not be trimmed: "\n" and "" are different configurations. // 换行符不能去除空白。
"provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak, "provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak,
"provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation), "provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation),
"provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation), "provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation),
@@ -229,7 +216,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
}; };
} }
/// <summary>Canonical text for a boolean, so "True" and "true" compare equal.</summary> /// <summary>统一布尔值的文本形式。</summary>
private static string Normalize(bool value) => value ? "true" : "false"; 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(bool? value) => value.HasValue ? Normalize(value.Value) : null;
@@ -242,188 +229,142 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
_ => raw _ => raw
}; };
/// <summary> /// <summary>用解析器的位置替换标量,保留流式映射、注释和未管理的字段。</summary>
/// Walks the YAML text, tracking the current key path by indentation, and replaces only the
/// value part of lines whose full path is managed. Trailing comments are preserved verbatim.
/// </summary>
private static string PatchText(string original, IReadOnlyDictionary<string, string> managed) 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"; var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
var lines = original.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); foreach (var (mapping, fields) in additions)
var stack = new List<(int Indent, string Path)>();
var replaced = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < lines.Length; i++)
{ {
var raw = lines[i]; if (mapping.Style == MappingStyle.Flow)
var trimmed = raw.TrimStart();
if (trimmed.Length == 0 || trimmed.StartsWith('#'))
{ {
continue; // 在首个键之前插入;空映射则插入到左花括号之后。
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 indent = raw.Length - trimmed.Length;
// Leave the previous sibling scope as soon as the indentation goes back out.
while (stack.Count > 0 && stack[^1].Indent >= indent)
{ {
stack.RemoveAt(stack.Count - 1); var first = mapping.Children.First().Key;
} var indent = new string(' ', (int)first.Start.Column - 1);
var text = string.Join(newline + indent,
var parent = stack.Count > 0 ? stack[^1].Path : string.Empty; fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}"));
edits.Add(((int)first.Start.Index, (int)first.Start.Index, text + newline + indent));
// List element header, e.g. " - name: NetEase # 基于网易云的歌词下载器。"
if (trimmed.StartsWith("- name:", StringComparison.Ordinal))
{
var name = ReadToken(trimmed["- name:".Length..]);
if (name.Length > 0)
{
stack.Add((indent, $"{parent}[{name}]"));
}
continue;
}
var colon = trimmed.IndexOf(':');
if (colon <= 0)
{
continue;
}
var key = trimmed[..colon].Trim();
if (key.Length == 0 || key.Contains(' ') || key.StartsWith('-'))
{
continue;
}
var rest = trimmed[(colon + 1)..];
var valuePart = ReadToken(rest);
var fullPath = parent.Length == 0 ? key : $"{parent}.{key}";
if (valuePart.Length == 0)
{
// Section header: children follow at a deeper indentation.
stack.Add((indent, fullPath));
continue;
}
if (!managed.TryGetValue(fullPath, out var newValue))
{
continue;
}
if (!replaced.Add(fullPath))
{
// 同一个键出现多次时只改第一处:改全部会让 YAML 里前一处生效、后一处变成
// 死键的语义更难理解,也让回读校验失去意义。留个注释说明这是有意为之。
continue;
}
// Preserve the exact column layout: the value span, then its trailing comment.
// config.yaml aligns its comments into columns, so a value that grew or shrank must
// absorb the difference in the padding rather than push the comment sideways.
var leadingSpaces = rest.Length - rest.TrimStart().Length;
var valueStart = indent + colon + 1 + leadingSpaces;
var comment = rest[(leadingSpaces + valuePart.Length)..];
var replacement = FormatScalar(newValue, valuePart);
if (comment.Length > 1 && comment[0] == ' ')
{
var commentColumn = valueStart + valuePart.Length + (comment.Length - comment.TrimStart().Length);
var padding = commentColumn - (valueStart + replacement.Length);
if (padding >= 1)
{
comment = new string(' ', padding) + comment.TrimStart();
} }
} }
lines[i] = raw[..valueStart] + replacement + comment; var builder = new StringBuilder(original);
} var nextStart = original.Length;
foreach (var edit in edits.OrderByDescending(edit => edit.Start))
return string.Join(newline, lines);
}
/// <summary>Reads the first YAML token, stopping at whitespace outside quotes.</summary>
private static string ReadToken(string text)
{ {
var s = text.TrimStart(); if (edit.End > nextStart)
if (s.Length == 0)
{ {
return string.Empty; throw new InvalidDataException("配置包含重叠的 YAML 别名,无法安全修改。");
}
builder.Remove(edit.Start, edit.End - edit.Start).Insert(edit.Start, edit.Text);
nextStart = edit.Start;
}
return builder.ToString();
} }
if (s[0] is '"' or '\'') private static string FormatValue(object value) => value is Dictionary<string, object> fields
{ ? "{ " + string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")) + " }"
var quote = s[0]; : QuoteScalar((string)value);
for (var i = 1; i < s.Length; i++)
{
if (s[i] == '\\' && quote == '"')
{
i++;
continue;
}
if (s[i] == quote) private static string QuoteScalar(string value) => "\"" + value
{
return s[..(i + 1)];
}
}
return s;
}
var end = 0;
while (end < s.Length && !char.IsWhiteSpace(s[end]))
{
end++;
}
return s[..end];
}
/// <summary>
/// Emits the new scalar in the shape the old one had: same quote character when the previous
/// value was quoted, double quotes when the value contains characters a plain scalar cannot
/// carry (the line-break value), plain otherwise.
/// </summary>
/// <remarks>
/// A value that merely looks like a boolean is left unquoted: "true" and "false" reach this
/// method both from boolean fields (where quoting would turn them into strings) and from
/// string fields (whose original spelling in the file was already quoted). Mirroring the
/// previous token's quoting therefore keeps both cases correct.
/// </remarks>
private static string FormatScalar(string value, string previous)
{
var mustQuote = value.Length == 0
|| value.Any(c => c is '\n' or '\r' or '\t' or '"' or '\\')
|| value != value.Trim();
if (!mustQuote)
{
if (previous.StartsWith('\'') && !value.Contains('\''))
{
return $"'{value}'";
}
if (previous.StartsWith('"'))
{
return $"\"{value}\"";
}
return value;
}
var escaped = value
.Replace("\\", "\\\\", StringComparison.Ordinal) .Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal) .Replace("\"", "\\\"", StringComparison.Ordinal)
.Replace("\r", "\\r", StringComparison.Ordinal) .Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal) .Replace("\n", "\\n", StringComparison.Ordinal)
.Replace("\t", "\\t", StringComparison.Ordinal); .Replace("\t", "\\t", StringComparison.Ordinal)
.Replace("\0", "\\0", StringComparison.Ordinal) + "\"";
return $"\"{escaped}\""; /// <summary>收集设置界面管理的配置路径和值。</summary>
}
/// <summary>Flattens the editable subset of <see cref="GlobalOptions"/> into path → scalar text.</summary>
private static Dictionary<string, string> BuildManagedScalars(GlobalOptions options) private static Dictionary<string, string> BuildManagedScalars(GlobalOptions options)
{ {
var managed = new Dictionary<string, string>(StringComparer.Ordinal); var managed = new Dictionary<string, string>(StringComparer.Ordinal);
@@ -484,10 +425,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
return managed; return managed;
} }
/// <summary> /// <summary>释放写入锁。</summary>
/// Releases the write lock. <see cref="SettingsStore" /> is a singleton, so this only runs at
/// shutdown, but the lock is a disposable handle and leaving it to finalization is sloppy.
/// </summary>
public void Dispose() public void Dispose()
{ {
if (_disposed) if (_disposed)
@@ -338,7 +338,7 @@
<value>Enable block word filtering</value> <value>Enable block word filtering</value>
</data> </data>
<data name="Settings_BlockWordPath" xml:space="preserve"> <data name="Settings_BlockWordPath" xml:space="preserve">
<value>Block word file path:</value> <value>Block Words File (relative to current working directory):</value>
</data> </data>
<data name="Settings_TagProvider" xml:space="preserve"> <data name="Settings_TagProvider" xml:space="preserve">
<value>Tag Providers</value> <value>Tag Providers</value>
@@ -436,6 +436,12 @@
<data name="NetEase_LoginSucceeded" xml:space="preserve"> <data name="NetEase_LoginSucceeded" xml:space="preserve">
<value>Signed in.</value> <value>Signed in.</value>
</data> </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"> <data name="Home_Features" xml:space="preserve">
<value>Features</value> <value>Features</value>
</data> </data>
@@ -338,7 +338,7 @@
<value>启用屏蔽词过滤</value> <value>启用屏蔽词过滤</value>
</data> </data>
<data name="Settings_BlockWordPath" xml:space="preserve"> <data name="Settings_BlockWordPath" xml:space="preserve">
<value>屏蔽词文件路径:</value> <value>屏蔽词文件路径(相对当前工作目录):</value>
</data> </data>
<data name="Settings_TagProvider" xml:space="preserve"> <data name="Settings_TagProvider" xml:space="preserve">
<value>标签源</value> <value>标签源</value>
@@ -436,6 +436,12 @@
<data name="NetEase_LoginSucceeded" xml:space="preserve"> <data name="NetEase_LoginSucceeded" xml:space="preserve">
<value>登录成功。</value> <value>登录成功。</value>
</data> </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"> <data name="Home_Features" xml:space="preserve">
<value>功能特性</value> <value>功能特性</value>
</data> </data>
@@ -2,6 +2,7 @@ using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage; using Avalonia.Platform.Storage;
using Avalonia.Threading;
using ZonyLrcTools.Desktop.ViewModels; using ZonyLrcTools.Desktop.ViewModels;
using ZonyLrcTools.Desktop.Views.Dialogs; using ZonyLrcTools.Desktop.Views.Dialogs;
@@ -24,17 +25,29 @@ public class DialogService : IDialogService
AllowMultiple = false AllowMultiple = false
}); });
return folders.FirstOrDefault()?.Path.LocalPath; return folders.FirstOrDefault()?.TryGetLocalPath();
} }
public async Task<string?> ShowFilePickerAsync(string title, string[]? filters = null) public async Task<string?> ShowFilePickerAsync(string title, string[]? filters = null)
{ {
var files = await ShowFilesPickerAsync(title, filters); if (MainWindow == null) return null;
return files.FirstOrDefault();
var files = await MainWindow.StorageProvider.OpenFilePickerAsync(
new FilePickerOpenOptions
{
Title = title,
AllowMultiple = false,
FileTypeFilter = BuildFileTypes(filters)
});
return files.FirstOrDefault()?.TryGetLocalPath();
} }
public async Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null) /// <inheritdoc />
public async Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null,
CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
if (MainWindow == null) return Array.Empty<string>(); if (MainWindow == null) return Array.Empty<string>();
var fileTypes = BuildFileTypes(filters); var fileTypes = BuildFileTypes(filters);
@@ -46,15 +59,17 @@ public class DialogService : IDialogService
AllowMultiple = true, AllowMultiple = true,
FileTypeFilter = fileTypes FileTypeFilter = fileTypes
}); });
cancellationToken.ThrowIfCancellationRequested();
return files return files
.Select(f => f.Path.LocalPath) .Select(f => f.TryGetLocalPath())
.OfType<string>()
.Where(p => !string.IsNullOrEmpty(p)) .Where(p => !string.IsNullOrEmpty(p))
.ToList(); .ToList();
} }
/// <summary> /// <summary>
/// Turn a list of bare extensions (".mp3", "mp3", "*.mp3") into Avalonia file type filters. /// 将文件扩展名转换为文件选择器筛选条件。
/// </summary> /// </summary>
private static List<FilePickerFileType>? BuildFileTypes(string[]? filters) private static List<FilePickerFileType>? BuildFileTypes(string[]? filters)
{ {
@@ -100,15 +115,19 @@ public class DialogService : IDialogService
await dialog.ShowDialog(MainWindow); await dialog.ShowDialog(MainWindow);
} }
public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel) /// <inheritdoc />
public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
if (MainWindow == null) if (MainWindow == null)
{ {
viewModel.RequestClose(); viewModel.NotifyClosed();
return; return;
} }
var dialog = new QrCodeLoginDialog(viewModel); var dialog = new QrCodeLoginDialog(viewModel);
using var registration = cancellationToken.Register(
() => Dispatcher.UIThread.Post(viewModel.RequestClose));
await dialog.ShowDialog(MainWindow); await dialog.ShowDialog(MainWindow);
} }
} }
@@ -8,16 +8,18 @@ public interface IDialogService
Task<string?> ShowFilePickerAsync(string title, string[]? filters = null); Task<string?> ShowFilePickerAsync(string title, string[]? filters = null);
Task<IReadOnlyList<string>> ShowFilesPickerAsync(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<bool> ShowConfirmDialogAsync(string title, string message);
Task ShowMessageAsync(string title, string message); Task ShowMessageAsync(string title, string message);
/// <summary> /// <summary>
/// Open the NetEase QR-code login dialog as a modal child of the main window. /// 显示网易云扫码登录对话框,关闭窗口后返回。
/// The returned task completes when the user or the login flow closes it; callers that
/// only want the dialog on screen can ignore it.
/// </summary> /// </summary>
Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel); Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default);
} }
@@ -8,13 +8,12 @@ public interface INavigationService
event EventHandler<ViewModelBase>? NavigationChanged; event EventHandler<ViewModelBase>? NavigationChanged;
/// <summary> /// <summary>
/// Push a page onto the navigation stack. Use for drill-down (detail pages, wizards). /// 打开页面并保留返回记录。
/// </summary> /// </summary>
TViewModel NavigateTo<TViewModel>() where TViewModel : ViewModelBase; TViewModel NavigateTo<TViewModel>() where TViewModel : ViewModelBase;
/// <summary> /// <summary>
/// Replace the whole stack with a single page. This is what the sidebar uses: switching /// 切换顶层页面并清空返回记录。
/// sections is not a back-navigable action, so the stack must not grow on every click.
/// </summary> /// </summary>
TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase; TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase;
@@ -24,7 +24,7 @@ public class NavigationService : INavigationService
if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel)) if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel))
{ {
// Already showing this page; do not restart it. // 当前页面无需重复激活。
return viewModel; return viewModel;
} }
@@ -40,6 +40,7 @@ public class NavigationService : INavigationService
return viewModel; return viewModel;
} }
/// <inheritdoc />
public TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase public TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase
{ {
var viewModel = _serviceProvider.GetRequiredService<TViewModel>(); var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
@@ -79,8 +80,7 @@ public class NavigationService : INavigationService
} }
/// <summary> /// <summary>
/// Page lifecycle hooks are fire-and-forget from the caller's perspective; an exception thrown /// 页面激活失败时不打断导航。
/// inside one must not tear down the navigation call that triggered it.
/// </summary> /// </summary>
private static async Task SafeActivateAsync(ViewModelBase viewModel) private static async Task SafeActivateAsync(ViewModelBase viewModel)
{ {
@@ -90,7 +90,7 @@ public class NavigationService : INavigationService
} }
catch (Exception) catch (Exception)
{ {
// A failing OnActivated must not crash navigation. // 页面自行处理错误,避免中断导航。
} }
} }
@@ -102,7 +102,7 @@ public class NavigationService : INavigationService
} }
catch (Exception) catch (Exception)
{ {
// A failing OnDeactivated must not crash navigation. // 页面自行处理错误,避免中断导航。
} }
} }
} }
@@ -21,9 +21,7 @@ public static class ServiceCollectionExtensions
services.BeginAutoDependencyInject<IWarpHttpClient>(); services.BeginAutoDependencyInject<IWarpHttpClient>();
// Configure Common services // Configure Common services
// ConfigureConfiguration() from Common always reads config.yaml from the executable // 桌面端使用可写的配置目录,避免只读安装位置导致保存失败。
// folder, which breaks portable installs and read-only install locations. The desktop
// app resolves a writable location first and binds from there instead.
services.ConfigureDesktopConfiguration(); services.ConfigureDesktopConfiguration();
services.ConfigureLocalization(); services.ConfigureLocalization();
services.ConfigureToolService(); services.ConfigureToolService();
@@ -43,10 +41,10 @@ public static class ServiceCollectionExtensions
services.AddSingleton<IDialogService, DialogService>(); services.AddSingleton<IDialogService, DialogService>();
services.AddSingleton<IThemeService, ThemeService>(); services.AddSingleton<IThemeService, ThemeService>();
// Stores the NetEase login cookie between launches so the QR dialog is a first-run event. // 保存网易云登录状态。
services.AddSingleton<NetEaseSessionStore>(); services.AddSingleton<NetEaseSessionStore>();
// Remembers a manually chosen KuGou database path (machine state, not a user preference). // 保存本机酷狗数据库路径。
services.AddSingleton<KugouDatabaseStore>(); services.AddSingleton<KugouDatabaseStore>();
// Register ViewModels (Singleton to preserve state across navigation) // Register ViewModels (Singleton to preserve state across navigation)
@@ -25,7 +25,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
private CancellationTokenSource? _downloadCts; private CancellationTokenSource? _downloadCts;
private readonly Dictionary<string, AlbumFileViewModel> _musicFileMap = new(); private readonly Dictionary<string, AlbumFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new(); private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty] [ObservableProperty]
private string? _selectedFolderPath; private string? _selectedFolderPath;
@@ -75,6 +75,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:"; public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:";
public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download"; public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download";
public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download"; public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download";
/// <summary>扫描进度提示。</summary>
public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files..."; public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files"; public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -142,23 +143,23 @@ public partial class AlbumDownloadViewModel : ViewModelBase
} }
[RelayCommand(CanExecute = nameof(CanSelectFolder))] [RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync() private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{ {
var folder = await _dialogService.ShowFolderPickerAsync( var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Album_SelectFolder"] ?? "Select Music Folder"); _localization?["Album_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return; if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder; SelectedFolderPath = folder;
await ScanFilesAsync(); await ScanFilesAsync(cancellationToken);
} }
private bool CanSelectFolder => !IsScanning && !IsDownloading; private bool CanSelectFolder => !IsScanning && !IsDownloading;
/// <summary> /// <summary>
/// Tag-read the folder the same way the lyrics page does: identical row set, so the user sees /// 扫描文件并读取音乐标签。
/// the same songs whichever feature they open first.
/// </summary> /// </summary>
private async Task ScanFilesAsync() private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{ {
if (string.IsNullOrEmpty(SelectedFolderPath)) return; if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -176,8 +177,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
try try
{ {
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions)) var files = (await Task.Run(
.ToList(); () => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0) if (files.Count == 0)
{ {
@@ -193,7 +195,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file => var scanTasks = files.Select(file =>
warpTask.RunAsync(async () => warpTask.RunAsync(async () =>
{ {
var musicInfo = await _tagLoader.LoadTagAsync(file); var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() => await Dispatcher.UIThread.InvokeAsync(() =>
{ {
@@ -215,12 +217,16 @@ public partial class AlbumDownloadViewModel : ViewModelBase
ScanProgressCount++; ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount; ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
}); });
})); }, cancellationToken));
await Task.WhenAll(scanTasks); await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count; TotalCount = MusicFiles.Count;
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex) catch (Exception ex)
{ {
await _dialogService.ShowMessageAsync( await _dialogService.ShowMessageAsync(
@@ -235,7 +241,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
} }
[RelayCommand(CanExecute = nameof(CanStartDownload))] [RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync() private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{ {
if (_scannedMusicInfos.Count == 0) return; if (_scannedMusicInfos.Count == 0) return;
@@ -252,7 +258,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
} }
_downloadCts = new CancellationTokenSource(); _downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try try
{ {
@@ -283,9 +289,15 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}, },
_downloadCts.Token); _downloadCts.Token);
} }
catch (OperationCanceledException) catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{ {
// User cancelled. // 用户取消下载。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
_localization?["Common_Error"] ?? "Error",
ex.Message);
} }
finally finally
{ {
@@ -302,6 +314,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
} }
} }
/// <summary>
/// 单个音乐文件的封面下载状态。
/// </summary>
public partial class AlbumFileViewModel : ObservableObject public partial class AlbumFileViewModel : ObservableObject
{ {
[ObservableProperty] [ObservableProperty]
@@ -10,6 +10,9 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// 音乐文件解密页面。
/// </summary>
public partial class DecryptViewModel : ViewModelBase public partial class DecryptViewModel : ViewModelBase
{ {
private const string KggExtension = ".kgg"; private const string KggExtension = ".kgg";
@@ -23,6 +26,13 @@ public partial class DecryptViewModel : ViewModelBase
private CancellationTokenSource? _decryptCts; private CancellationTokenSource? _decryptCts;
private bool _isInitialized; private bool _isInitialized;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
private bool _isInitializing;
[ObservableProperty] [ObservableProperty]
private int _parallelCount = 2; private int _parallelCount = 2;
@@ -42,13 +52,13 @@ public partial class DecryptViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))] [NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))] [NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))] [NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))] [NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
[NotifyPropertyChangedFor(nameof(CanClear))] [NotifyPropertyChangedFor(nameof(CanClear))]
private bool _isDecrypting; private bool _isDecrypting;
/// <summary> /// <summary>
/// True when the KuGou key database could not be read. kgg files cannot be decrypted without /// 是否可以读取酷狗解密密钥数据库。
/// it, so the page says so up front instead of letting every row fail with a wall of text.
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))] [NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))]
@@ -57,54 +67,78 @@ public partial class DecryptViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
private string _kugouDatabaseStatus = string.Empty; private string _kugouDatabaseStatus = string.Empty;
// Localized strings // 界面文案。
/// <summary>页面标题。</summary>
public string DecryptTitle => _localization?["Decrypt_Title"] ?? "Music Decryption"; 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"; 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..."; public string DecryptSelectFiles => _localization?["Decrypt_SelectFiles"] ?? "Select encrypted music files...";
/// <summary>添加文件按钮文案。</summary>
public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files..."; public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files...";
/// <summary>并行任务数标签。</summary>
public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:"; public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:";
/// <summary>开始解密按钮文案。</summary>
public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt"; public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt";
/// <summary>停止按钮文案。</summary>
public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop"; public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop";
/// <summary>文件列表为空时的提示。</summary>
public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting"; public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting";
/// <summary>清空按钮文案。</summary>
public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear"; public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear";
/// <summary>文件列表标签。</summary>
public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files"; public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files";
/// <summary>选择数据库按钮文案。</summary>
public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db..."; public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db...";
/// <summary>数据库缺失状态文案。</summary>
public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing"; public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing";
/// <summary>查看详情按钮文案。</summary>
public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details"; public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details";
/// <summary>失败详情窗口标题。</summary>
public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure"; public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure";
/// <summary> /// <summary>
/// Explanation shown in the warning strip. Kept as one sentence because the real condition is /// 酷狗数据库缺失时的提示。
/// simple: kgg needs the KuGou database, and that database only holds keys for songs KuGou
/// itself downloaded on this machine.
/// </summary> /// </summary>
public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"] public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"]
?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)"; ?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)";
/// <summary>是否显示数据库缺失提示。</summary>
public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable; public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable;
/// <summary> /// <summary>
/// Read-only summary shown in the picker text box: "3 files selected" rather than a path, /// 已选文件数量。
/// because this page takes a list, not a single location.
/// </summary> /// </summary>
public string SelectionSummary => Files.Count == 0 public string SelectionSummary => Files.Count == 0
? string.Empty ? string.Empty
: $"{Files.Count} {CommonFiles}"; : $"{Files.Count} {CommonFiles}";
/// <summary>总数标签。</summary>
public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
/// <summary>文件数量单位。</summary>
public string CommonFiles => _localization?["Common_Files"] ?? "files"; public string CommonFiles => _localization?["Common_Files"] ?? "files";
/// <summary>成功数量标签。</summary>
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:"; public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
/// <summary>失败数量标签。</summary>
public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:"; public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:";
/// <summary>文件名列标题。</summary>
public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name"; public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name";
/// <summary>输出路径列标题。</summary>
public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output"; public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output";
/// <summary>状态列标题。</summary>
public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
// 全部行都被 blocked 时按钮不该亮着,否则点下去只会空转一次。 /// <summary>是否存在可以开始解密的文件。</summary>
public bool CanStartDecrypt => !IsDecrypting && Files.Any(f => !f.IsBlocked); public bool CanStartDecrypt => !IsDecrypting && !IsInitializing && Files.Any(f => !f.IsBlocked);
/// <summary>文件列表是否为空。</summary>
public bool HasNoFiles => Files.Count == 0; public bool HasNoFiles => Files.Count == 0;
/// <summary>待解密文件列表。</summary>
public ObservableCollection<DecryptFileViewModel> Files { get; } = new(); public ObservableCollection<DecryptFileViewModel> Files { get; } = new();
/// <summary>
/// 创建音乐解密页面。
/// </summary>
public DecryptViewModel( public DecryptViewModel(
IMusicDecryptor musicDecryptor, IMusicDecryptor musicDecryptor,
IDialogService dialogService, IDialogService dialogService,
@@ -135,11 +169,12 @@ public partial class DecryptViewModel : ViewModelBase
} }
/// <summary> /// <summary>
/// Restores the manually chosen database path (if any) and probes it once so the page can show /// 恢复已保存的数据库路径并刷新文件状态。
/// the warning strip and mark kgg rows before the user presses start.
/// </summary> /// </summary>
public override async Task OnActivatedAsync() public override async Task OnActivatedAsync()
{ {
if (IsDecrypting || IsInitializing) return;
if (!_isInitialized) if (!_isInitialized)
{ {
await InitializeAsync(); await InitializeAsync();
@@ -149,12 +184,19 @@ public partial class DecryptViewModel : ViewModelBase
RefreshDatabaseStatus(); RefreshDatabaseStatus();
} }
public async Task InitializeAsync() /// <summary>
/// 初始化酷狗数据库路径。
/// </summary>
public async Task InitializeAsync(CancellationToken cancellationToken = default)
{
if (IsInitializing) return;
IsInitializing = true;
try
{ {
_isInitialized = true;
if (_kugouDatabaseStore != null && _kugouKeyProvider != null) if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
{ {
var stored = await _kugouDatabaseStore.LoadAsync().ConfigureAwait(true); var stored = await _kugouDatabaseStore.LoadAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(stored)) if (!string.IsNullOrWhiteSpace(stored))
{ {
_kugouKeyProvider.SetDatabasePath(stored); _kugouKeyProvider.SetDatabasePath(stored);
@@ -162,13 +204,27 @@ public partial class DecryptViewModel : ViewModelBase
} }
RefreshDatabaseStatus(); 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() private void RefreshDatabaseStatus()
{ {
if (_kugouKeyProvider == null) if (_kugouKeyProvider == null)
{ {
// No provider at all: keep the page usable, kgg will report the failure itself. // 未注册密钥提供者时,由解密器报告具体错误。
IsKugouDatabaseAvailable = true; IsKugouDatabaseAvailable = true;
KugouDatabaseStatus = string.Empty; KugouDatabaseStatus = string.Empty;
return; return;
@@ -178,7 +234,7 @@ public partial class DecryptViewModel : ViewModelBase
IsKugouDatabaseAvailable = info.IsAvailable; IsKugouDatabaseAvailable = info.IsAvailable;
KugouDatabaseStatus = info.Message; KugouDatabaseStatus = info.Message;
// Rows added while the database was missing are stale the moment it becomes readable. // 数据库可用后解除未处理文件的阻止状态。
foreach (var file in Files) foreach (var file in Files)
{ {
if (!IsKggFile(file.FilePath)) continue; if (!IsKggFile(file.FilePath)) continue;
@@ -241,24 +297,35 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(ColumnFileName)); OnPropertyChanged(nameof(ColumnFileName));
OnPropertyChanged(nameof(ColumnOutputPath)); OnPropertyChanged(nameof(ColumnOutputPath));
OnPropertyChanged(nameof(ColumnStatus)); 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))] [RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SelectFilesAsync() private async Task SelectFilesAsync(CancellationToken cancellationToken = default)
{ {
var picked = await _dialogService.ShowFilesPickerAsync( var picked = await _dialogService.ShowFilesPickerAsync(
DecryptSelectFiles, DecryptSelectFiles,
new[] { ".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm" }); [".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm"],
cancellationToken);
if (picked.Count == 0) return; if (picked.Count == 0) return;
// Probe once for the whole batch instead of per file: the database is either readable or // 同一批文件只检查一次数据库。
// it is not, and re-reading it for every dropped file would be pointless I/O.
RefreshDatabaseStatus(); RefreshDatabaseStatus();
foreach (var path in picked) foreach (var path in picked)
{ {
// The picker can hand back the same file twice; keys must stay unique. // 避免重复添加同一文件。
if (Files.Any(f => string.Equals(f.FilePath, path, StringComparison.OrdinalIgnoreCase))) if (Files.Any(f => string.Equals(f.FilePath, path, StringComparison.OrdinalIgnoreCase)))
{ {
continue; continue;
@@ -277,9 +344,7 @@ public partial class DecryptViewModel : ViewModelBase
ViewDetailLabel = DecryptViewDetail ViewDetailLabel = DecryptViewDetail
}; };
// 详情命令挂在行自己身上,比在模板里通过 $parent 硬转成父 VM 再取命令更稳, row.ShowDetailCommand = new AsyncRelayCommand(token => ShowDetailAsync(row, token));
// 也不会因为 DataTemplate 的上下文变化而悄悄失效。
row.ShowDetailCommand = new AsyncRelayCommand(() => ShowDetailAsync(row));
Files.Add(row); Files.Add(row);
} }
@@ -287,14 +352,15 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt)); OnPropertyChanged(nameof(CanStartDecrypt));
} }
private bool CanSelectFiles => !IsDecrypting; private bool CanSelectFiles => !IsDecrypting && !IsInitializing;
[RelayCommand(CanExecute = nameof(CanSelectFiles))] [RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SpecifyDatabaseAsync() private async Task SpecifyDatabaseAsync(CancellationToken cancellationToken = default)
{ {
var picked = await _dialogService.ShowFilePickerAsync( var picked = await _dialogService.ShowFilePickerAsync(
DecryptSpecifyDatabase, DecryptSpecifyDatabase,
new[] { ".db" }); new[] { ".db" });
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrWhiteSpace(picked)) if (string.IsNullOrWhiteSpace(picked))
{ {
@@ -306,16 +372,15 @@ public partial class DecryptViewModel : ViewModelBase
if (_kugouDatabaseStore != null) if (_kugouDatabaseStore != null)
{ {
await _kugouDatabaseStore.SaveAsync(picked).ConfigureAwait(true); await _kugouDatabaseStore.SaveAsync(picked, cancellationToken);
} }
} }
[RelayCommand(CanExecute = nameof(CanStartDecrypt))] [RelayCommand(CanExecute = nameof(CanStartDecrypt))]
private async Task StartDecryptAsync() private async Task StartDecryptAsync(CancellationToken cancellationToken = default)
{ {
if (Files.Count == 0) return; if (Files.Count == 0) return;
// A kgg row without a readable database cannot decrypt, so it is left out of the run // 缺少密钥数据库的文件不加入本次任务。
// entirely instead of failing one file at a time with the same message.
var runnable = Files.Where(f => !f.IsBlocked).ToList(); var runnable = Files.Where(f => !f.IsBlocked).ToList();
IsDecrypting = true; IsDecrypting = true;
@@ -329,6 +394,7 @@ public partial class DecryptViewModel : ViewModelBase
file.IsProcessed = false; file.IsProcessed = false;
file.IsSuccessful = false; file.IsSuccessful = false;
file.OutputPath = null; file.OutputPath = null;
file.ErrorDetail = null;
if (!file.IsBlocked) if (!file.IsBlocked)
{ {
@@ -342,7 +408,7 @@ public partial class DecryptViewModel : ViewModelBase
return; return;
} }
_decryptCts = new CancellationTokenSource(); _decryptCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = _decryptCts.Token; var token = _decryptCts.Token;
try try
@@ -358,7 +424,11 @@ public partial class DecryptViewModel : ViewModelBase
DecryptionResult result; DecryptionResult result;
try try
{ {
result = await _musicDecryptor.ConvertMusicAsync(file.FilePath, token); result = await Task.Run(() => _musicDecryptor.ConvertMusicAsync(file.FilePath, token), token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
throw;
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -379,8 +449,7 @@ public partial class DecryptViewModel : ViewModelBase
} }
else else
{ {
// The status column shows a short label; the full reason (a missing // 状态列只显示摘要,完整错误在详情对话框展示。
// database dumps several hundred characters) lives in the row detail.
file.ErrorDetail = result.ErrorMessage; file.ErrorDetail = result.ErrorMessage;
file.StatusMessage = _localization?["Status_Failed"] ?? "Failed"; file.StatusMessage = _localization?["Status_Failed"] ?? "Failed";
FailedCount++; FailedCount++;
@@ -389,13 +458,13 @@ public partial class DecryptViewModel : ViewModelBase
var done = CompletedCount + FailedCount; var done = CompletedCount + FailedCount;
ProgressPercentage = done * 100.0 / TotalCount; ProgressPercentage = done * 100.0 / TotalCount;
}); });
})); }, token));
await Task.WhenAll(tasks); await Task.WhenAll(tasks);
} }
catch (OperationCanceledException) catch (OperationCanceledException) when (token.IsCancellationRequested)
{ {
// User cancelled; rows that never ran stay "Pending". // 用户取消时,未完成的文件保持待处理状态。
} }
finally finally
{ {
@@ -406,11 +475,11 @@ public partial class DecryptViewModel : ViewModelBase
} }
/// <summary> /// <summary>
/// Shows the untruncated reason a row failed. Without this the only place the explanatory text /// 显示文件解密失败的完整原因。
/// exists is a tooltip, which is unreadable for the long "database not found" message.
/// </summary> /// </summary>
private async Task ShowDetailAsync(DecryptFileViewModel? file) private async Task ShowDetailAsync(DecryptFileViewModel? file, CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail)) if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail))
{ {
return; return;
@@ -436,47 +505,57 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt)); OnPropertyChanged(nameof(CanStartDecrypt));
} }
/// <summary>
/// 是否可以清空文件列表。
/// </summary>
private bool CanClear => !IsDecrypting && Files.Count > 0; private bool CanClear => !IsDecrypting && Files.Count > 0;
} }
/// <summary>
/// 单个文件的解密状态。
/// </summary>
public partial class DecryptFileViewModel : ObservableObject public partial class DecryptFileViewModel : ObservableObject
{ {
/// <summary>输入文件路径。</summary>
[ObservableProperty] [ObservableProperty]
private string _filePath = string.Empty; private string _filePath = string.Empty;
/// <summary>输入文件名。</summary>
[ObservableProperty] [ObservableProperty]
private string _fileName = string.Empty; private string _fileName = string.Empty;
/// <summary>解密后的输出路径。</summary>
[ObservableProperty] [ObservableProperty]
private string? _outputPath; private string? _outputPath;
/// <summary>是否已完成处理。</summary>
[ObservableProperty] [ObservableProperty]
private bool _isProcessed; private bool _isProcessed;
/// <summary>是否解密成功。</summary>
[ObservableProperty] [ObservableProperty]
private bool _isSuccessful; private bool _isSuccessful;
/// <summary> /// <summary>
/// Short label for the status column. Long explanations belong in <see cref="ErrorDetail"/>, /// 状态列摘要,完整原因保存在 <see cref="ErrorDetail"/>。
/// which the detail dialog shows in full.
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))] [NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _statusMessage; private string? _statusMessage;
/// <summary>解密失败的完整原因。</summary>
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))] [NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _errorDetail; private string? _errorDetail;
/// <summary> /// <summary>
/// Set when the row cannot run at all (kgg without a readable KuGou database). Blocked rows are /// 是否因缺少酷狗数据库而无法开始解密。
/// tinted so the reason is visible before pressing start.
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
private bool _isBlocked; private bool _isBlocked;
/// <summary> /// <summary>
/// 详情按钮上的文案。挂在行上,模板就不必再通过 $parent 反向取父 ViewModel。 /// 详情按钮文案。
/// </summary> /// </summary>
[ObservableProperty] [ObservableProperty]
private string? _viewDetailLabel; private string? _viewDetailLabel;
@@ -486,5 +565,8 @@ public partial class DecryptFileViewModel : ObservableObject
/// </summary> /// </summary>
public IAsyncRelayCommand? ShowDetailCommand { get; set; } public IAsyncRelayCommand? ShowDetailCommand { get; set; }
/// <summary>
/// 是否存在可查看的错误详情。
/// </summary>
public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail); public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail);
} }
@@ -7,14 +7,16 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary> /// <summary>
/// The landing page. Its only job is to point people at the three things this app actually does, /// 首页与功能入口。
/// so every quick-action button navigates for real instead of sitting there looking clickable.
/// </summary> /// </summary>
public partial class HomeViewModel : ViewModelBase public partial class HomeViewModel : ViewModelBase
{ {
private readonly INavigationService _navigation; private readonly INavigationService _navigation;
private readonly IUILocalizationService _localization; private readonly IUILocalizationService _localization;
/// <summary>
/// 创建首页。
/// </summary>
public HomeViewModel(INavigationService navigation, IUILocalizationService localization) public HomeViewModel(INavigationService navigation, IUILocalizationService localization)
{ {
_navigation = navigation; _navigation = navigation;
@@ -26,22 +28,37 @@ public partial class HomeViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
private string _version; private string _version;
/// <summary>欢迎语。</summary>
public string WelcomeMessage => _localization["Home_Welcome"]; public string WelcomeMessage => _localization["Home_Welcome"];
/// <summary>应用说明。</summary>
public string Description => _localization["Home_Description"]; public string Description => _localization["Home_Description"];
/// <summary>快捷操作标题。</summary>
public string QuickActionsTitle => _localization["Home_QuickActions"]; public string QuickActionsTitle => _localization["Home_QuickActions"];
/// <summary>功能特性标题。</summary>
public string FeaturesTitle => _localization["Home_Features"]; public string FeaturesTitle => _localization["Home_Features"];
/// <summary>支持格式说明。</summary>
public string FeatureFormats => _localization["Home_FeatureFormats"]; public string FeatureFormats => _localization["Home_FeatureFormats"];
/// <summary>并行下载说明。</summary>
public string FeatureParallel => _localization["Home_FeatureParallel"]; public string FeatureParallel => _localization["Home_FeatureParallel"];
/// <summary>编码支持说明。</summary>
public string FeatureEncodings => _localization["Home_FeatureEncodings"]; public string FeatureEncodings => _localization["Home_FeatureEncodings"];
/// <summary>跨平台支持说明。</summary>
public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"]; public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"];
/// <summary>版本标签。</summary>
public string VersionLabel => _localization["Home_Version"]; public string VersionLabel => _localization["Home_Version"];
// Card copy: title + one-line explanation, both localized. // 功能入口文案。
/// <summary>歌词下载入口标题。</summary>
public string LyricsCardTitle => _localization["Home_DownloadLyrics"]; public string LyricsCardTitle => _localization["Home_DownloadLyrics"];
/// <summary>歌词下载入口说明。</summary>
public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"]; public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"];
/// <summary>封面下载入口标题。</summary>
public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"]; public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"];
/// <summary>封面下载入口说明。</summary>
public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"]; public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"];
/// <summary>音乐解密入口标题。</summary>
public string DecryptCardTitle => _localization["Home_Decrypt"]; public string DecryptCardTitle => _localization["Home_Decrypt"];
/// <summary>音乐解密入口说明。</summary>
public string DecryptCardDescription => _localization["Home_DecryptHint"]; public string DecryptCardDescription => _localization["Home_DecryptHint"];
[RelayCommand] [RelayCommand]
@@ -79,7 +96,7 @@ public partial class HomeViewModel : ViewModelBase
if (!string.IsNullOrWhiteSpace(informational)) if (!string.IsNullOrWhiteSpace(informational))
{ {
// Strip the "+<commit sha>" suffix that SourceLink appends. // 隐藏 SourceLink 添加的提交标识。
var plusIndex = informational.IndexOf('+'); var plusIndex = informational.IndexOf('+');
return plusIndex > 0 ? informational[..plusIndex] : informational; return plusIndex > 0 ? informational[..plusIndex] : informational;
} }
@@ -17,17 +17,17 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary> /// <summary>
/// Which source the lyrics page reads its song list from. /// 歌词列表的数据来源。
/// </summary> /// </summary>
public enum LyricsScannerKind public enum LyricsScannerKind
{ {
/// <summary>Scan a local folder for audio files.</summary> /// <summary>扫描本地音乐文件夹。</summary>
Local = 0, Local = 0,
/// <summary>Read a CSV file containing "song,artist" rows.</summary> /// <summary>读取歌曲与歌手信息的 CSV 文件。</summary>
Csv = 1, Csv = 1,
/// <summary>Pull a NetEase Cloud Music playlist by id.</summary> /// <summary>读取网易云歌单。</summary>
NetEase = 2 NetEase = 2
} }
@@ -47,9 +47,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private readonly IUILocalizationService? _localization; private readonly IUILocalizationService? _localization;
private CancellationTokenSource? _downloadCts; private CancellationTokenSource? _downloadCts;
private CancellationTokenSource? _scanCts;
private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new(); private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new(); private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty] [ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))] [NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
@@ -73,6 +72,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(IsLocalScanner))] [NotifyPropertyChangedFor(nameof(IsLocalScanner))]
[NotifyPropertyChangedFor(nameof(IsCsvScanner))] [NotifyPropertyChangedFor(nameof(IsCsvScanner))]
[NotifyPropertyChangedFor(nameof(IsNetEaseScanner))] [NotifyPropertyChangedFor(nameof(IsNetEaseScanner))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))] [NotifyPropertyChangedFor(nameof(CanScan))]
private int _selectedScannerIndex; private int _selectedScannerIndex;
@@ -93,6 +93,14 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] [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))] [NotifyPropertyChangedFor(nameof(CanStartDownload))]
private bool _isDownloading; private bool _isDownloading;
@@ -102,6 +110,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))] [NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))] [NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))] [NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))] [NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))] [NotifyPropertyChangedFor(nameof(CanScan))]
private bool _isScanning; private bool _isScanning;
@@ -121,10 +132,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
private bool _isNetEaseLoggedIn; 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] [ObservableProperty]
private string? _currentProcessingFile; private string? _currentProcessingFile;
// Localized strings // 界面文案。
public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download"; public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download";
public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files"; public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files";
public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder"; public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder";
@@ -134,32 +158,45 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download"; public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download";
public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download"; public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download";
public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files..."; public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
/// <summary>数据来源标签。</summary>
public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source"; public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source";
/// <summary>扫描按钮文案。</summary>
public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan"; public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan";
/// <summary>CSV 文件标签。</summary>
public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File"; public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File";
/// <summary>CSV 文件选择提示。</summary>
public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file..."; public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file...";
/// <summary>CSV 文件选择按钮文案。</summary>
public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose..."; public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose...";
/// <summary>网易云歌单编号标签。</summary>
public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID"; public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID";
/// <summary>网易云歌单编号输入提示。</summary>
public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)"; public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)";
/// <summary>输出目录标签。</summary>
public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To"; public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To";
/// <summary>输出目录选择提示。</summary>
public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written"; public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written";
/// <summary>输出目录选择按钮文案。</summary>
public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose..."; public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose...";
/// <summary>退出登录按钮文案。</summary>
public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out"; public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out";
/// <summary>退出登录提示。</summary>
public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ?? public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ??
"Forget the saved session and scan the QR code again next time."; "Forget the saved session and scan the QR code again next time.";
/// <summary>登录按钮文案。</summary>
public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…"; public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…";
/// <summary>登录按钮提示。</summary>
public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ?? public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ??
"Scan a QR code now instead of waiting until the next scan."; "Scan a QR code now instead of waiting until the next scan.";
/// <summary> /// <summary>
/// Human readable login state. The sign in / sign out buttons alone were not enough: a user /// 当前网易云登录状态。
/// who had never signed in could not tell whether a session was stored, and a user who had
/// signed in had no way to notice the cookie was restored from disk.
/// </summary> /// </summary>
public string NetEaseAccountStatus => IsNetEaseLoggedIn public string NetEaseAccountStatus => IsNetEaseLoggedIn
? _localization?["NetEase_LoggedIn"] ?? "Signed in. Scanning a playlist reuses this session." ? _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."; : _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 NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files"; public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -171,7 +208,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
/// <summary> /// <summary>
/// Scanner display names, indexed the same way as <see cref="SelectedScannerIndex"/>. /// 按 <see cref="SelectedScannerIndex"/> 排列的数据来源名称。
/// </summary> /// </summary>
public string[] ScannerNames => public string[] ScannerNames =>
[ [
@@ -184,7 +221,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv; public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv;
public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase; public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase;
public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0; public bool CanStartDownload => CanEditInputs && MusicFiles.Count > 0;
public bool HasNoFiles => MusicFiles.Count == 0; public bool HasNoFiles => MusicFiles.Count == 0;
@@ -222,8 +259,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
_localization.LanguageChanged += OnLanguageChanged; _localization.LanguageChanged += OnLanguageChanged;
} }
// The scanner is a singleton, so a session restored by an earlier page visit is already // 扫描器为单例,页面直接复用已恢复的登录状态。
// in memory; reflect it right away instead of waiting for the first activation.
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
MusicFiles.CollectionChanged += (_, _) => MusicFiles.CollectionChanged += (_, _) =>
@@ -273,75 +309,93 @@ public partial class LyricsDownloadViewModel : ViewModelBase
OnPropertyChanged(nameof(ScannerNames)); OnPropertyChanged(nameof(ScannerNames));
} }
// ---------------------------------------------------------------- selection commands 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))] [RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync() private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{ {
var folder = await _dialogService.ShowFolderPickerAsync( var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_SelectFolder"] ?? "Select Music Folder"); _localization?["Lyrics_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return; if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder; SelectedFolderPath = folder;
await ScanFilesAsync(); await ScanFilesAsync(cancellationToken);
} }
private bool CanSelectFolder => !IsScanning && !IsDownloading; /// <summary>
/// 是否可以修改任务来源与输出目录。
/// </summary>
public bool CanEditInputs => !IsScanning && !IsDownloading && !IsAccountBusy;
private bool CanSelectFolder => CanEditInputs;
[RelayCommand(CanExecute = nameof(CanSelectFolder))] [RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectCsvFileAsync() private async Task SelectCsvFileAsync(CancellationToken cancellationToken = default)
{ {
var file = await _dialogService.ShowFilePickerAsync( var file = await _dialogService.ShowFilePickerAsync(
_localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]); _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(file)) return; if (string.IsNullOrEmpty(file)) return;
SelectedCsvFilePath = file; SelectedCsvFilePath = file;
} }
[RelayCommand(CanExecute = nameof(CanSelectFolder))] [RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectOutputFolderAsync() private async Task SelectOutputFolderAsync(CancellationToken cancellationToken = default)
{ {
var folder = await _dialogService.ShowFolderPickerAsync( var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_OutputSelect"] ?? "Select Output Folder"); _localization?["Lyrics_OutputSelect"] ?? "Select Output Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return; if (string.IsNullOrEmpty(folder)) return;
OutputDirectory = folder; OutputDirectory = folder;
} }
// ---------------------------------------------------------------- scanning
/// <summary> /// <summary>
/// Whether the current source has enough input to start reading a song list. /// 当前来源是否具备扫描所需的输入。
/// </summary> /// </summary>
public bool CanScan => !IsScanning && !IsDownloading && SelectedScannerIndex switch public bool CanScan => CanEditInputs && (SelectedScannerIndex switch
{ {
(int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath), (int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath),
(int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath), (int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath),
(int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds), (int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds),
_ => false _ => false
}; });
/// <summary> /// <summary>
/// Re-read the song list using the currently selected source. /// 使用当前来源重新读取歌曲列表。
/// </summary> /// </summary>
[RelayCommand(CanExecute = nameof(CanScan))] [RelayCommand(CanExecute = nameof(CanScan))]
private async Task StartScanAsync() private async Task StartScanAsync(CancellationToken cancellationToken = default)
{ {
switch ((LyricsScannerKind)SelectedScannerIndex) switch ((LyricsScannerKind)SelectedScannerIndex)
{ {
case LyricsScannerKind.Csv: case LyricsScannerKind.Csv:
await ScanCsvFileAsync(); await ScanCsvFileAsync(cancellationToken);
break; break;
case LyricsScannerKind.NetEase: case LyricsScannerKind.NetEase:
await ScanNetEasePlaylistAsync(); await ScanNetEasePlaylistAsync(cancellationToken);
break; break;
default: default:
await ScanFilesAsync(); await ScanFilesAsync(cancellationToken);
break; break;
} }
} }
private async Task ScanFilesAsync() private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{ {
if (string.IsNullOrEmpty(SelectedFolderPath)) return; if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -350,12 +404,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try try
{ {
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions)) var files = (await Task.Run(
.ToList(); () => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0) if (files.Count == 0)
{ {
await ShowNoMusicFilesAsync(); await ShowNoMusicFilesAsync(cancellationToken);
return; return;
} }
@@ -365,7 +420,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file => var scanTasks = files.Select(file =>
warpTask.RunAsync(async () => warpTask.RunAsync(async () =>
{ {
var musicInfo = await _tagLoader.LoadTagAsync(file); var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() => await Dispatcher.UIThread.InvokeAsync(() =>
{ {
@@ -378,15 +433,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
ScanProgressCount++; ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount; ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
}); });
})); }, cancellationToken));
await Task.WhenAll(scanTasks); await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count; TotalCount = MusicFiles.Count;
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex) catch (Exception ex)
{ {
await ShowErrorAsync(ex.Message); await ShowErrorAsync(ex.Message, cancellationToken);
} }
finally finally
{ {
@@ -394,7 +453,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
} }
} }
private async Task ScanCsvFileAsync() private async Task ScanCsvFileAsync(CancellationToken cancellationToken = default)
{ {
if (string.IsNullOrEmpty(SelectedCsvFilePath)) return; if (string.IsNullOrEmpty(SelectedCsvFilePath)) return;
@@ -403,16 +462,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try try
{ {
var musicInfos = await _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync( var outputDirectory = RequireOutputDirectory();
SelectedCsvFilePath, var musicInfos = await Task.Run(() => _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
RequireOutputDirectory(), SelectedCsvFilePath, outputDirectory, DefaultFileNamePattern, cancellationToken), cancellationToken);
DefaultFileNamePattern);
AppendScannedMusicInfos(musicInfos); AppendScannedMusicInfos(musicInfos);
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex) catch (Exception ex)
{ {
await ShowErrorAsync(ex.Message); await ShowErrorAsync(ex.Message, cancellationToken);
} }
finally finally
{ {
@@ -420,21 +482,18 @@ public partial class LyricsDownloadViewModel : ViewModelBase
} }
} }
private async Task ScanNetEasePlaylistAsync() private async Task ScanNetEasePlaylistAsync(CancellationToken cancellationToken = default)
{ {
if (string.IsNullOrWhiteSpace(SongListIds)) return; if (string.IsNullOrWhiteSpace(SongListIds)) return;
ResetCollections(); ResetCollections();
IsScanning = true; IsScanning = true;
using var scanCts = new CancellationTokenSource();
_scanCts = scanCts;
try try
{ {
await RestoreNetEaseSessionAsync(); await RestoreNetEaseSessionAsync(cancellationToken);
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync()) if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync(cancellationToken))
{ {
return; return;
} }
@@ -448,46 +507,43 @@ public partial class LyricsDownloadViewModel : ViewModelBase
DefaultFileNamePattern, DefaultFileNamePattern,
onQrCodeReady: null, onQrCodeReady: null,
onStateChanged: null, onStateChanged: null,
cancellationToken: scanCts.Token); cancellationToken: cancellationToken);
await PersistNetEaseSessionAsync(); await PersistNetEaseSessionAsync(cancellationToken);
AppendScannedMusicInfos(musicInfos); AppendScannedMusicInfos(musicInfos);
} }
catch (OperationCanceledException) catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{ {
// User closed the login dialog. // 用户取消扫描。
} }
catch (Exception ex) catch (Exception ex)
{ {
await ShowErrorAsync(ex.Message); await ShowErrorAsync(ex.Message, cancellationToken);
} }
finally finally
{ {
_scanCts = null;
IsScanning = false; IsScanning = false;
// Whatever happened above - scan ok, user cancelled the QR dialog, request failed - // 无论登录成功还是取消,都以扫描器中的状态为准。
// the account row must reflect the scanner's real state. Without this the sign-in
// button kept saying "Sign out" after a successful login from the scan flow.
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
} }
} }
/// <summary> /// <summary>
/// Load a previously saved NetEase session so the QR dialog only appears on first use. /// 恢复已保存的网易云登录状态。
/// </summary> /// </summary>
private async Task RestoreNetEaseSessionAsync() private async Task RestoreNetEaseSessionAsync(CancellationToken cancellationToken = default)
{ {
if (_neteaseMusicScanner.IsLoggedIn) return; if (_neteaseMusicScanner.IsLoggedIn) return;
var session = await _sessionStore.LoadAsync(); var session = await _sessionStore.LoadAsync(cancellationToken);
if (session == null) return; if (session == null) return;
_neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken); _neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken);
} }
private async Task PersistNetEaseSessionAsync() private async Task PersistNetEaseSessionAsync(CancellationToken cancellationToken = default)
{ {
if (!_neteaseMusicScanner.IsLoggedIn) return; if (!_neteaseMusicScanner.IsLoggedIn) return;
@@ -495,61 +551,81 @@ public partial class LyricsDownloadViewModel : ViewModelBase
{ {
Cookie = _neteaseMusicScanner.Cookie, Cookie = _neteaseMusicScanner.Cookie,
CsrfToken = _neteaseMusicScanner.CsrfToken, CsrfToken = _neteaseMusicScanner.CsrfToken,
SavedAt = DateTimeOffset.Now SavedAtUtc = DateTimeOffset.UtcNow
}); }, cancellationToken);
} }
/// <summary> /// <summary>
/// Show the QR dialog and wait for the scan-and-confirm flow to finish. /// 显示二维码并等待登录或窗口关闭。
/// </summary> /// </summary>
private async Task<bool> LoginToNetEaseAsync() private async Task<bool> LoginToNetEaseAsync(CancellationToken cancellationToken = default)
{ {
var loginViewModel = new QrCodeLoginViewModel(_localization); var loginViewModel = new QrCodeLoginViewModel(_localization);
using var loginCts = new CancellationTokenSource(); using var loginCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
void OnCancelled(object? sender, EventArgs args) => loginCts.Cancel();
loginViewModel.Cancelled += (_, _) => loginCts.Cancel(); loginViewModel.Cancelled += OnCancelled;
var loginTask = Task.Run(async () => var loginTask = Task.Run(async () =>
{ {
try try
{ {
var expired = false;
var isSuccess = await _neteaseMusicScanner.LoginAsync( var isSuccess = await _neteaseMusicScanner.LoginAsync(
payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)), payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)),
state => Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)), state =>
{
expired = state == NetEaseLoginState.Expired;
Dispatcher.UIThread.Post(() => loginViewModel.SetState(state));
},
loginCts.Token); loginCts.Token);
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (isSuccess) if (isSuccess)
{ {
Dispatcher.UIThread.Post(() => loginViewModel.Complete()); loginViewModel.Complete();
} }
else if (!expired)
{
loginViewModel.SetError(_localization?["NetEase_LoginFailed"] ??
"Login did not complete. Close this dialog and try again.");
}
});
return isSuccess; return isSuccess;
} }
catch (OperationCanceledException) catch (OperationCanceledException) when (loginCts.IsCancellationRequested)
{ {
return false; return false;
} }
catch (Exception ex) catch (Exception ex)
{ {
Dispatcher.UIThread.Post(() => loginViewModel.SetError(ex.Message)); await Dispatcher.UIThread.InvokeAsync(() => loginViewModel.SetError(ex.Message));
return false; return false;
} }
}); });
// The dialog closes itself once the flow calls Complete(), so this await returns as soon try
// as the user either confirms on the phone or gives up. {
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel); await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel, cancellationToken);
}
finally
{
loginViewModel.NotifyClosed();
loginCts.Cancel();
await loginTask;
loginViewModel.Cancelled -= OnCancelled;
}
var isSuccess = await loginTask; var isSuccess = await loginTask;
if (isSuccess) if (isSuccess)
{ {
await PersistNetEaseSessionAsync(); await PersistNetEaseSessionAsync(cancellationToken);
} }
return isSuccess; return isSuccess;
} }
// ---------------------------------------------------------------- shared helpers
private void ResetCollections() private void ResetCollections()
{ {
@@ -567,6 +643,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private void AddRow(MusicInfo musicInfo) private void AddRow(MusicInfo musicInfo)
{ {
if (_musicFileMap.ContainsKey(musicInfo.FilePath)) return;
var vm = new MusicFileViewModel var vm = new MusicFileViewModel
{ {
FilePath = musicInfo.FilePath, FilePath = musicInfo.FilePath,
@@ -581,7 +659,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
} }
/// <summary> /// <summary>
/// Fill the grid from a scanner that returns its list in one shot (CSV, NetEase). /// 将 CSV 或网易云扫描结果加入列表。
/// </summary> /// </summary>
private void AppendScannedMusicInfos(List<MusicInfo> musicInfos) private void AppendScannedMusicInfos(List<MusicInfo> musicInfos)
{ {
@@ -611,22 +689,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
return fallback; return fallback;
} }
private Task ShowNoMusicFilesAsync() private Task ShowNoMusicFilesAsync(CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync( return _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info", _localization?["Common_Info"] ?? "Info",
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder."); _localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
} }
private Task ShowErrorAsync(string message) private Task ShowErrorAsync(string message, CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message); return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message);
} }
// ---------------------------------------------------------------- download
[RelayCommand(CanExecute = nameof(CanStartDownload))] [RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync() private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{ {
if (_scannedMusicInfos.Count == 0) return; if (_scannedMusicInfos.Count == 0) return;
@@ -643,7 +722,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
} }
_downloadCts = new CancellationTokenSource(); _downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try try
{ {
@@ -683,9 +762,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}, },
_downloadCts.Token); _downloadCts.Token);
} }
catch (OperationCanceledException) catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{ {
// User cancelled // 用户取消下载。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
} }
finally finally
{ {
@@ -702,54 +785,85 @@ public partial class LyricsDownloadViewModel : ViewModelBase
} }
/// <summary> /// <summary>
/// Clears the saved NetEase session so the next playlist scan asks for a fresh QR login. /// 清除已保存的网易云登录状态。
/// <remarks>
/// Without this the only way to recover from an expired Cookie was to delete
/// <c>netease.session.json</c> by hand.
/// </remarks>
/// </summary> /// </summary>
[RelayCommand(CanExecute = nameof(IsNetEaseLoggedIn))] [RelayCommand(CanExecute = nameof(CanSignOutNetEase))]
private async Task SignOutNetEaseAsync() private async Task SignOutNetEaseAsync(CancellationToken cancellationToken = default)
{ {
IsAccountBusy = true;
try
{
await _sessionStore.ClearAsync(cancellationToken);
_neteaseMusicScanner.ClearLoginState(); _neteaseMusicScanner.ClearLoginState();
await _sessionStore.ClearAsync();
IsNetEaseLoggedIn = false;
await _dialogService.ShowMessageAsync( await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info", _localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login."); _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 && !IsScanning && !IsDownloading; private bool CanSignInNetEase => !IsNetEaseLoggedIn && CanEditInputs;
private bool CanSignOutNetEase => IsNetEaseLoggedIn && CanEditInputs;
/// <summary> /// <summary>
/// Let the user sign in from the page itself instead of discovering the QR dialog only after /// 主动发起网易云扫码登录。
/// pressing "Scan" - the button used to be hidden behind one specific scanner choice.
/// </summary> /// </summary>
[RelayCommand(CanExecute = nameof(CanSignInNetEase))] [RelayCommand(CanExecute = nameof(CanSignInNetEase))]
private async Task SignInNetEaseAsync() private async Task SignInNetEaseAsync(CancellationToken cancellationToken = default)
{ {
if (await LoginToNetEaseAsync()) IsAccountBusy = true;
try
{ {
IsNetEaseLoggedIn = true; await LoginToNetEaseAsync(cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消登录。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
} }
} }
/// <summary> /// <summary>
/// Refresh the visible login state. Called on construction and every time the page is shown, /// 页面打开时恢复登录状态。
/// because the session may have been written by an earlier run of the app.
/// </summary> /// </summary>
private async Task RefreshNetEaseLoginStateAsync()
{
await RestoreNetEaseSessionAsync();
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
SignOutNetEaseCommand.NotifyCanExecuteChanged();
SignInNetEaseCommand.NotifyCanExecuteChanged();
}
public override async Task OnActivatedAsync() public override async Task OnActivatedAsync()
{ {
await base.OnActivatedAsync(); if (!CanEditInputs) return;
await RefreshNetEaseLoginStateAsync();
IsAccountBusy = true;
try
{
await RestoreNetEaseSessionAsync();
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
}
} }
} }
@@ -28,6 +28,7 @@ public partial class MainWindowViewModel : ViewModelBase
public string NavHome => _localization["Nav_Home"]; public string NavHome => _localization["Nav_Home"];
public string NavLyricsDownload => _localization["Nav_LyricsDownload"]; public string NavLyricsDownload => _localization["Nav_LyricsDownload"];
public string NavAlbumDownload => _localization["Nav_AlbumDownload"]; public string NavAlbumDownload => _localization["Nav_AlbumDownload"];
/// <summary>音乐解密导航文案。</summary>
public string NavDecrypt => _localization["Nav_Decrypt"]; public string NavDecrypt => _localization["Nav_Decrypt"];
public string NavSettings => _localization["Nav_Settings"]; public string NavSettings => _localization["Nav_Settings"];
public string HomeDescription => _localization["Home_Description"]; public string HomeDescription => _localization["Home_Description"];
@@ -44,17 +45,20 @@ public partial class MainWindowViewModel : ViewModelBase
_themeService = themeService; _themeService = themeService;
_localization = localization; _localization = localization;
_navigation = navigation; _navigation = navigation;
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
_themeService.ThemeChanged += (_, _) =>
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
// Subscribe to language changes // Subscribe to language changes
_localization.LanguageChanged += OnLanguageChanged; _localization.LanguageChanged += OnLanguageChanged;
// The navigation service is the single owner of "which page is showing". // 页面切换统一由导航服务管理。
_navigation.NavigationChanged += OnNavigationChanged; _navigation.NavigationChanged += OnNavigationChanged;
NavigateToIndex(0); NavigateToIndex(0);
} }
// Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed". // 避免导航通知与侧栏选中状态互相触发。
private bool _isSyncingNavigation; private bool _isSyncingNavigation;
partial void OnSelectedNavigationIndexChanged(int value) partial void OnSelectedNavigationIndexChanged(int value)
@@ -69,8 +73,7 @@ public partial class MainWindowViewModel : ViewModelBase
private void NavigateToIndex(int index) private void NavigateToIndex(int index)
{ {
// NavigateRoot keeps the stack depth at one: sidebar switching is not a back-navigable // 侧栏切换不累积返回记录。
// action, so clicking around must not grow history.
CurrentPage = index switch CurrentPage = index switch
{ {
1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(), 1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(),
@@ -85,7 +88,7 @@ public partial class MainWindowViewModel : ViewModelBase
{ {
CurrentPage = viewModel; CurrentPage = viewModel;
// The home page quick actions navigate directly, so the sidebar has to follow them. // 首页快捷入口跳转时同步侧栏选中项。
var index = IndexOf(viewModel); var index = IndexOf(viewModel);
if (index < 0 || index == SelectedNavigationIndex) if (index < 0 || index == SelectedNavigationIndex)
{ {
@@ -128,9 +131,6 @@ public partial class MainWindowViewModel : ViewModelBase
[RelayCommand] [RelayCommand]
private void ToggleTheme() private void ToggleTheme()
{ {
IsDarkTheme = !IsDarkTheme; _themeService.ToggleTheme();
_themeService.SetTheme(IsDarkTheme
? Avalonia.Styling.ThemeVariant.Dark
: Avalonia.Styling.ThemeVariant.Light);
} }
} }
@@ -7,16 +7,12 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary> /// <summary>
/// Drives the NetEase QR-code login dialog. /// 网易云扫码登录对话框。
/// </summary> /// </summary>
/// <remarks>
/// Two events cross the dialog boundary in opposite directions: <see cref="CloseRequested"/>
/// lets the login flow close the window once it is done, and <see cref="Cancelled"/> fires when
/// the user closed the window first, so the caller can stop polling instead of waiting forever.
/// </remarks>
public partial class QrCodeLoginViewModel : ObservableObject public partial class QrCodeLoginViewModel : ObservableObject
{ {
private readonly IUILocalizationService? _localization; private readonly IUILocalizationService? _localization;
private bool _isClosed;
[ObservableProperty] [ObservableProperty]
private Bitmap? _qrCodeImage; private Bitmap? _qrCodeImage;
@@ -28,24 +24,30 @@ public partial class QrCodeLoginViewModel : ObservableObject
private bool _hasImage; private bool _hasImage;
/// <summary> /// <summary>
/// Raised when the login flow wants the dialog closed. /// 请求关闭登录对话框。
/// </summary> /// </summary>
public event EventHandler? CloseRequested; public event EventHandler? CloseRequested;
/// <summary> /// <summary>
/// Raised when the user closed the dialog before logging in. /// 登录完成前关闭对话框时触发。
/// </summary> /// </summary>
public event EventHandler? Cancelled; public event EventHandler? Cancelled;
/// <summary> /// <summary>
/// True once the login succeeded; the dialog stays closable but no longer counts as a cancel. /// 是否已登录成功。
/// </summary> /// </summary>
public bool IsCompleted { get; private set; } public bool IsCompleted { get; private set; }
/// <summary>登录窗口标题。</summary>
public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music"; 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."; 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"; public string CancelText => _localization?["Common_Cancel"] ?? "Cancel";
/// <summary>
/// 创建扫码登录对话框状态。
/// </summary>
public QrCodeLoginViewModel(IUILocalizationService? localization = null) public QrCodeLoginViewModel(IUILocalizationService? localization = null)
{ {
_localization = localization; _localization = localization;
@@ -57,47 +59,60 @@ public partial class QrCodeLoginViewModel : ObservableObject
private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in."; private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in.";
/// <summary> /// <summary>
/// Render the QR payload the scanner produced. /// 显示扫描器提供的二维码。
/// </summary> /// </summary>
public void SetPayload(NetEaseQrCodePayload payload) public void SetPayload(NetEaseQrCodePayload payload)
{ {
if (_isClosed) return;
var previousImage = QrCodeImage;
QrCodeImage = RenderQrCode(payload.Content); QrCodeImage = RenderQrCode(payload.Content);
HasImage = QrCodeImage != null; HasImage = QrCodeImage != null;
StatusText = WaitText; previousImage?.Dispose();
StatusText = HasImage
? WaitText
: _localization?["NetEase_LoginFailed"] ?? "Login did not complete. Close this dialog and try again.";
} }
/// <summary> /// <summary>
/// Reflect a login-state change reported by the scanner. /// 更新扫码登录状态。
/// </summary> /// </summary>
public void SetState(NetEaseLoginState state) public void SetState(NetEaseLoginState state)
{ {
if (_isClosed) return;
StatusText = state switch StatusText = state switch
{ {
NetEaseLoginState.ScanConfirmed => ScannedText, NetEaseLoginState.ScanConfirmed => ScannedText,
NetEaseLoginState.Succeeded => SuccessText, NetEaseLoginState.Succeeded => SuccessText,
NetEaseLoginState.Expired => _localization?["NetEase_LoginExpired"] ?? "The QR code expired. Close this dialog and try again.",
_ => WaitText _ => WaitText
}; };
} }
/// <summary> /// <summary>
/// Push an error message into the dialog. /// 显示登录错误。
/// </summary> /// </summary>
public void SetError(string message) public void SetError(string message)
{ {
if (_isClosed) return;
StatusText = message; StatusText = message;
} }
/// <summary> /// <summary>
/// Mark the flow as finished and close the dialog. /// 标记登录完成并关闭对话框。
/// </summary> /// </summary>
public void Complete() public void Complete()
{ {
if (_isClosed) return;
IsCompleted = true; IsCompleted = true;
RequestClose(); RequestClose();
} }
/// <summary> /// <summary>
/// Ask the dialog to close. /// 请求关闭对话框。
/// </summary> /// </summary>
public void RequestClose() public void RequestClose()
{ {
@@ -105,10 +120,18 @@ public partial class QrCodeLoginViewModel : ObservableObject
} }
/// <summary> /// <summary>
/// Called by the dialog when its window closed, for whatever reason. /// 窗口关闭后停止登录并释放二维码。
/// </summary> /// </summary>
public void NotifyClosed() public void NotifyClosed()
{ {
if (_isClosed) return;
_isClosed = true;
var image = QrCodeImage;
QrCodeImage = null;
HasImage = false;
image?.Dispose();
if (!IsCompleted) if (!IsCompleted)
{ {
Cancelled?.Invoke(this, EventArgs.Empty); Cancelled?.Invoke(this, EventArgs.Empty);
@@ -121,13 +144,13 @@ public partial class QrCodeLoginViewModel : ObservableObject
{ {
using var generator = new QRCodeGenerator(); using var generator = new QRCodeGenerator();
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M); using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
var pngBytes = new PngByteQRCode(data).GetGraphic(12); using var qrCode = new PngByteQRCode(data);
using var stream = new MemoryStream(qrCode.GetGraphic(12));
return new Bitmap(new MemoryStream(pngBytes)); return new Bitmap(stream);
} }
catch (Exception) catch (Exception)
{ {
// A render failure shows up as the placeholder, not as a crash. // 二维码无法生成时,由界面显示登录失败提示。
return null; return null;
} }
} }
@@ -9,12 +9,13 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>设置页面及自动保存状态。</summary>
public partial class SettingsViewModel : ViewModelBase public partial class SettingsViewModel : ViewModelBase
{ {
private readonly ISettingsStore _settingsStore; private readonly ISettingsStore _settingsStore;
private readonly IUILocalizationService? _localizationService; private readonly IUILocalizationService? _localizationService;
private readonly GlobalOptions _globalOptions; private readonly GlobalOptions _globalOptions;
private bool _isLoading = true; // Prevent saving during initial load private bool _isLoading = true;
[ObservableProperty] [ObservableProperty]
private bool _followSystemLanguage = true; private bool _followSystemLanguage = true;
@@ -32,7 +33,7 @@ public partial class SettingsViewModel : ViewModelBase
private string _proxyIp = "127.0.0.1"; private string _proxyIp = "127.0.0.1";
[ObservableProperty] [ObservableProperty]
private int _proxyPort = 7890; private int _proxyPort = 4780;
[ObservableProperty] [ObservableProperty]
private bool _isTranslationEnabled; private bool _isTranslationEnabled;
@@ -61,15 +62,11 @@ public partial class SettingsViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
private bool _isRomanOutputEnabled; private bool _isRomanOutputEnabled;
/// <summary> /// <summary>是否显示高级设置。</summary>
/// Advanced options are collapsed by default: the common path is language + proxy + the four
/// lyric flags, everything else is a power-user setting.
/// </summary>
[ObservableProperty] [ObservableProperty]
private bool _isAdvancedVisible; private bool _isAdvancedVisible;
// Status line for the settings page: shows where settings are stored and whether the // 显示配置位置及上次保存结果。
// last save succeeded.
[ObservableProperty] [ObservableProperty]
private string _storageHint = string.Empty; private string _storageHint = string.Empty;
@@ -83,10 +80,7 @@ public partial class SettingsViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))] [NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
private bool _hasSaveError; private bool _hasSaveError;
/// <summary> /// <summary>可选择的歌词编码。</summary>
/// Encoding choices offered in the settings page. These map to the values accepted by
/// <see cref="GlobalLyricsConfigOptions.FileEncoding"/>.
/// </summary>
public ObservableCollection<string> AvailableEncodings { get; } = new() public ObservableCollection<string> AvailableEncodings { get; } = new()
{ {
"utf-8", "utf-8",
@@ -95,10 +89,7 @@ public partial class SettingsViewModel : ViewModelBase
"gbk" "gbk"
}; };
/// <summary> /// <summary>预设换行符,与显示列表顺序一致。</summary>
/// Line-break choices, parallel to <see cref="LineBreakDisplayNames"/>. The stored value is the
/// actual escape sequence so the YAML file stays compatible with the CLI.
/// </summary>
private static readonly string[] LineBreaks = private static readonly string[] LineBreaks =
{ {
LineBreakType.Unix, LineBreakType.Unix,
@@ -106,9 +97,7 @@ public partial class SettingsViewModel : ViewModelBase
LineBreakType.MacOs LineBreakType.MacOs
}; };
/// <summary> /// <summary>换行符的显示名称。</summary>
/// Display names for the line-break selector, parallel to the internal sequence table.
/// </summary>
public ObservableCollection<string> LineBreakDisplayNames { get; } = new() public ObservableCollection<string> LineBreakDisplayNames { get; } = new()
{ {
"LF (Unix)", "LF (Unix)",
@@ -116,68 +105,103 @@ public partial class SettingsViewModel : ViewModelBase
"CR (macOS)" "CR (macOS)"
}; };
/// <summary> private string CurrentLineBreak => SelectedLineBreakIndex >= 0 && SelectedLineBreakIndex < LineBreaks.Length
/// Value the current settings file uses, for the selected line-break entry. ? LineBreaks[SelectedLineBreakIndex]
/// </summary> : _globalOptions.Provider?.Lyric?.Config?.LineBreak ?? LineBreakType.Unix;
private string CurrentLineBreak => LineBreaks[Math.Clamp(SelectedLineBreakIndex, 0, LineBreaks.Length - 1)];
/// <summary>歌词提供者及搜索顺序。</summary>
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new(); public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new();
/// <summary>标签提供者及加载顺序。</summary>
public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new(); public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new();
// Localized strings // 本地化文本。
/// <summary>设置标题的本地化文本。</summary>
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings"; public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
/// <summary>语言设置标题的本地化文本。</summary>
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language"; public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
/// <summary>跟随系统语言的本地化文本。</summary>
public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System"; public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System";
/// <summary>中文选项的本地化文本。</summary>
public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese"; public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese";
/// <summary>英文选项的本地化文本。</summary>
public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English"; public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English";
/// <summary>代理设置标题的本地化文本。</summary>
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy"; public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
/// <summary>启用代理的本地化文本。</summary>
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy"; public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
/// <summary>代理地址的本地化文本。</summary>
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address"; public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
/// <summary>代理端口的本地化文本。</summary>
public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port"; public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port";
/// <summary>歌词提供者标题的本地化文本。</summary>
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider"; public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
/// <summary>恢复默认值的本地化文本。</summary>
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset"; public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
/// <summary>基本设置标题的本地化文本。</summary>
public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics"; public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics";
/// <summary>高级设置标题的本地化文本。</summary>
public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced"; public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced";
/// <summary>高级选项开关的本地化文本。</summary>
public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options"; public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options";
/// <summary>歌词设置标题的本地化文本。</summary>
public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics"; public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics";
/// <summary>翻译开关的本地化文本。</summary>
public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics"; 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)"; 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"; public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only";
/// <summary>跳过已有文件开关的本地化文本。</summary>
public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files"; public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files";
/// <summary>编码选项的本地化文本。</summary>
public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:"; public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:";
/// <summary>换行符选项的本地化文本。</summary>
public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:"; public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:";
/// <summary>罗马音开关的本地化文本。</summary>
public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)"; public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)";
/// <summary>屏蔽词设置标题的本地化文本。</summary>
public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary"; public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary";
/// <summary>屏蔽词开关的本地化文本。</summary>
public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary"; public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary";
public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the app folder)"; /// <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"; public string SettingsTagProvider => _localizationService?["Settings_TagProvider"] ?? "Tag Provider";
/// <summary>优先级标题的本地化文本。</summary>
public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: "; public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: ";
/// <summary>上移按钮的本地化文本。</summary>
public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up"; public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up";
/// <summary>下移按钮的本地化文本。</summary>
public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down"; public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down";
/// <summary>提供者顺序说明的本地化文本。</summary>
public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"] public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"]
?? "The list order is the search order. Use the arrows to change which source is tried first."; ?? "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"; public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file";
/// <summary>保存成功的本地化文本。</summary>
public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved"; public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved";
/// <summary>保存失败的本地化文本。</summary>
public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings"; public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings";
/// <summary>代理重启提示的本地化文本。</summary>
public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"] public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"]
?? "Proxy changes take effect the next time the app starts."; ?? "Proxy changes take effect the next time the app starts.";
/// <summary> /// <summary>是否显示保存成功提示。</summary>
/// Save feedback: only one of these is ever true, and both stay false before the first save.
/// </summary>
public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText); public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>是否显示保存失败提示。</summary>
public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText); public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>创建设置页面。</summary>
public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null) public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null)
{ {
_settingsStore = settingsStore; _settingsStore = settingsStore;
_localizationService = localizationService; _localizationService = localizationService;
_globalOptions = settingsStore.Options; _globalOptions = settingsStore.Options;
// Subscribe to language changes // 跟随应用语言切换更新界面。
if (_localizationService != null) if (_localizationService != null)
{ {
_localizationService.LanguageChanged += OnLanguageChanged; _localizationService.LanguageChanged += OnLanguageChanged;
@@ -186,7 +210,7 @@ public partial class SettingsViewModel : ViewModelBase
LoadSettings(); LoadSettings();
LoadLanguageSettings(); LoadLanguageSettings();
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}"; StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
_isLoading = false; // Allow saving after initial load _isLoading = false;
} }
private void OnLanguageChanged(object? sender, EventArgs e) private void OnLanguageChanged(object? sender, EventArgs e)
@@ -225,6 +249,7 @@ public partial class SettingsViewModel : ViewModelBase
OnPropertyChanged(nameof(SettingsSaved)); OnPropertyChanged(nameof(SettingsSaved));
OnPropertyChanged(nameof(SettingsSaveFailed)); OnPropertyChanged(nameof(SettingsSaveFailed));
OnPropertyChanged(nameof(SettingsProxyRestartHint)); OnPropertyChanged(nameof(SettingsProxyRestartHint));
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
} }
private void LoadLanguageSettings() private void LoadLanguageSettings()
@@ -238,7 +263,7 @@ public partial class SettingsViewModel : ViewModelBase
{ {
if (value) if (value)
{ {
// Auto-detect system language // 使用操作系统语言。
var systemCulture = CultureInfo.InstalledUICulture.Name; var systemCulture = CultureInfo.InstalledUICulture.Name;
ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US"); ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US");
} }
@@ -294,12 +319,12 @@ public partial class SettingsViewModel : ViewModelBase
private void LoadSettings() private void LoadSettings()
{ {
// Load network settings // 加载代理设置。
IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false; IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false;
ProxyIp = _globalOptions.NetworkOptions?.Ip ?? "127.0.0.1"; 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; var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
if (lyricsConfig != null) if (lyricsConfig != null)
{ {
@@ -307,11 +332,15 @@ public partial class SettingsViewModel : ViewModelBase
IsOneLineMode = lyricsConfig.IsOneLine; IsOneLineMode = lyricsConfig.IsOneLine;
SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles; SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles;
SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8"; SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8";
if (!AvailableEncodings.Contains(SelectedEncoding))
{
AvailableEncodings.Add(SelectedEncoding);
}
IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation; IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation;
SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak); SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak);
} }
// Load block word settings // 加载屏蔽词设置。
var blockWord = _globalOptions.Provider?.Tag?.BlockWord; var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
if (blockWord != null) if (blockWord != null)
{ {
@@ -321,7 +350,7 @@ public partial class SettingsViewModel : ViewModelBase
: blockWord.FilePath; : blockWord.FilePath;
} }
// Load romanized output flag from the NetEase provider's extended options // 罗马音开关保存在网易云提供者的扩展设置中。
var netEase = _globalOptions.Provider?.Lyric?.Plugin? var netEase = _globalOptions.Provider?.Lyric?.Plugin?
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase)); .FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
if (netEase?.Additional != null && if (netEase?.Additional != null &&
@@ -330,9 +359,7 @@ public partial class SettingsViewModel : ViewModelBase
IsRomanOutputEnabled = string.Equals(romanValue, "true", StringComparison.OrdinalIgnoreCase); IsRomanOutputEnabled = string.Equals(romanValue, "true", StringComparison.OrdinalIgnoreCase);
} }
// Tag providers are listed in ascending priority, which is also the order the loader tries // 启用的提供者按优先级排列,禁用项放到末尾。
// them in. The list itself is the order now: the number is derived from the position, so a
// row that is moved up shows a smaller number without any extra bookkeeping.
var tagProviders = _globalOptions.Provider?.Tag?.Plugin; var tagProviders = _globalOptions.Provider?.Tag?.Plugin;
if (tagProviders != null) if (tagProviders != null)
{ {
@@ -341,8 +368,7 @@ public partial class SettingsViewModel : ViewModelBase
AddTagProviderRow(provider.Name, true); AddTagProviderRow(provider.Name, true);
} }
// Disabled sources (priority -1) have no slot of their own; they sit at the bottom of // 禁用项不参与搜索。
// the list, greyed out, so re-enabling one just drops it back into the queue.
foreach (var provider in tagProviders.Where(p => p.Priority == -1)) foreach (var provider in tagProviders.Where(p => p.Priority == -1))
{ {
AddTagProviderRow(provider.Name, false); AddTagProviderRow(provider.Name, false);
@@ -351,7 +377,7 @@ public partial class SettingsViewModel : ViewModelBase
NormalizeProviderOrder(TagProviders); NormalizeProviderOrder(TagProviders);
} }
// Lyrics providers follow the same rule as the tag providers above. // 歌词提供者与标签提供者采用相同排序规则。
var providers = _globalOptions.Provider?.Lyric?.Plugin; var providers = _globalOptions.Provider?.Lyric?.Plugin;
if (providers != null) if (providers != null)
{ {
@@ -377,13 +403,11 @@ public partial class SettingsViewModel : ViewModelBase
IsEnabled = isEnabled IsEnabled = isEnabled
}; };
// The arrows move the row inside its own list; the callback has to be installed after the // 创建行后绑定移动命令。
// row exists, otherwise the lambda would capture an unassigned local.
row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, -1)); row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, -1));
row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, 1)); row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, 1));
// Rows are separate objects, so their own change notifications have to be wired back into // 将行内编辑接入自动保存。
// the save pipeline or the checkbox moves and the file never changes.
row.PropertyChanged += OnProviderRowChanged; row.PropertyChanged += OnProviderRowChanged;
TagProviders.Add(row); TagProviders.Add(row);
} }
@@ -403,11 +427,7 @@ public partial class SettingsViewModel : ViewModelBase
LyricsProviders.Add(row); LyricsProviders.Add(row);
} }
/// <summary> /// <summary>提供者启用状态改变后重新排序并保存。</summary>
/// Any edit inside a provider row funnels into the same debounced save that the top-level
/// settings use. Toggling a checkbox also re-sorts the list, because enabled sources always
/// sit above disabled ones and the visible numbering has to follow.
/// </summary>
private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{ {
if (_isLoading || _isNormalizing) if (_isLoading || _isNormalizing)
@@ -442,11 +462,7 @@ public partial class SettingsViewModel : ViewModelBase
private bool _isNormalizing; private bool _isNormalizing;
/// <summary> /// <summary>启用项在前,优先级按可见顺序从一开始。</summary>
/// The list order <em>is</em> the search order. This enforces the two invariants that make that
/// readable: enabled rows above disabled ones, and a visible 1..n numbering that matches the
/// position. Priorities are derived here, never typed by hand.
/// </summary>
private void NormalizeProviderOrder<T>(ObservableCollection<T> rows) where T : class, IProviderRowViewModel 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(); var ordered = rows.Where(r => r.IsEnabled).Concat(rows.Where(r => !r.IsEnabled)).ToList();
@@ -465,8 +481,7 @@ public partial class SettingsViewModel : ViewModelBase
{ {
var row = ordered[i]; var row = ordered[i];
// 禁用行在内存里就写 -1,和配置文件里的语义保持一致;否则一旦某条路径漏掉 // 禁用项统一使用 -1。
// ApplyProviderSelection,就会把一个不存在的「第 5 名」写回 config.yaml。
row.Priority = i < enabledCount ? i + 1 : -1; row.Priority = i < enabledCount ? i + 1 : -1;
row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—"; row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—";
row.CanMoveUp = i > 0 && i < enabledCount; row.CanMoveUp = i > 0 && i < enabledCount;
@@ -474,11 +489,7 @@ public partial class SettingsViewModel : ViewModelBase
} }
} }
/// <summary> /// <summary>在启用项范围内移动提供者。</summary>
/// Moves a row one slot up or down. Disabled rows are pinned to the bottom, so a move that
/// would cross the enabled/disabled boundary is ignored rather than silently doing nothing
/// visible.
/// </summary>
private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset) private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset)
where T : class, IProviderRowViewModel where T : class, IProviderRowViewModel
{ {
@@ -513,7 +524,7 @@ public partial class SettingsViewModel : ViewModelBase
} }
} }
return 0; return -1;
} }
private void WriteSettingsToOptions() private void WriteSettingsToOptions()
@@ -551,18 +562,12 @@ public partial class SettingsViewModel : ViewModelBase
netEase.Additional["isEnableRomanOutput"] = IsRomanOutputEnabled ? "true" : "false"; netEase.Additional["isEnableRomanOutput"] = IsRomanOutputEnabled ? "true" : "false";
} }
// Provider toggles are not decoration: unchecking writes priority -1, which is how the // 同步启用状态及搜索顺序。
// downloader skips a source. Without this the checkboxes move and the file never changes.
ApplyProviderSelection(_globalOptions.Provider?.Lyric?.Plugin, LyricsProviders); ApplyProviderSelection(_globalOptions.Provider?.Lyric?.Plugin, LyricsProviders);
ApplyProviderSelection(_globalOptions.Provider?.Tag?.Plugin, TagProviders); ApplyProviderSelection(_globalOptions.Provider?.Tag?.Plugin, TagProviders);
} }
/// <summary> /// <summary>将歌词提供者的界面顺序写入共享配置。</summary>
/// Push the row state onto the options: the checkbox decides whether a source runs at all
/// (disabled sources store -1, which is how the downloader skips them) and the list position
/// decides the search order. The number in the UI is derived from that position, so there is
/// nothing to reconcile here — no duplicate slots, no silent renumbering.
/// </summary>
private static void ApplyProviderSelection( private static void ApplyProviderSelection(
IEnumerable<LyricsProviderOptions>? options, IEnumerable<LyricsProviderOptions>? options,
IEnumerable<LyricsProviderSettingViewModel> viewModels) IEnumerable<LyricsProviderSettingViewModel> viewModels)
@@ -611,18 +616,22 @@ public partial class SettingsViewModel : ViewModelBase
} }
} }
private async Task SaveSettingsAsync() private async Task SaveSettingsAsync(CancellationToken cancellationToken = default)
{ {
// Debounce rapid changes (dragging a port spinner, typing an IP) into one write. // 合并连续输入,但配置在内存中立即生效。
var pending = Interlocked.Increment(ref _saveRequestId); var pending = Interlocked.Increment(ref _saveRequestId);
await Task.Delay(SaveDebounceMilliseconds).ConfigureAwait(true); await Task.Delay(SaveDebounceMilliseconds, cancellationToken).ConfigureAwait(true);
if (pending != Volatile.Read(ref _saveRequestId)) if (pending != Volatile.Read(ref _saveRequestId))
{ {
return; return;
} }
var result = await _settingsStore.SaveAsync().ConfigureAwait(true); var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
if (pending != Volatile.Read(ref _saveRequestId))
{
return;
}
HasSaveError = !result.IsSuccess; HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess SaveStatusText = result.IsSuccess
@@ -635,12 +644,13 @@ public partial class SettingsViewModel : ViewModelBase
private const int SaveDebounceMilliseconds = 400; private const int SaveDebounceMilliseconds = 400;
[RelayCommand] [RelayCommand]
private async Task ResetToDefaults() private async Task ResetToDefaultsAsync(CancellationToken cancellationToken = default)
{ {
_isLoading = true; // Prevent multiple saves during reset Interlocked.Increment(ref _saveRequestId);
_isLoading = true;
IsProxyEnabled = false; IsProxyEnabled = false;
ProxyIp = "127.0.0.1"; ProxyIp = "127.0.0.1";
ProxyPort = 7890; ProxyPort = 4780;
IsTranslationEnabled = true; IsTranslationEnabled = true;
IsOneLineMode = true; IsOneLineMode = true;
SkipExistingLyrics = false; SkipExistingLyrics = false;
@@ -651,9 +661,9 @@ public partial class SettingsViewModel : ViewModelBase
BlockWordFilePath = "BlockWords.json"; BlockWordFilePath = "BlockWords.json";
IsRomanOutputEnabled = false; IsRomanOutputEnabled = false;
// Provider rows are settings too; leaving a disabled source behind after "reset" would // 恢复随程序附带的默认顺序,额外提供者保留在末尾。
// look like the button half worked. Everything comes back enabled, in the order the rows RestoreProviderOrder(LyricsProviders, ["NetEase", "QQ", "KuGou", "KuWo"], row => row.Name);
// are listed, which the numbering then reflects as 1..n again. RestoreProviderOrder(TagProviders, ["Taglib", "FileName"], row => row.Name);
foreach (var row in LyricsProviders) foreach (var row in LyricsProviders)
{ {
row.IsEnabled = true; row.IsEnabled = true;
@@ -669,44 +679,59 @@ public partial class SettingsViewModel : ViewModelBase
_isLoading = false; _isLoading = false;
// Save once after all resets // 所有默认值恢复后只保存一次。
WriteSettingsToOptions(); WriteSettingsToOptions();
var result = await _settingsStore.SaveAsync().ConfigureAwait(true); var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
HasSaveError = !result.IsSuccess; HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess SaveStatusText = result.IsSuccess
? $"{SettingsSaved}: {result.FilePath}" ? $"{SettingsSaved}: {result.FilePath}"
: $"{SettingsSaveFailed}: {result.ErrorMessage}"; : $"{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++);
}
}
}
} }
/// <summary> /// <summary>可排序的提供者设置行。</summary>
/// Shared shape of a source row so the reordering logic can work on both lists without
/// duplicating it. The visible order is the search order; <see cref="Priority"/> and
/// <see cref="PriorityLabel"/> are written by the view model, never typed by the user.
/// </summary>
public interface IProviderRowViewModel public interface IProviderRowViewModel
{ {
/// <summary>是否启用。</summary>
bool IsEnabled { get; set; } bool IsEnabled { get; set; }
/// <summary>搜索优先级,禁用时为 -1。</summary>
int Priority { get; set; } int Priority { get; set; }
/// <summary>界面显示的顺序。</summary>
string PriorityLabel { get; set; } string PriorityLabel { get; set; }
/// <summary>是否可以向上移动。</summary>
bool CanMoveUp { get; set; } bool CanMoveUp { get; set; }
/// <summary>是否可以向下移动。</summary>
bool CanMoveDown { get; set; } bool CanMoveDown { get; set; }
/// <summary> /// <summary>禁用时降低行透明度。</summary>
/// Dimming for disabled rows: they are out of the running and pinned to the bottom, so they
/// should read as inactive rather than as just another entry.
/// </summary>
double RowOpacity { get; } double RowOpacity { get; }
/// <summary>向上移动命令。</summary>
IRelayCommand MoveUpCommand { get; } IRelayCommand MoveUpCommand { get; }
/// <summary>向下移动命令。</summary>
IRelayCommand MoveDownCommand { get; } IRelayCommand MoveDownCommand { get; }
} }
/// <summary>歌词提供者设置行。</summary>
public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{ {
[ObservableProperty] [ObservableProperty]
@@ -716,17 +741,11 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[NotifyPropertyChangedFor(nameof(RowOpacity))] [NotifyPropertyChangedFor(nameof(RowOpacity))]
private bool _isEnabled; private bool _isEnabled;
/// <summary> /// <summary>搜索优先级,禁用时为 -1。</summary>
/// Search order derived from the row position, smaller runs first. Disabled rows keep the
/// number they would occupy but are written as -1, which is how the downloader skips them.
/// </summary>
[ObservableProperty] [ObservableProperty]
private int _priority; private int _priority;
/// <summary> /// <summary>显示的顺序,禁用时显示横线。</summary>
/// What the list shows in the number column: the position, or a dash once the row is disabled
/// and pushed to the bottom.
/// </summary>
[ObservableProperty] [ObservableProperty]
private string _priorityLabel = string.Empty; private string _priorityLabel = string.Empty;
@@ -736,13 +755,17 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[ObservableProperty] [ObservableProperty]
private bool _canMoveDown; private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45; public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { }); public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { }); public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
} }
/// <summary>标签提供者设置行。</summary>
public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{ {
[ObservableProperty] [ObservableProperty]
@@ -766,9 +789,12 @@ public partial class TagInfoProviderSettingViewModel : ObservableObject, IProvid
[ObservableProperty] [ObservableProperty]
private bool _canMoveDown; private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45; public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { }); public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { }); public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
} }
@@ -16,7 +16,7 @@
FontWeight="SemiBold" FontWeight="SemiBold"
Margin="0,0,0,12" /> Margin="0,0,0,12" />
<!-- Message. 用只读 TextBox 而不是 TextBlock,这样正文可以被选中复制。 --> <!-- 正文可选中并复制。 -->
<TextBox Grid.Row="1" <TextBox Grid.Row="1"
x:Name="MessageText" x:Name="MessageText"
IsReadOnly="True" IsReadOnly="True"
@@ -20,7 +20,7 @@
Opacity="0.65" Opacity="0.65"
TextWrapping="Wrap" /> TextWrapping="Wrap" />
<!-- QR surface: fixed size so the dialog does not jump when the image arrives. --> <!-- 固定二维码区域尺寸,避免加载时窗口跳动。 -->
<Border Width="240" Height="240" <Border Width="240" Height="240"
HorizontalAlignment="Center" HorizontalAlignment="Center"
Background="White" Background="White"
@@ -4,15 +4,24 @@ using ZonyLrcTools.Desktop.ViewModels;
namespace ZonyLrcTools.Desktop.Views.Dialogs; namespace ZonyLrcTools.Desktop.Views.Dialogs;
/// <summary>
/// 网易云扫码登录窗口。
/// </summary>
public partial class QrCodeLoginDialog : Window public partial class QrCodeLoginDialog : Window
{ {
private QrCodeLoginViewModel? _viewModel; private QrCodeLoginViewModel? _viewModel;
/// <summary>
/// 初始化登录窗口。
/// </summary>
public QrCodeLoginDialog() public QrCodeLoginDialog()
{ {
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// 使用指定登录状态创建窗口。
/// </summary>
public QrCodeLoginDialog(QrCodeLoginViewModel viewModel) : this() public QrCodeLoginDialog(QrCodeLoginViewModel viewModel) : this()
{ {
_viewModel = viewModel; _viewModel = viewModel;
@@ -77,7 +77,6 @@
MinWidth="108" /> MinWidth="108" />
<Button Content="{Binding DecryptClear}" <Button Content="{Binding DecryptClear}"
Command="{Binding ClearFilesCommand}" Command="{Binding ClearFilesCommand}"
IsEnabled="{Binding CanClear}"
MinWidth="88" /> MinWidth="88" />
</StackPanel> </StackPanel>
@@ -2,8 +2,14 @@ using Avalonia.Controls;
namespace ZonyLrcTools.Desktop.Views.Pages; namespace ZonyLrcTools.Desktop.Views.Pages;
/// <summary>
/// 音乐解密页面。
/// </summary>
public partial class DecryptPage : UserControl public partial class DecryptPage : UserControl
{ {
/// <summary>
/// 初始化音乐解密页面。
/// </summary>
public DecryptPage() public DecryptPage()
{ {
InitializeComponent(); InitializeComponent();
@@ -36,6 +36,7 @@
<ComboBox Grid.Column="1" <ComboBox Grid.Column="1"
ItemsSource="{Binding ScannerNames}" ItemsSource="{Binding ScannerNames}"
SelectedIndex="{Binding SelectedScannerIndex}" SelectedIndex="{Binding SelectedScannerIndex}"
IsEnabled="{Binding CanEditInputs}"
MinWidth="200" MinWidth="200"
HorizontalAlignment="Left" HorizontalAlignment="Left"
Margin="16,0" /> Margin="16,0" />
@@ -97,6 +98,7 @@
FontWeight="Medium" /> FontWeight="Medium" />
<TextBox Grid.Column="1" <TextBox Grid.Column="1"
Text="{Binding SongListIds}" Text="{Binding SongListIds}"
IsEnabled="{Binding CanEditInputs}"
Watermark="{Binding LyricsSongListWatermark}" Watermark="{Binding LyricsSongListWatermark}"
Margin="16,0" /> Margin="16,0" />
<Button Grid.Column="2" <Button Grid.Column="2"
@@ -114,8 +116,7 @@
MinWidth="88" /> MinWidth="88" />
</Grid> </Grid>
<!-- Account state stays visible even when this scanner is not selected, so the <!-- 显示当前网易云登录状态。 -->
sign-out entry is no longer hidden behind one dropdown value. -->
<Grid ColumnDefinitions="Auto,*,Auto"> <Grid ColumnDefinitions="Auto,*,Auto">
<PathIcon Grid.Column="0" <PathIcon Grid.Column="0"
Data="{StaticResource AccountIcon}" Data="{StaticResource AccountIcon}"
@@ -18,6 +18,7 @@
<PackageReference Include="Avalonia.Fonts.Inter" /> <PackageReference Include="Avalonia.Fonts.Inter" />
<PackageReference Include="Avalonia.Controls.DataGrid" /> <PackageReference Include="Avalonia.Controls.DataGrid" />
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" /> <PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="Tmds.DBus.Protocol" />
<!-- MVVM --> <!-- MVVM -->
<PackageReference Include="CommunityToolkit.Mvvm" /> <PackageReference Include="CommunityToolkit.Mvvm" />
<!-- DI & Hosting --> <!-- DI & Hosting -->
@@ -30,29 +31,12 @@
<PackageReference Include="System.Text.Encoding.CodePages" /> <PackageReference Include="System.Text.Encoding.CodePages" />
<!-- Localization --> <!-- Localization -->
<PackageReference Include="Microsoft.Extensions.Localization" /> <PackageReference Include="Microsoft.Extensions.Localization" />
<!-- QR code rendering for the NetEase QR login dialog --> <!-- 网易云扫码登录所需的二维码生成器 -->
<PackageReference Include="QRCoder" /> <PackageReference Include="QRCoder" />
</ItemGroup> </ItemGroup>
<!-- <!-- 指定运行平台时默认裁剪,可通过 -p:PublishTrimmed=false 关闭。
Trimming is ON by default for RID-specific publishes, taking the self-contained win-x64 反射注入、序列化和无障碍访问所需程序集由 ILLink.Descriptors.xml 保留。 -->
output from ~108 MB to ~51 MB. Pass -p:PublishTrimmed=false to get the untrimmed build.
Trimming is not free here, which is why ILLink.Descriptors.xml exists. Two things in this
app are resolved by reflection and would silently vanish from a naive trim:
- the DI container, populated by GetTypes() over ZonyLrcTools.Common, and
- Avalonia's automation peers, which is what Windows UI Automation asks for by name.
Lose the first and the app starts then throws "No service for type ... has been registered"
the moment a page is opened; lose the second and the window renders fine while its UIA tree
is empty, taking Narrator and every automation script with it. Both are rooted in that file.
TrimMode=partial keeps method bodies intact and only drops whole unreferenced assemblies,
which is the conservative choice: the size win comes from the framework, not from risking
half an assembly that something reflects over.
The condition also keeps plain `dotnet build` (no RID) unaffected: trimming needs a runtime
identifier, so there is nothing to opt into there.
-->
<PropertyGroup Condition="'$(RuntimeIdentifier)' != '' AND '$(PublishTrimmed)' == ''"> <PropertyGroup Condition="'$(RuntimeIdentifier)' != '' AND '$(PublishTrimmed)' == ''">
<PublishTrimmed>true</PublishTrimmed> <PublishTrimmed>true</PublishTrimmed>
</PropertyGroup> </PropertyGroup>
@@ -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);
}
}
}
@@ -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 System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Shouldly; using Shouldly;
@@ -7,16 +8,31 @@ using ZonyLrcTools.Common.MusicDecryption;
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
{ {
/// <summary>
/// 使用真实 NCM 样本验证解密。
/// </summary>
public class NcmMusicDecryptorTests : TestBase public class NcmMusicDecryptorTests : TestBase
{ {
/// <summary>
/// 每次使用独立目录,避免历史输出影响解密结果。
/// </summary>
[Fact] [Fact]
public async Task ConvertMusicAsync_Test() public async Task ConvertMusicAsync_DecryptsNcmAsync()
{
var directory = Directory.CreateTempSubdirectory("zony-ncm-tests-").FullName;
try
{ {
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>(); var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
var ncmFilePath = Path.Combine(Directory.GetCurrentDirectory(), "MusicFiles", "Loren Gray - Queen.ncm"); 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); var result = await decryptor.ConvertMusicAsync(ncmFilePath);
result.IsSuccess.ShouldBeTrue(); 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> <ItemGroup>
<ProjectReference Include="..\..\src\ZonyLrcTools.Cli\ZonyLrcTools.Cli.csproj" /> <ProjectReference Include="..\..\src\ZonyLrcTools.Cli\ZonyLrcTools.Cli.csproj" />
<ProjectReference Include="..\..\src\ZonyLrcTools.Desktop\ZonyLrcTools.Desktop.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+13 -3
View File
@@ -1,7 +1,17 @@
New Features: None New Features:
Breaking Changes: None - [#172] Complete the Avalonia desktop workflow and add KGG decryption using a matching KuGou database.
Enhancement: None
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: 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.