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
+2787 -1182

No files matched your search

+9 -8
View File
@@ -61,15 +61,9 @@ jobs:
working-directory: ./src/ZonyLrcTools.Desktop
run: |
dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true -p:UseAppHost=true -p:DebugType=none --self-contained true
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
if ($LASTEXITCODE -ne 0) { throw '桌面端发布失败' }
shell: pwsh
# Microsoft.Data.Sqlite 的原生库不会被打进单文件 exe,漏了它 .kgg 解密会在运行时直接失败。
# 这里在打包后做一次校验,让 CI 在发布环节而不是在用户机器上暴露问题。
#
# 顺带盯着裁剪有没有真的生效:项目默认开了 PublishTrimmed,但裁剪可以被环境变量、
# 命令行参数或者一次 csproj 手滑静默关掉,而关掉之后唯一的症状就是包变大 55 MB。
# 用一个宽阈值(90 MB)而不是精确值,是因为框架版本升级会让体积小幅波动。
# 单文件发布仍需附带 SQLite 原生库、配置模板及第三方许可声明。
- name: Verify Desktop publish output
working-directory: ./src/ZonyLrcTools.Desktop
run: |
@@ -79,6 +73,7 @@ jobs:
if (-not (Test-Path $exe)) { throw "缺少主程序: $exe" }
if (-not (Test-Path $sqlite)) { throw "缺少 SQLite 原生库: $sqlite(.kgg 解密依赖它)" }
if (-not (Test-Path (Join-Path $publish 'config.yaml'))) { throw '缺少 config.yaml 模板' }
if (-not (Test-Path (Join-Path $publish 'THIRD-PARTY-NOTICES.md'))) { throw '缺少第三方许可声明' }
$totalMb = [math]::Round(((Get-ChildItem $publish -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1MB), 1)
Write-Host "publish 目录校验通过:$((Get-ChildItem $publish -File).Count) 个文件,共 $totalMb MB"
@@ -86,6 +81,12 @@ jobs:
throw "publish 目录有 $totalMb MB,超过 90 MB 上限;这通常意味着 PublishTrimmed 被关掉了"
}
shell: pwsh
- name: Package Desktop
working-directory: ./src/ZonyLrcTools.Desktop
run: |
New-Item -ItemType Directory -Force -Path ./TempFiles | Out-Null
Compress-Archive -Path ./bin/Release/net10.0/win-x64/publish/* -DestinationPath ./TempFiles/ZonyLrcTools.Desktop_win-x64_${{ steps.date.outputs.date }}.zip -Force
shell: pwsh
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
+2
View File
@@ -51,6 +51,8 @@
<PackageVersion Include="Avalonia.Fonts.Inter" Version="11.2.3" />
<PackageVersion Include="Avalonia.Diagnostics" Version="11.2.3" />
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="11.2.3" />
<!-- Avalonia 的 Linux D-Bus 依赖:使用包含安全修复的兼容分支。 -->
<PackageVersion Include="Tmds.DBus.Protocol" Version="0.21.3" />
<!-- MVVM -->
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<!-- Localization -->
+15 -1
View File
@@ -8,7 +8,7 @@ English | [简体中文](./docs/zh_CN.md)
# Introduction
ZonyLrcToolX 4 is a cross-platform lyrics download tool based on CEF. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
ZonyLrcToolX 4 is a cross-platform lyrics download tool with a .NET 10 CLI and an Avalonia desktop application. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
🚧 The current version is under development.
🚧 If you want to see working code, please switch to the dev branch.
@@ -31,6 +31,20 @@ ZonyLrcTools.Cli --help
# Usage
Detailed usage instructions have been moved to a new documentation site. Please visit [https://docs.myzony.com](https://docs.myzony.com) for complete documentation.
## Run a contribution locally
Fork pull requests can be checked out without merging or obtaining write access to the contributor's repository. From the repository root, use a new branch and directory (replace `172` with the PR number):
```bash
git fetch origin pull/172/head
git worktree add ../ZonyLrcToolsX-pr-172 -b review/pr-172 FETCH_HEAD
cd ../ZonyLrcToolsX-pr-172
dotnet run --project src/ZonyLrcTools.Desktop -c Release
```
Requires .NET SDK 10. Local changes do not update the PR until explicitly committed and pushed. See [desktop notes](./docs/en_US.md#desktop-development) for publishing, configuration and manual verification.
# Donation
[爱发电](https://afdian.net/a/zony-lrc-tools)
+19 -1
View File
@@ -8,7 +8,7 @@ English | [简体中文](./zh_CN.md)
# Introduction
ZonyLrcToolX 4 is a cross-platform lyrics download tool based on CEF. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
ZonyLrcToolX 4 is a cross-platform lyrics download tool with a .NET 10 CLI and an Avalonia desktop application. **QQ Group: 337656932**. Detailed video tutorials are available in the group files.
🚧 The current version is under development.
🚧 If you want to see working code, please switch to the dev branch.
@@ -31,6 +31,24 @@ ZonyLrcTools.Cli --help
# Usage
Detailed usage instructions have been moved to a new documentation site. Please visit [https://docs.myzony.com](https://docs.myzony.com) for complete documentation.
## Desktop development
Requires .NET SDK 10. Run from the repository root:
```bash
dotnet run --project src/ZonyLrcTools.Desktop -c Release
dotnet publish src/ZonyLrcTools.Desktop -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
```
CI distributes Windows x64. For local builds, choose the appropriate RID, such as `osx-arm64`. RID-specific desktop builds enable trimming by default; pass `-p:PublishTrimmed=false` to disable it. Publish success is not a substitute for testing the target OS. Keep the entire publish directory, including native SQLite/Avalonia libraries, configuration and `THIRD-PARTY-NOTICES.md`.
Settings use the writable executable directory, falling back to the user's application data directory. Saving preserves unknown YAML fields and comments; unsupported anchored or multiline values fail without overwriting the file. `netease.session.json` contains login credentials: never share or commit it. Unix restricts it to the current user; Windows inherits directory permissions. Relative block-word paths resolve against the current working directory.
KGG decryption requires a matching `KGMusicV3.db` containing that file's key. Automatic database discovery covers Windows KuGou locations; a matching database can also be selected manually. Existing decrypted audio is not overwritten and is reported as an output conflict. Cancellation prevents publishing partial output, but providers and third-party decryptors without cancellation support must finish their in-flight call first.
Before merging, manually check navigation, language/theme changes, local lyrics and cover downloads, cancel/restart, QR login/logout/restart, settings save/restart, and KGG with a real matching database. Synthetic decryption tests do not establish compatibility with every client format.
# Donation
[爱发电](https://afdian.net/a/zony-lrc-tools)
+19 -1
View File
@@ -8,7 +8,7 @@
# 简介
ZonyLrcToolX 4 是一个基于 CEF 的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。
ZonyLrcToolX 4 是一个提供 .NET 10 CLI 和 Avalonia 桌面界面的跨平台歌词下载工具,**QQ 群:337656932**,群文件里面有详细的视频教程。
🚧 当前版本正在开发当中。
🚧 如果你想查看可以工作的代码,请切换到 dev 分支。
@@ -32,6 +32,24 @@ ZonyLrcTools.Cli --help
软件的具体使用方法已经迁移到了全新的文档站点,请跳转到 [https://docs.myzony.com](https://docs.myzony.com),里面包含完整的说明文档。
## 桌面端本地开发
需要 .NET SDK 10。在仓库根目录执行:
```bash
dotnet run --project src/ZonyLrcTools.Desktop -c Release
dotnet publish src/ZonyLrcTools.Desktop -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true
```
CI 分发 Windows x64 版本。本机发布请选择对应 RID,例如 Apple Silicon 使用 `osx-arm64`。指定 RID 时桌面端默认开启裁剪,使用 `-p:PublishTrimmed=false` 可以关闭。发布成功不等于目标系统上的功能验收通过。分发时保留整个发布目录,包括 SQLite/Avalonia 原生库、配置和 `THIRD-PARTY-NOTICES.md`。
配置优先保存在可写的程序目录,否则回退到用户应用数据目录。保存时保留未知 YAML 字段和注释;无法安全修改的锚点或多行值会明确报错,不覆盖原文件。`netease.session.json` 包含登录凭据,不要分享或提交到仓库。Unix 仅允许当前用户读写,Windows 继承目录权限。屏蔽词字典的相对路径以当前工作目录为基准。
KGG 解密需要包含对应文件密钥的 `KGMusicV3.db`。自动查找覆盖 Windows 酷狗目录,也可手动选择匹配的数据库。已有解密音频不会被覆盖,而是报告输出冲突。取消后不会发布不完整文件;不支持取消的歌词源、封面源及第三方解密器仍需等待当前调用返回。
合并前请手动检查:导航与语言/主题切换、本地歌词和封面下载、取消后重启任务、扫码登录/退出/重启、设置保存后重启,以及真实 KGG 配合匹配数据库的解密。合成解密测试不能代替所有客户端格式的兼容性验证。fork PR 的独立检出步骤见 [README](../README.md#run-a-contribution-locally)。
# 捐赠
[爱发电](https://afdian.net/a/zony-lrc-tools)
@@ -41,14 +41,14 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand
{
_logger.LogInformation("开始扫描文件夹,请稍等...");
var files = (await _fileScanner.ScanAsync(Source, DecryptoFactory.KnownExtensions.Select(x => $"*{x}")))
var files = (await _fileScanner.ScanAsync(Source,
DecryptoFactory.KnownExtensions.Append(".kgg").Distinct().Select(x => $"*{x}")))
.SelectMany(f => f.FilePaths)
.ToList();
_logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。");
// WarpTask.Dispose 会取消令牌并同步等待所有槽位释放,漏掉 using 就会
// 泄漏 CTS/Semaphore,并让终结器线程去做阻塞等待。
// 等待转换结束后释放并发控制资源。
using var wrapTask = new WarpTask(4);
var tasks = files.Select(path => wrapTask.RunAsync(async () =>
{
@@ -1,16 +1,17 @@
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Extensions;
using ZonyLrcTools.Common.Infrastructure.IO;
using ZonyLrcTools.Common.Infrastructure.Logging;
using ZonyLrcTools.Common.Infrastructure.Threading;
namespace ZonyLrcTools.Common.Album;
/// <inheritdoc />
public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
{
private readonly IEnumerable<IAlbumProvider> _albumProviders;
/// <inheritdoc />
public IEnumerable<IAlbumProvider> AvailableProviders => new Lazy<IEnumerable<IAlbumProvider>>(() =>
{
return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
@@ -18,6 +19,9 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
private readonly IWarpLogger _logger;
/// <summary>
/// 创建专辑封面下载器。
/// </summary>
public AlbumDownloader(IEnumerable<IAlbumProvider> albumProviders,
IWarpLogger logger)
{
@@ -25,39 +29,20 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
_logger = logger;
}
/// <inheritdoc />
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
int parallelCount = 2,
Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default)
{
await _logger.InfoAsync("开始下载专辑图像数据...");
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
if (provider == null)
foreach (var info in needDownloadMusicInfos)
{
// 没有任何可用的专辑图像源,全部标记为失败并回调,避免调用方一直等待。
foreach (var info in needDownloadMusicInfos)
{
info.IsSuccessful = false;
if (callback == null)
{
continue;
}
try
{
await callback(info);
}
catch (Exception ex)
{
await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。");
}
}
return;
info.IsSuccessful = false;
}
cancellationToken.ThrowIfCancellationRequested();
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
if (parallelCount <= 0)
{
parallelCount = 1;
@@ -72,59 +57,81 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
{
cancellationToken.ThrowIfCancellationRequested();
var album = await provider.DownloadAsync(info.Name, info.Artist);
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
if (album.Length <= 0)
{
info.IsSuccessful = false;
return;
}
// 已存在同名图像视为成功,不重复覆盖用户已有的封面。
var filePath = Path.ChangeExtension(info.FilePath, ".png");
if (File.Exists(filePath))
{
info.IsSuccessful = true;
return;
}
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album);
if (provider == null)
{
return;
}
var album = await provider.DownloadAsync(info.Name, info.Artist);
cancellationToken.ThrowIfCancellationRequested();
if (album.Length == 0)
{
return;
}
var temporaryPath = $"{filePath}.{Guid.NewGuid():N}.tmp";
try
{
await File.WriteAllBytesAsync(temporaryPath, album, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
// 完整写入后再发布,且不覆盖其他任务或用户刚创建的封面。
try
{
File.Move(temporaryPath, filePath);
}
catch (IOException) when (File.Exists(filePath))
{
// 目标已由其他任务生成,保留已有封面。
}
}
finally
{
File.Delete(temporaryPath);
}
info.IsSuccessful = true;
_logger.LogSuccessful(info);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (ErrorCodeException ex)
{
info.IsSuccessful = false;
_logger.LogWarningInfo(ex);
}
catch (OperationCanceledException)
{
info.IsSuccessful = false;
}
catch (Exception ex)
{
info.IsSuccessful = false;
await _logger.ErrorAsync($"下载专辑图像时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
await _logger.ErrorAsync("下载专辑图像失败。", ex);
}
finally
{
// 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。
if (callback != null)
{
try
{
await callback(info);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。");
await _logger.WarnAsync("处理专辑下载回调失败。", ex);
}
}
}
}, cancellationToken), cancellationToken));
await Task.WhenAll(warpTaskList);
cancellationToken.ThrowIfCancellationRequested();
await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。");
}
@@ -1,5 +1,8 @@
namespace ZonyLrcTools.Common.Album;
/// <summary>
/// 下载歌曲对应的专辑封面。
/// </summary>
public interface IAlbumDownloader
{
/// <summary>
@@ -14,5 +17,8 @@ public interface IAlbumDownloader
Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 可用的专辑封面来源。
/// </summary>
IEnumerable<IAlbumProvider> AvailableProviders { get; }
}
@@ -1,6 +1,4 @@
using System.Text;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Logging;
@@ -19,26 +17,19 @@ namespace ZonyLrcTools.Common.Infrastructure.Extensions
/// <param name="e">异常实例,可为空。</param>
public static void LogWarningWithErrorCode(this IWarpLogger logger, int errorCode, Exception? e = null)
{
logger.WarnAsync($"错误代码: {errorCode}\n堆栈异常: {e?.StackTrace}").GetAwaiter().GetResult();
logger.WarnAsync($"错误代码: {errorCode}", e).GetAwaiter().GetResult();
}
/// <summary>
/// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。
/// <remarks>
/// 这个方法只负责记录,<b>不会抛出异常</b>。调用点全部位于 catch 块内,
/// 若在此处重新抛出,异常会穿透调用方的 catch 并终止整批任务
/// (例如一首歌的编码配置有误会导致整批歌词下载中断)。
/// 需要向上传播错误时,请由调用方显式决定,而不是让日志方法代劳。
/// </remarks>
/// 记录错误码与异常,不重新抛出业务异常。
/// </summary>
/// <param name="logger">日志记录器的实例。</param>
/// <param name="exception">错误码异常实例。</param>
public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception)
{
var sb = new StringBuilder();
sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}");
sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}");
logger.WarnAsync(sb.ToString()).GetAwaiter().GetResult();
logger.WarnAsync(
$"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}",
exception).GetAwaiter().GetResult();
}
/// <summary>
@@ -18,59 +18,73 @@ namespace ZonyLrcTools.Common.Infrastructure.Network
_httpClientFactory = httpClientFactory;
}
/// <inheritdoc />
public async ValueTask<string> PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null)
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{
using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption);
var responseContentString = await responseMessage.Content.ReadAsStringAsync();
using var responseMessage = await PostReturnHttpResponseAsync(url, parameters, isQueryStringParam, requestOption,
cancellationToken: cancellationToken);
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
return ValidateHttpResponse(responseMessage, parameters, responseContentString);
}
/// <inheritdoc />
public async ValueTask<TResponse> PostAsync<TResponse>(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null)
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{
var responseString = await PostAsync(url, parameters, isQueryStringParam, requestOption);
var responseString = await PostAsync(url, parameters, isQueryStringParam, requestOption,
cancellationToken: cancellationToken);
return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
}
/// <inheritdoc />
public async ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null)
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{
var parametersStr = isQueryStringParam ? BuildQueryString(parameters) : BuildJsonBodyString(parameters);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
using var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
requestMessage.Content = new StringContent(parametersStr);
requestOption?.Invoke(requestMessage);
return await BuildHttpClient().SendAsync(requestMessage);
using var client = BuildHttpClient();
return await client.SendAsync(requestMessage, cancellationToken);
}
/// <inheritdoc />
public async ValueTask<string> GetAsync(string url,
object? parameters = null,
Action<HttpRequestMessage>? requestOption = null)
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{
var requestParamsStr = BuildQueryString(parameters);
var requestMsg = new HttpRequestMessage(HttpMethod.Get, new Uri($"{url}?{requestParamsStr}"));
using var requestMsg = new HttpRequestMessage(HttpMethod.Get, new Uri($"{url}?{requestParamsStr}"));
requestOption?.Invoke(requestMsg);
using var responseMessage = await BuildHttpClient().SendAsync(requestMsg);
var responseContentString = await responseMessage.Content.ReadAsStringAsync();
using var client = BuildHttpClient();
using var responseMessage = await client.SendAsync(requestMsg, cancellationToken);
var responseContentString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
return ValidateHttpResponse(responseMessage, parameters, responseContentString);
}
/// <inheritdoc />
public async ValueTask<TResponse> GetAsync<TResponse>(string url,
object? parameters = null,
Action<HttpRequestMessage>? requestOption = null)
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default)
{
var responseString = await GetAsync(url, parameters, requestOption);
var responseString = await GetAsync(url, parameters, requestOption, cancellationToken: cancellationToken);
return ConvertHttpResponseToObject<TResponse>(parameters, responseString);
}
@@ -12,11 +12,13 @@
/// <param name="parameters">请求的参数。</param>
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
/// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>服务端的响应结果。</returns>
ValueTask<string> PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null);
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 根据指定的配置执行 POST 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
@@ -25,17 +27,28 @@
/// <param name="parameters">请求的参数。</param>
/// <param name="isQueryStringParam">是否以 QueryString 形式携带参数。</param>
/// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
/// <returns>服务端的响应结果。</returns>
ValueTask<TResponse> PostAsync<TResponse>(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null);
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 执行 POST 请求,由调用方释放返回的响应。
/// </summary>
/// <param name="url">请求地址。</param>
/// <param name="parameters">请求参数。</param>
/// <param name="isQueryStringParam">是否将参数编码为查询字符串。</param>
/// <param name="requestOption">请求配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
ValueTask<HttpResponseMessage> PostReturnHttpResponseAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
Action<HttpRequestMessage>? requestOption = null);
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 根据指定的配置执行 GET 请求,并以 <see cref="string"/> 作为返回值。
@@ -43,10 +56,12 @@
/// <param name="url">请求的 URL 地址。</param>
/// <param name="parameters">请求的参数。</param>
/// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>服务端的响应结果。</returns>
ValueTask<string> GetAsync(string url,
object? parameters = null,
Action<HttpRequestMessage>? requestOption = null);
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 根据指定的配置执行 GET 请求,并将结果反序列化为 <see cref="TResponse"/> 对象。
@@ -54,11 +69,13 @@
/// <param name="url">请求的 URL 地址。</param>
/// <param name="parameters">请求的参数。</param>
/// <param name="requestOption">请求时的配置动作。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <typeparam name="TResponse">需要将响应结果反序列化的目标类型。</typeparam>
/// <returns>服务端的响应结果。</returns>
ValueTask<TResponse> GetAsync<TResponse>(
string url,
object? parameters = null,
Action<HttpRequestMessage>? requestOption = null);
Action<HttpRequestMessage>? requestOption = null,
CancellationToken cancellationToken = default);
}
}
@@ -42,8 +42,14 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default)
{
await _logger.InfoAsync("开始下载歌词文件数据...");
foreach (var info in needDownloadMusicInfos)
{
info.IsSuccessful = false;
info.IsPruneMusic = false;
}
cancellationToken.ThrowIfCancellationRequested();
var providers = AvailableProviders.ToArray();
if (parallelCount <= 0)
{
parallelCount = 1;
@@ -54,98 +60,105 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
warpTask.RunAsync(() =>
Task.Run(async () =>
{
// 依次尝试所有可用的歌词来源,直到某一家真正返回了歌词。
// 某个来源返回空结果是「这家没搜到」,不是「这首歌没有歌词」,必须继续问下一家。
var isFinished = false;
var hasProviderError = false;
foreach (var lyricsProvider in AvailableProviders)
try
{
var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info);
var isFinished = false;
var hasProviderError = providers.Length == 0;
if (result == LyricsDownloadResult.Success)
foreach (var lyricsProvider in providers)
{
_logger.LogSuccessful(info);
isFinished = true;
break;
cancellationToken.ThrowIfCancellationRequested();
var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info, cancellationToken);
if (result == LyricsDownloadResult.Success)
{
isFinished = true;
break;
}
hasProviderError |= result == LyricsDownloadResult.Failed;
}
if (result == LyricsDownloadResult.Failed)
cancellationToken.ThrowIfCancellationRequested();
if (!isFinished)
{
hasProviderError = true;
// 只有所有来源均返回空结果时,才按纯音乐处理。
info.IsSuccessful = !hasProviderError;
info.IsPruneMusic = !hasProviderError;
}
}
if (!isFinished)
finally
{
// 所有来源都没有返回歌词。若期间有来源报错,就判为失败;
// 否则说明各家都查无此曲,按纯音乐/未收录处理(与旧版的统计口径保持一致)。
info.IsSuccessful = !hasProviderError;
info.IsPruneMusic = !hasProviderError;
}
// 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。
if (callback != null)
{
try
if (callback != null)
{
await callback(info);
}
catch (Exception ex)
{
await _logger.WarnAsync($"处理歌曲下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。");
try
{
await callback(info);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
await _logger.WarnAsync("处理歌曲下载回调失败。", ex);
}
}
}
}, cancellationToken), cancellationToken));
await Task.WhenAll(downloadTasks);
cancellationToken.ThrowIfCancellationRequested();
var successfulCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: false });
var skippedCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: true });
var failedCount = needDownloadMusicInfos.Count(m => m.IsSuccessful == false);
await _logger.InfoAsync($"歌词数据下载完成,成功: {successfulCount} 跳过(纯音乐): {skippedCount} 失败{failedCount}。");
await LogFailedSongFilesInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.Now:yyyyMMddHHmmss}.txt"), needDownloadMusicInfos);
await LogFailedSongFilesInfoAsync(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.UtcNow:yyyyMMddHHmmss}.txt"),
needDownloadMusicInfos, cancellationToken);
}
private async Task<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info)
private async Task<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info,
CancellationToken cancellationToken = default)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
var lyrics = await provider.DownloadAsync(info.Name, info.Artist);
cancellationToken.ThrowIfCancellationRequested();
// 该来源没有搜到歌词,交给调用方去问下一家,不能在这里判定整首歌完成。
// 空结果只表示当前来源未找到歌词,继续尝试其他来源。
if (lyrics.IsPruneMusic)
{
return LyricsDownloadResult.Empty;
}
// 先把歌词编码成字节,再动磁盘。编码配置有误时(例如 fileEncoding 写成了不存在的名字)
// 这一步就会抛错,此时文件还没被创建,不会留下 0 字节的空壳。
// 编码成功后再创建文件,避免配置错误破坏原歌词。
var content = Utf8ToSelectedEncoding(lyrics);
var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc");
if (File.Exists(newLyricsFilePath))
var newLyricsFilePath = Path.ChangeExtension(info.FilePath, ".lrc");
var temporaryPath = $"{newLyricsFilePath}.{Guid.NewGuid():N}.tmp";
try
{
File.Delete(newLyricsFilePath);
await File.WriteAllBytesAsync(temporaryPath, content, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
File.Move(temporaryPath, newLyricsFilePath, overwrite: true);
}
// Write lyrics to file.
await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write))
finally
{
await fileStream.WriteAsync(content);
await fileStream.FlushAsync();
File.Delete(temporaryPath);
}
info.IsSuccessful = true;
info.IsPruneMusic = false;
return LyricsDownloadResult.Success;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (ErrorCodeException ex)
{
// 失败标记必须放在记录日志之前:LoggerHelper 即便将来再改动行为,
// 也不能让「失败」的歌曲以默认的 IsSuccessful = true 冒出去。
info.IsSuccessful = false;
info.IsPruneMusic = false;
_logger.LogWarningInfo(ex);
@@ -155,7 +168,7 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
{
info.IsSuccessful = false;
info.IsPruneMusic = false;
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
await _logger.WarnAsync("当前歌词来源下载失败,将尝试其他来源。", ex);
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());
}
private async Task LogFailedSongFilesInfo(string outFilePath, IEnumerable<MusicInfo> musicInfos)
private async Task LogFailedSongFilesInfoAsync(string outFilePath, IEnumerable<MusicInfo> musicInfos,
CancellationToken cancellationToken = default)
{
var failedSongList = musicInfos.Where(m => m.IsSuccessful == false).ToImmutableList();
if (!failedSongList.Any())
@@ -210,6 +224,6 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
failedSongFiles.AppendLine($"{failedSongFile.Name},{failedSongFile.Artist},{failedSongFile.FilePath}");
}
await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString());
await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString(), cancellationToken);
}
}
@@ -11,12 +11,16 @@ namespace ZonyLrcTools.Common.MusicDecryption
private readonly IWarpLogger _warpLogger;
private readonly IKugouKeyProvider? _kugouKeyProvider;
/// <summary>
/// 创建音乐解密器。
/// </summary>
public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null)
{
_warpLogger = warpLogger;
_kugouKeyProvider = kugouKeyProvider;
}
/// <inheritdoc />
public async Task<DecryptionResult> ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default)
{
try
@@ -36,12 +40,46 @@ namespace ZonyLrcTools.Common.MusicDecryption
using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { });
var outFileName = (await decrypto.DecryptAsync()).NewName;
cancellationToken.ThrowIfCancellationRequested();
var outFilePath = Path.Combine(Path.GetDirectoryName(filePath)!, outFileName);
if (!File.Exists(outFilePath))
if (File.Exists(outFilePath))
{
await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
await buffer.CopyToAsync(outFile, cancellationToken);
return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outFilePath}");
}
var tempPath = outFilePath + $".{Guid.NewGuid():N}.part";
var ownsTempFile = false;
try
{
await using (var outFile = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
ownsTempFile = true;
buffer.Position = 0;
await buffer.CopyToAsync(outFile, cancellationToken);
await outFile.FlushAsync(cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
File.Move(tempPath, outFilePath);
}
finally
{
if (ownsTempFile)
{
try
{
File.Delete(tempPath);
}
catch (IOException)
{
// 保留原始转换结果或异常。
}
catch (UnauthorizedAccessException)
{
// 保留原始转换结果或异常。
}
}
}
return DecryptionResult.Success(outFilePath);
@@ -46,7 +46,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
void Invalidate();
/// <summary>
/// 判断文件是否是 .kgg(按魔数,不看扩展名)。
/// 按魔数和加密版本判断文件是否为 KGG,不看扩展名。
/// </summary>
bool IsKggFile(string filePath);
@@ -15,7 +15,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary>
/// V2 前缀,解码后即 "QQMusic EncV2,Key:"。
/// </summary>
private static readonly byte[] V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6"u8.ToArray();
private const string V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6";
private static readonly byte[] V2Key1 =
[
@@ -35,11 +35,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary>
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
/// <param name="invalidCharCount">
/// Base64 段里被忽略的非法字符数量。Base64 解码本身是宽容的(会静默映射成 0),
/// 这里把它统计出来,让上层能把「密钥损坏」和「没有密钥」区分开。
/// </param>
/// </summary>
/// <param name="ekey">数据库中的密钥。</param>
/// <param name="invalidCharCount">Base64 中的非法字符数量,空白不计入。</param>
/// <returns>原始密钥;解码失败时为空数组。</returns>
public static byte[] Decode(string ekey, out int invalidCharCount)
{
@@ -49,10 +47,10 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return [];
}
var raw = Encoding.Latin1.GetBytes(ekey);
if (raw.Length >= V2Prefix.Length && raw.AsSpan(0, V2Prefix.Length).SequenceEqual(V2Prefix))
if (ekey.StartsWith(V2Prefix, StringComparison.Ordinal))
{
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)
{
return [];
@@ -72,7 +70,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
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)
{
return [];
@@ -98,107 +96,52 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return output;
}
private static readonly byte[] Base64Table =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u8.ToArray();
/// <summary>
/// 宽容的 Base64 解码,兼容 URL-safe 变体与不规范的长度。
/// <param name="invalidCount">输入中不属于 Base64 的字符数量(空白字符会被跳过,不计入)。</param>
/// </summary>
private static byte[] Base64Decode(byte[] input, out int invalidCount)
private static byte[] Base64Decode(string input, out int invalidCount)
{
var reverse = new byte[256];
var isKnown = new bool[256];
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;
var normalized = new char[input.Length + 3];
var length = 0;
invalidCount = 0;
var cleaned = new byte[input.Length];
var cleanedLength = 0;
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;
}
if (!isKnown[value])
if (value is not (>= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9'
or '+' or '/' or '-' or '_' or '='))
{
invalidCount++;
continue;
}
cleaned[cleanedLength++] = value;
}
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]];
var d = reverse[block[3]];
output[outOffset++] = (byte)((a << 2) | (b >> 4));
if (block[2] == '=')
normalized[length++] = value switch
{
return true;
}
output[outOffset++] = (byte)((b << 4) | (c >> 2));
if (block[3] == '=')
{
return true;
}
output[outOffset++] = (byte)((c << 6) | d);
return false;
'-' => '+',
'_' => '/',
_ => value
};
}
var fullLength = input.Length - input.Length % 4;
for (var i = 0; i < fullLength; i += 4)
if (invalidCount != 0 || length == 0 || length % 4 == 1)
{
if (DecodeBlock(input.AsSpan(i, 4)))
{
return output.AsSpan(0, outOffset).ToArray();
}
return [];
}
var remainder = input.Length % 4;
if (remainder != 0)
// 兼容省略末尾填充的密钥,由标准解码器校验填充位置。
while (length % 4 != 0)
{
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);
normalized[length++] = '=';
}
return output.AsSpan(0, outOffset).ToArray();
var padding = normalized[length - 1] == '=' ? 1 : 0;
if (normalized[length - 2] == '=')
{
padding++;
}
var output = new byte[length / 4 * 3 - padding];
return Convert.TryFromBase64Chars(normalized.AsSpan(0, length), output, out _) ? output : [];
}
}
}
@@ -29,16 +29,17 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private static byte[] Magic => KugouEkeyDatabase.KggMagic;
/// <summary>
/// 判断文件是否真的是 .kgg 格式(按魔数而非扩展名)。
/// 按魔数和加密版本判断是否为 KGG,避免误判共用魔数的旧版 KGM。
/// </summary>
public static bool IsKggFile(string filePath)
{
try
{
using var stream = File.OpenRead(filePath);
Span<byte> buffer = stackalloc byte[16];
return stream.ReadAtLeast(buffer, 16, throwOnEndOfStream: false) == 16
&& buffer.SequenceEqual(Magic);
Span<byte> buffer = stackalloc byte[0x18];
return stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false) == buffer.Length
&& buffer[..Magic.Length].SequenceEqual(Magic)
&& BinaryPrimitives.ReadUInt32LittleEndian(buffer[0x14..]) == ExpectedEncodingVersion;
}
catch
{
@@ -55,8 +56,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <returns>解密结果;失败时带有可读的错误说明。</returns>
public static async Task<DecryptionResult> ConvertAsync(string filePath,
IKugouKeyProvider? keyProvider,
CancellationToken cancellationToken)
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (!File.Exists(filePath))
{
return DecryptionResult.Failed($"文件不存在: {filePath}");
@@ -77,6 +79,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
}
var offsetToAudio = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10));
if (offsetToAudio < HeaderSize || offsetToAudio > input.Length - 4)
{
return DecryptionResult.Failed("kgg 音频偏移超出有效范围。");
}
var encodingVersion = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14));
if (encodingVersion != ExpectedEncodingVersion)
{
@@ -93,10 +100,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
if (!HasDatabase(keyProvider))
{
return DecryptionResult.Failed(KugouEkeyDatabase.BuildMissingDatabaseMessage());
return DecryptionResult.Failed(keyProvider?.Probe().Message ?? KugouEkeyDatabase.BuildMissingDatabaseMessage());
}
var ekey = ResolveEkey(keyProvider, audioHash);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(ekey))
{
return DecryptionResult.Failed(
@@ -129,6 +137,11 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
cipher.Decrypt(magic, 0);
var extension = DetectExtension(magic);
if (extension == null)
{
return DecryptionResult.Failed("解密后的音频格式无法识别,文件或密钥可能已损坏。");
}
input.Seek(offsetToAudio, SeekOrigin.Begin);
var outputPath = Path.Combine(
@@ -138,25 +151,30 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
// 期望的输出字节数,用于校验写盘是否完整。
var expectedLength = input.Length - offsetToAudio;
// 目标已存在且大小正确就不再覆盖,避免重复解密白费时间。
// 只要大小对不上(例如上次被中途取消留下的半截文件),就重新解密覆盖。
if (File.Exists(outputPath) && new FileInfo(outputPath).Length == expectedLength)
if (File.Exists(outputPath))
{
return DecryptionResult.Success(outputPath);
return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outputPath}");
}
// 先写临时文件,成功后再改名。中途取消或被强杀都不会污染正式输出文件名。
var tempPath = outputPath + ".part";
// 每次转换独占临时文件,仅在完整写入后发布,且不覆盖已有输出。
var tempPath = outputPath + $".{Guid.NewGuid():N}.part";
var ownsTempFile = false;
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))
{
ownsTempFile = true;
var buffer = new byte[BufferSize];
long offset = 0;
int read;
while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0)
var offset = 0L;
while (true)
{
var read = await input.ReadAsync(buffer, cancellationToken);
if (read == 0)
{
break;
}
cipher.Decrypt(buffer.AsSpan(0, read), offset);
await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken);
offset += read;
@@ -170,12 +188,15 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
}
}
File.Move(tempPath, outputPath, overwrite: true);
cancellationToken.ThrowIfCancellationRequested();
File.Move(tempPath, outputPath);
}
catch
finally
{
TryDelete(tempPath);
throw;
if (ownsTempFile)
{
TryDelete(tempPath);
}
}
return DecryptionResult.Success(outputPath);
@@ -192,13 +213,13 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
}
catch
{
// 清理失败不影响主流程,下次解密会覆盖这个临时文件。
// 保留原始转换结果或异常。
}
}
private static bool HasDatabase(IKugouKeyProvider? keyProvider)
{
return keyProvider?.DatabasePath != null || KugouEkeyDatabase.FindDatabasePath() != null;
return keyProvider != null ? keyProvider.DatabasePath != null : KugouEkeyDatabase.FindDatabasePath() != null;
}
/// <summary>
@@ -221,7 +242,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
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))
{
@@ -233,7 +254,10 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
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.
using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Data.Sqlite;
@@ -13,7 +14,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// <summary>
/// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。
/// <remarks>
/// 数据库按 4KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥 + 页号派生。
/// 数据库按 1KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥和页号派生。
/// 解密后可以读到 <c>ShareFileItems</c> 表里的 ekey,那是 .kgg 文件真正用的解密密钥。
/// </remarks>
/// </summary>
@@ -106,20 +107,18 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return result;
}
// 解密后的内容写到临时文件,交给 SQLite 自己解析,避免手写记录格式。
// 这里放的是明文密钥库,所以用一个专用目录并在每次进入时清理上次留下的残留:
// 进程被强杀时 finally 不会执行,但下一次读取会把上一轮的明文文件删掉。
var tempDirectory = Path.Combine(Path.GetTempPath(), TemporaryDirectoryName);
var tempPath = Path.Combine(tempDirectory, $"{Guid.NewGuid():N}.db");
// 直接从内存解析,避免明文密钥落盘和并发清理临时文件的竞争。
var pinned = GCHandle.Alloc(plain, GCHandleType.Pinned);
try
{
Directory.CreateDirectory(tempDirectory);
SweepStaleTempFiles(tempDirectory);
WriteFileWithFlush(tempPath, plain);
using var connection = new SqliteConnection($"Data Source={tempPath};Mode=ReadOnly");
using var connection = new SqliteConnection("Data Source=:memory:;Pooling=False");
connection.Open();
var error = SQLitePCL.raw.sqlite3_deserialize(connection.Handle, "main",
pinned.AddrOfPinnedObject(), plain.Length, plain.Length, SQLitePCL.raw.SQLITE_DESERIALIZE_READONLY);
if (error != SQLitePCL.raw.SQLITE_OK)
{
throw new SqliteException("无法读取解密后的酷狗数据库。", error);
}
using var command = connection.CreateCommand();
command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''";
@@ -146,54 +145,12 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
}
finally
{
TryDeleteFile(tempPath);
pinned.Free();
}
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>
/// 把整个加密数据库解密成明文的 SQLite 字节流。
/// </summary>
@@ -201,12 +158,13 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read);
var length = (int)source.Length;
if (length == 0 || length % PageSize != 0)
var sourceLength = source.Length;
if (sourceLength == 0 || sourceLength > Array.MaxLength || sourceLength % PageSize != 0)
{
return [];
}
var length = (int)sourceLength;
var pageCount = length / PageSize;
var plain = new byte[length];
var headerBuffer = new byte[8];
@@ -3,8 +3,6 @@
// Copyright (c) 2024 LSR
// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root.
using System.Buffers.Binary;
namespace ZonyLrcTools.Common.MusicDecryption.Kugou
{
/// <summary>
@@ -70,6 +68,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private readonly byte[] _key;
/// <summary>
/// 根据短密钥生成查找表。
/// </summary>
public Qmc2MapCipher(byte[] key)
{
_key = new byte[MapKeySize];
@@ -79,16 +80,18 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
var j = (int)(((long)i * i + MapIndexOffset) % length);
var shift = (j + 4) % 8;
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)
{
var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary;
return (byte)(cipher ^ _key[index % MapKeySize]);
}
/// <inheritdoc />
public override void Decrypt(Span<byte> data, long offset)
{
for (var i = 0; i < data.Length; i++)
@@ -119,6 +122,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private readonly byte[] _keyStream = new byte[KeyStreamSize];
private readonly uint _keyHash;
/// <summary>
/// 根据长密钥生成密钥流。
/// </summary>
public Qmc2Rc4Cipher(byte[] key)
{
_key = key;
@@ -126,6 +132,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
DeriveKeyStream();
}
/// <inheritdoc />
public override byte Decrypt(byte cipher, long offset)
{
if (offset < FirstSegmentSize)
@@ -142,6 +149,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]);
}
/// <inheritdoc />
public override void Decrypt(Span<byte> data, long offset)
{
// 首段与常规段的算法不同,先按边界切一刀。
@@ -182,7 +190,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
/// </summary>
private static uint ComputeKeyHash(ReadOnlySpan<byte> key)
{
uint hash = 1;
var hash = 1u;
foreach (var item in key)
{
if (item == 0)
@@ -68,8 +68,8 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return [];
}
ulong iv1 = 0;
ulong iv2 = 0;
var iv1 = 0UL;
var iv2 = 0UL;
var inOffset = 0;
var header = new byte[HeaderSize];
@@ -16,10 +16,10 @@ namespace ZonyLrcTools.Common.MusicDecryption
private string? _manualPath;
private string? _databasePath;
private string? _loadedPath;
private string? _failureReason;
private bool _isLoaded;
/// <inheritdoc />
public string? DatabasePath
{
get
@@ -32,12 +32,14 @@ namespace ZonyLrcTools.Common.MusicDecryption
}
}
/// <inheritdoc />
public void SetDatabasePath(string? path)
{
lock (_syncRoot)
{
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 数据库。
return;
@@ -65,7 +67,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
{
var message = _manualPath != null
? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}"
: Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage();
: _failureReason ?? Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage();
return new KugouDatabaseInfo(false, null, 0, message);
}
@@ -88,13 +90,14 @@ namespace ZonyLrcTools.Common.MusicDecryption
_isLoaded = false;
_keys.Clear();
_databasePath = null;
_loadedPath = 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)
{
try
@@ -111,8 +114,15 @@ namespace ZonyLrcTools.Common.MusicDecryption
return null;
}
var audioOffset = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10));
if (BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14)) != 5
|| audioOffset < HeaderSize || audioOffset > stream.Length - 4)
{
return null;
}
var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44));
if (hashLength == 0 || hashLength > AudioHashLength)
if (hashLength != AudioHashLength)
{
return null;
}
@@ -125,6 +135,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
}
}
/// <inheritdoc />
public string? FindKey(string audioHash)
{
if (string.IsNullOrEmpty(audioHash))
@@ -149,7 +160,6 @@ namespace ZonyLrcTools.Common.MusicDecryption
_isLoaded = true;
_keys.Clear();
_databasePath = null;
_loadedPath = null;
_failureReason = null;
var path = _manualPath;
@@ -172,15 +182,10 @@ namespace ZonyLrcTools.Common.MusicDecryption
{
_failureReason = failureReason ?? "没有读到任何密钥";
// 手动指定的文件读不出密钥,就不要把它当成可用数据库。
if (_manualPath != null)
{
return;
}
return;
}
_databasePath = path;
_loadedPath = path;
foreach (var pair in keys)
{
_keys[pair.Key] = pair.Value;
@@ -15,19 +15,19 @@ public class CsvFileMusicScanner : ITransientDependency
/// <param name="csvFilePath">CSV 文件的路径。</param>
/// <param name="outputDirectory">歌词文件的输出目录。</param>
/// <param name="pattern">输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。</param>
/// <param name="cancellationToken">取消令牌。</param>
public async Task<List<MusicInfo>> GetMusicInfoFromCsvFileAsync(string csvFilePath, string outputDirectory,
string pattern)
string pattern, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var encoding = DetectFileEncoding(csvFilePath);
var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding);
var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding, cancellationToken);
// 不能只按 Environment.NewLine 切分:在 Windows 上读到的是 "\r\n",而用户从网盘、
// 版本的表格导出、Git 里签出的 CSV 往往是 "\n",那样整个文件会被当成一行,
// 跳过表头之后就是空的,界面上表现为"解析了但一首歌都没有"。
// 兼容不同操作系统导出的换行符。
var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
return csvFileLines.Skip(1)
.Where(line => line.Contains(',')) // 跳过空行与 VCS 合并产生的杂行。
.Where(line => line.Contains(','))
.Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern))
.ToList();
}
@@ -20,16 +20,55 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
private readonly IWarpHttpClient _warpHttpClient;
private readonly ILogger<NetEaseMusicSongListMusicScanner> _logger;
private const string Host = "https://music.163.com";
private readonly SemaphoreSlim _loginSemaphore = new(1, 1);
private readonly object _loginStateLock = new();
private string _cookie = string.Empty;
private string _csrfToken = string.Empty;
private long _loginStateVersion;
/// <summary>
/// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。
/// </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>
/// 登录后的 CSRF Token,通常与 <see cref="Cookie"/> 一起持久化。
/// </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>
/// 当前是否已经持有登录态。
@@ -51,8 +90,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </summary>
public void ClearLoginState()
{
Cookie = string.Empty;
CsrfToken = string.Empty;
RestoreLoginState(string.Empty, string.Empty);
}
/// <summary>
@@ -62,8 +100,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// <param name="csrfToken">与 <paramref name="cookie"/> 一起保存的 CSRF Token。</param>
public void RestoreLoginState(string cookie, string csrfToken)
{
Cookie = cookie ?? string.Empty;
CsrfToken = csrfToken ?? string.Empty;
lock (_loginStateLock)
{
_cookie = cookie ?? string.Empty;
_csrfToken = csrfToken ?? string.Empty;
_loginStateVersion++;
}
}
/// <summary>
@@ -78,17 +120,44 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action<NetEaseLoginState>? onStateChanged = null,
CancellationToken cancellationToken = default)
{
if (IsLoggedIn)
await _loginSemaphore.WaitAsync(cancellationToken);
try
{
var session = GetLoginState();
if (!string.IsNullOrEmpty(session.Cookie))
{
onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
return true;
}
var loginResponse = await LoginViaQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
var cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
lock (_loginStateLock)
{
// 退出或恢复会话后,不能再提交旧二维码的登录结果。
if (session.Version != _loginStateVersion)
{
return false;
}
_cookie = cookie;
_csrfToken = loginResponse.csrfToken ?? string.Empty;
_loginStateVersion++;
}
if (string.IsNullOrEmpty(cookie))
{
return false;
}
onStateChanged?.Invoke(NetEaseLoginState.Succeeded);
return true;
}
var loginResponse = await LoginViqQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken);
Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty;
CsrfToken = loginResponse.csrfToken ?? string.Empty;
return IsLoggedIn;
finally
{
_loginSemaphore.Release();
}
}
/// <summary>
@@ -111,33 +180,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action<NetEaseLoginState>? onStateChanged = null,
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();
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
var response = await _warpHttpClient.PostAsync<GetMusicInfoFromNetEaseMusicSongListResponse>(
$"{Host}/weapi/v6/playlist/detail?csrf_token={CsrfToken}", requestOption:
$"{Host}/weapi/v6/playlist/detail?csrf_token={session.CsrfToken}", requestOption:
request =>
{
request.Headers.Add("Cookie", Cookie);
request.Headers.Add("Cookie", session.Cookie);
request.Content = new FormUrlEncodedContent(HandleRequest(new
{
csrf_token = CsrfToken,
csrf_token = session.CsrfToken,
id = songId,
n = 1000,
offset = 0,
@@ -145,7 +208,8 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
limit = 1000,
}, secretKey, encSecKey));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
});
}, cancellationToken: cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
if (response.Code != 200 || response.PlayList?.SongList == null)
{
@@ -164,18 +228,25 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
}
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();
_logger.LogInformation("正在获取歌单 {SongListId} 的歌曲列表。", songListId);
var musicInfos = await GetMusicInfoBySongIdAsync(songListId);
var musicInfos = await GetMusicInfoBySongIdAsync(songListId, cancellationToken);
musicInfoList.AddRange(musicInfos);
}
return musicInfoList;
}
private (string Cookie, string CsrfToken, long Version) GetLoginState()
{
lock (_loginStateLock)
{
return (_cookie, _csrfToken, _loginStateVersion);
}
}
/// <summary>
/// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。
/// </summary>
@@ -204,24 +275,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </param>
/// <param name="onStateChanged">登录状态变化回调。</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<NetEaseLoginState>? onStateChanged,
CancellationToken cancellationToken)
CancellationToken cancellationToken = default)
{
// Get unikey.
var qrCodeKeyJson = await (await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
using var keyResponse = await PostAsync($"{Host}/weapi/login/qrcode/unikey", new
{
type = 1
})).Content.ReadAsStringAsync(cancellationToken);
var uniKey = JObject.Parse(qrCodeKeyJson).SelectToken("$.unikey")!.Value<string>();
if (string.IsNullOrEmpty(uniKey)) return (null, null);
}, cancellationToken: cancellationToken);
var keyResponseJson = JObject.Parse(await keyResponse.Content.ReadAsStringAsync(cancellationToken));
var uniKey = keyResponseJson.Value<string>("unikey");
if (keyResponseJson.Value<int?>("code") != 200 || string.IsNullOrEmpty(uniKey))
{
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
// Generate QR code.
var qrGenerator = new QRCodeGenerator();
using var qrGenerator = new QRCodeGenerator();
var qrContent = $"{Host}/login?codekey={uniKey}";
var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L);
var asciiQrCodeString = new AsciiQRCode(qrCodeData).GetGraphic(1, drawQuietZones: false);
using var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L);
using var qrCode = new AsciiQRCode(qrCodeData);
var asciiQrCodeString = qrCode.GetGraphic(1, drawQuietZones: false);
if (onQrCodeReady != null)
{
@@ -233,7 +307,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
_logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString);
}
// Wait for login success.
onStateChanged?.Invoke(NetEaseLoginState.Waiting);
var lastState = NetEaseLoginState.Waiting;
while (true)
{
@@ -241,7 +315,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken);
if (state != lastState)
if (state != lastState && state != NetEaseLoginState.Succeeded)
{
lastState = state;
onStateChanged?.Invoke(state);
@@ -264,13 +338,13 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
private async Task<(NetEaseLoginState state, CookieContainer? cookieContainer)> CheckIsLoginAsync(
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,
type = 1
});
}, cancellationToken: cancellationToken);
var responseString = await responseMessage.Content.ReadAsStringAsync(cancellationToken);
var responseCode = JObject.Parse(responseString)["code"]?.Value<int>();
@@ -280,17 +354,19 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
// 800 二维码过期、801 等待扫码、802 已扫码待确认、803 登录成功。
case 800:
return (NetEaseLoginState.Expired, null);
case 801:
return (NetEaseLoginState.Waiting, null);
case 802:
return (NetEaseLoginState.ScanConfirmed, null);
case 803:
break;
default:
return (NetEaseLoginState.Waiting, null);
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies))
{
return (NetEaseLoginState.Waiting, null);
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
var cookieContainer = new CookieContainer();
@@ -299,6 +375,11 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
cookieContainer.SetCookies(new Uri(Host), cookie);
}
if (cookieContainer.GetCookies(new Uri(Host)).Count == 0)
{
throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic);
}
return (NetEaseLoginState.Succeeded, cookieContainer);
}
@@ -307,19 +388,34 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// </summary>
/// <param name="url">需要请求的网易云音乐 API 地址。</param>
/// <param name="params">API 请求参数。</param>
/// <param name="cancellationToken">取消令牌。</param>
/// <returns>
/// 正常情况下会返回一个 <see cref="HttpResponseMessage"/> 对象。
/// </returns>
private async Task<HttpResponseMessage> PostAsync(string url, object @params)
private async Task<HttpResponseMessage> PostAsync(string url, object @params,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
return await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption:
var response = await _warpHttpClient.PostReturnHttpResponseAsync(url, requestOption:
request =>
{
request.Content = new FormUrlEncodedContent(HandleRequest(@params, secretKey, encSecKey));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
});
}, cancellationToken: cancellationToken);
try
{
response.EnsureSuccessStatusCode();
cancellationToken.ThrowIfCancellationRequested();
return response;
}
catch
{
response.Dispose();
throw;
}
}
}
@@ -27,4 +27,16 @@
<Compile Remove="Lyrics\Providers\Kugeci\KugeciDownloader.cs"/>
</ItemGroup>
<ItemGroup>
<Content Include="..\..\THIRD-PARTY-NOTICES.md" Link="THIRD-PARTY-NOTICES.md">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</Content>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="ZonyLrcTools.Tests"/>
</ItemGroup>
</Project>
+2 -6
View File
@@ -7,11 +7,7 @@
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml"/>
<!--
按钮排版统一:Fluent 默认的 14px/偏大内边距在中文界面里显得松散,而且
带图标的按钮和纯文字按钮高度对不齐。这里把字号、内边距、圆角、最小高度
统一成一套,让所有页面的按钮共用同一套度量。
-->
<!-- 统一按钮尺寸与文字对齐方式。 -->
<Style Selector="Button">
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="16,6" />
@@ -33,7 +29,7 @@
<Setter Property="Height" Value="14" />
</Style>
<!-- Compact icon-only button used by the reorder arrows in the settings list -->
<!-- 设置列表中的紧凑图标按钮。 -->
<Style Selector="Button.icon">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
@@ -1,58 +1,24 @@
<?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>
<!--
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" />
<!--
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" />
<!--
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.
-->
<!-- Avalonia 的无障碍节点通过运行时查找创建。 -->
<assembly fullname="Avalonia.Controls" preserve="all" />
<assembly fullname="Avalonia.Controls.DataGrid" preserve="all" />
<!--
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.
-->
<!-- Windows 无障碍提供程序还会通过 COM 激活。 -->
<assembly fullname="Avalonia.Win32" preserve="all" />
<assembly fullname="Avalonia.Base" preserve="all" />
<!--
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.
-->
<!-- 保留配置映射、音频元数据、解密及 SQLite 运行时加载所需类型。 -->
<assembly fullname="YamlDotNet" preserve="all" />
<assembly fullname="Newtonsoft.Json" 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="QRCoder" preserve="all" />
<assembly fullname="SQLitePCLRaw.core" preserve="all" />
@@ -1,14 +1,7 @@
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary>
/// Resolves the directories the desktop application reads and writes at runtime.
/// </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>
/// <summary>解析桌面应用的配置目录。</summary>
/// <remarks>优先使用便携目录;不可写时回退到当前用户的应用数据目录。</remarks>
public static class AppPaths
{
private const string ApplicationFolderName = "ZonyLrcTools";
@@ -16,20 +9,13 @@ public static class AppPaths
private static readonly Lazy<string> LazyConfigDirectory = new(ResolveConfigDirectory);
/// <summary>
/// Directory that holds <c>config.yaml</c>.
/// </summary>
/// <summary>配置文件所在目录。</summary>
public static string ConfigDirectory => LazyConfigDirectory.Value;
/// <summary>
/// Full path of the writable <c>config.yaml</c>.
/// </summary>
/// <summary>配置文件的完整路径。</summary>
public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName);
/// <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>
/// <summary>首次启动时将随程序附带的配置复制到用户目录。</summary>
public static void EnsureConfigFile()
{
if (File.Exists(ConfigFilePath))
@@ -46,7 +32,7 @@ public static class AppPaths
if (string.Equals(
Path.GetFullPath(template),
Path.GetFullPath(ConfigFilePath),
StringComparison.OrdinalIgnoreCase))
OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{
return;
}
@@ -57,7 +43,7 @@ public static class AppPaths
}
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)
{
// Fall through to the portable path; reading still works even when writing does not.
// 没有可写目录时仍允许读取便携目录的配置。
}
return baseDirectory;
@@ -5,13 +5,10 @@ using ZonyLrcTools.Common.Infrastructure.DependencyInject;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary>桌面配置服务注册。</summary>
public static class ConfigurationServiceCollectionExtensions
{
/// <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>
/// <summary>从可写配置目录加载配置并注册设置存储。</summary>
public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services)
{
AppPaths.EnsureConfigFile();
@@ -2,38 +2,28 @@ using ZonyLrcTools.Common.Configuration;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary>
/// Result of a settings persist operation.
/// </summary>
/// <param name="IsSuccess">Whether the settings were written to disk.</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>
/// <summary>设置保存结果。</summary>
/// <param name="IsSuccess">是否保存成功。</param>
/// <param name="FilePath">保存成功的文件路径。</param>
/// <param name="ErrorMessage">保存失败的原因。</param>
public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage)
{
/// <summary>创建保存成功的结果。</summary>
public static SettingsSaveResult Success(string filePath) => new(true, filePath, null);
/// <summary>创建保存失败的结果。</summary>
public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage);
}
/// <summary>
/// Single owner of the settings file: reads the bound <see cref="GlobalOptions"/> and writes it back
/// to <see cref="AppPaths.ConfigFilePath"/>.
/// </summary>
/// <summary>统一管理共享配置及其持久化。</summary>
public interface ISettingsStore
{
/// <summary>
/// The live options instance shared by the whole application. Mutating it takes effect
/// immediately for components that read it per operation.
/// </summary>
/// <summary>应用共享配置,修改后对按操作读取配置的组件立即生效。</summary>
GlobalOptions Options { get; }
/// <summary>
/// Absolute path of the settings file currently in use.
/// </summary>
/// <summary>当前配置文件的完整路径。</summary>
string ConfigFilePath { get; }
/// <summary>
/// Serialize <see cref="Options"/> to YAML and replace the settings file atomically.
/// </summary>
/// <summary>保存界面管理的配置值,不覆盖无法安全修改的文件。</summary>
Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default);
}
@@ -2,33 +2,17 @@ using System.Text.Json;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <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>
/// <summary>保存本机手动选择的酷狗数据库路径。</summary>
public sealed class KugouDatabaseStore
{
private const string FileName = "kugou.database.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary>
/// Full path of the settings file.
/// </summary>
/// <summary>本机状态文件的完整路径。</summary>
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
/// <summary>
/// Load the stored database path, or <c>null</c> when there is none / it cannot be read.
/// </summary>
/// <summary>读取数据库路径;文件缺失或损坏时返回空。</summary>
public async Task<string?> LoadAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
@@ -40,13 +24,13 @@ public sealed class KugouDatabaseStore
}
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;
}
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;
}
finally
@@ -55,24 +39,19 @@ public sealed class KugouDatabaseStore
}
}
/// <summary>
/// Persist the chosen database path.
/// </summary>
/// <summary>保存数据库路径。</summary>
public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
try
{
Directory.CreateDirectory(AppPaths.ConfigDirectory);
var setting = new KugouDatabaseSetting { DatabasePath = databasePath };
var temporaryPath = FilePath + ".tmp";
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(setting, JsonOptions), cancellationToken);
File.Move(temporaryPath, FilePath, overwrite: true);
await DesktopStateFile.WriteAsync(FilePath, setting,
DesktopStateJsonContext.Default.KugouDatabaseSetting, ownerOnly: false, cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Losing this only costs the user one extra pick next launch.
// 缓存写入失败不影响本次使用。
}
finally
{
@@ -80,9 +59,7 @@ public sealed class KugouDatabaseStore
}
}
/// <summary>
/// Forget the stored path so auto detection takes over again.
/// </summary>
/// <summary>忘记手动路径,恢复自动查找。</summary>
public async Task ClearAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
@@ -95,7 +72,7 @@ public sealed class KugouDatabaseStore
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing actionable.
// 调用方仍可使用本次自动查找结果。
}
finally
{
@@ -104,10 +81,9 @@ public sealed class KugouDatabaseStore
}
}
/// <summary>
/// The persisted shape of <see cref="KugouDatabaseStore"/>.
/// </summary>
/// <summary>酷狗数据库路径的持久化格式。</summary>
public sealed class KugouDatabaseSetting
{
/// <summary>数据库的完整路径。</summary>
public string DatabasePath { get; set; } = string.Empty;
}
@@ -1,40 +1,24 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <summary>
/// Persists the NetEase Cloud Music login state (cookie + csrf token) so the QR login dialog
/// 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>
/// <summary>持久化网易云登录会话。</summary>
/// <remarks>会话属于登录凭据;Unix 文件仅限当前用户读写,Windows 继承目录权限。</remarks>
public sealed class NetEaseSessionStore
{
private const string FileName = "netease.session.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true
};
private readonly SemaphoreSlim _lock = new(1, 1);
/// <summary>
/// Full path of the session file.
/// </summary>
/// <summary>会话文件的完整路径。</summary>
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
/// <summary>
/// Whether a stored session exists on disk.
/// </summary>
/// <summary>是否存在已保存的会话。</summary>
public bool HasStoredSession => File.Exists(FilePath);
/// <summary>
/// Load the stored session, or <c>null</c> when there is none / it cannot be read.
/// </summary>
/// <summary>读取会话;文件缺失或损坏时返回空。</summary>
public async Task<NetEaseSession?> LoadAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
@@ -44,15 +28,19 @@ public sealed class NetEaseSessionStore
{
return null;
}
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(FilePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
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;
}
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;
}
finally
@@ -61,23 +49,18 @@ public sealed class NetEaseSessionStore
}
}
/// <summary>
/// Write the session to disk.
/// </summary>
/// <summary>保存会话。</summary>
public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
try
{
Directory.CreateDirectory(AppPaths.ConfigDirectory);
var temporaryPath = FilePath + ".tmp";
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(session, JsonOptions), cancellationToken);
File.Move(temporaryPath, FilePath, overwrite: true);
await DesktopStateFile.WriteAsync(FilePath, session,
DesktopStateJsonContext.Default.NetEaseSession, ownerOnly: true, cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Losing the cache only costs the user one extra scan next launch.
// 缓存写入失败不影响本次会话。
}
finally
{
@@ -85,22 +68,14 @@ public sealed class NetEaseSessionStore
}
}
/// <summary>
/// Delete the stored session.
/// </summary>
/// <summary>删除已保存的会话。</summary>
public async Task ClearAsync(CancellationToken cancellationToken = default)
{
await _lock.WaitAsync(cancellationToken);
try
{
if (File.Exists(FilePath))
{
File.Delete(FilePath);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Nothing actionable; the in-memory state is cleared regardless.
cancellationToken.ThrowIfCancellationRequested();
File.Delete(FilePath);
}
finally
{
@@ -109,14 +84,58 @@ public sealed class NetEaseSessionStore
}
}
/// <summary>
/// The bits of a NetEase login that are worth keeping between runs.
/// </summary>
/// <summary>网易云登录凭据。</summary>
public sealed class NetEaseSession
{
/// <summary>登录 Cookie。</summary>
public string Cookie { get; set; } = string.Empty;
/// <summary>请求校验令牌。</summary>
public string CsrfToken { get; set; } = string.Empty;
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;
/// <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>
/// <summary>将含控制字符的文本输出为单行双引号标量。</summary>
public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
{
/// <summary>创建标量输出器。</summary>
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] == ' ');
}
}
@@ -1,6 +1,9 @@
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Options;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using ZonyLrcTools.Common.Configuration;
@@ -8,29 +11,17 @@ using ZonyLrcTools.Common.Configuration;
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
/// <inheritdoc cref="ISettingsStore" />
/// <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>
/// <remarks>只修改界面管理的值,保留其他配置和注释;无法安全修改时返回错误。</remarks>
public sealed class SettingsStore : ISettingsStore, IDisposable
{
private const string RegeneratedHeaderText =
"# 此文件由 ZonyLrcTools X 重新生成:原有的注释已丢失,你可以参照文档重新补充。";
private const string RegeneratedHeaderText = "# ZonyLrcTools X 配置文件";
private readonly ISerializer _serializer;
private readonly IDeserializer _deserializer;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private bool _disposed;
/// <summary>使用应用共享配置创建设置存储。</summary>
public SettingsStore(IOptions<GlobalOptions> options)
{
Options = options.Value;
@@ -38,7 +29,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
_serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
// Keep "\n" readable instead of letting YamlDotNet emit the folded block scalar ">2".
// 换行符保持双引号转义形式,便于手工编辑。
.WithEventEmitter(next => new QuotedScalarEventEmitter(next))
.Build();
@@ -73,12 +64,19 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
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 + ".tmp";
await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
.ConfigureAwait(false);
File.Move(tempPath, targetPath, overwrite: true);
// 使用独立临时文件,避免多个进程互相截断写入。
var tempPath = targetPath + $".{Guid.NewGuid():N}.tmp";
try
{
await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
File.Move(tempPath, targetPath, overwrite: true);
}
finally
{
File.Delete(tempPath);
}
return SettingsSaveResult.Success(targetPath);
}
@@ -96,20 +94,11 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
}
}
/// <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>
/// <summary>按 YAML 节点位置修改配置;仅文件不存在时允许重新生成。</summary>
private async Task<string?> TryPatchInPlaceAsync(
string path,
IReadOnlyDictionary<string, string> managed,
CancellationToken cancellationToken)
CancellationToken cancellationToken = default)
{
if (!File.Exists(path))
{
@@ -117,20 +106,18 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
}
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 VerifyRoundTrip(patched, managed) ? patched : null;
return patched;
}
private string BuildFromScratch()
{
// Materialize the same managed values the patch path would have written, so the two
// paths cannot disagree about what "saved" means.
// YamlDotNet 输出统一是 "\n",这里显式拼同一套行尾,避免首行注释与正文混用 CRLF/LF。
// 新文件使用统一的 LF 行尾。
var body = _serializer.Serialize(Options);
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)
{
if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal))
@@ -217,7 +204,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
"networkOptions.ip" => options.NetworkOptions?.Ip,
"networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture),
"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.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation),
"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.HasValue ? Normalize(value.Value) : null;
@@ -242,188 +229,142 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
_ => raw
};
/// <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>
/// <summary>用解析器的位置替换标量,保留流式映射、注释和未管理的字段。</summary>
private static string PatchText(string original, IReadOnlyDictionary<string, string> managed)
{
var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
var lines = original.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
var stack = new List<(int Indent, string Path)>();
var replaced = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < lines.Length; i++)
var stream = new YamlStream();
stream.Load(new StringReader(original));
if (stream.Documents.Count != 1 || stream.Documents[0].RootNode is not YamlMappingNode root)
{
var raw = lines[i];
var trimmed = raw.TrimStart();
if (trimmed.Length == 0 || trimmed.StartsWith('#'))
{
continue;
}
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 parent = stack.Count > 0 ? stack[^1].Path : string.Empty;
// 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;
throw new InvalidDataException("配置必须是单个 YAML 映射文档。");
}
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 (s.Length == 0)
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)
{
return string.Empty;
}
if (s[0] is '"' or '\'')
{
var quote = s[0];
for (var i = 1; i < s.Length; i++)
var parts = path.Split('.');
var current = (YamlNode)root;
for (var i = 0; i < parts.Length; i++)
{
if (s[i] == '\\' && quote == '"')
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)
{
i++;
continue;
}
if (s[i] == quote)
if (child is not YamlScalarNode existing || !child.Anchor.IsEmpty)
{
return s[..(i + 1)];
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)));
}
return s;
}
var end = 0;
while (end < s.Length && !char.IsWhiteSpace(s[end]))
var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
foreach (var (mapping, fields) in additions)
{
end++;
if (mapping.Style == MappingStyle.Flow)
{
// 在首个键之前插入;空映射则插入到左花括号之后。
var position = mapping.Children.Count > 0
? (int)mapping.Children.First().Key.Start.Index
: (int)mapping.End.Index + 1;
var text = string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}"));
edits.Add((position, position, text + (mapping.Children.Count > 0 ? ", " : string.Empty)));
}
else
{
var first = mapping.Children.First().Key;
var indent = new string(' ', (int)first.Start.Column - 1);
var text = string.Join(newline + indent,
fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}"));
edits.Add(((int)first.Start.Index, (int)first.Start.Index, text + newline + indent));
}
}
return s[..end];
var builder = new StringBuilder(original);
var nextStart = original.Length;
foreach (var edit in edits.OrderByDescending(edit => edit.Start))
{
if (edit.End > nextStart)
{
throw new InvalidDataException("配置包含重叠的 YAML 别名,无法安全修改。");
}
builder.Remove(edit.Start, edit.End - edit.Start).Insert(edit.Start, edit.Text);
nextStart = edit.Start;
}
return builder.ToString();
}
/// <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();
private static string FormatValue(object value) => value is Dictionary<string, object> fields
? "{ " + string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")) + " }"
: QuoteScalar((string)value);
if (!mustQuote)
{
if (previous.StartsWith('\'') && !value.Contains('\''))
{
return $"'{value}'";
}
private static string QuoteScalar(string value) => "\"" + value
.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal)
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal)
.Replace("\t", "\\t", StringComparison.Ordinal)
.Replace("\0", "\\0", StringComparison.Ordinal) + "\"";
if (previous.StartsWith('"'))
{
return $"\"{value}\"";
}
return value;
}
var escaped = value
.Replace("\\", "\\\\", StringComparison.Ordinal)
.Replace("\"", "\\\"", StringComparison.Ordinal)
.Replace("\r", "\\r", StringComparison.Ordinal)
.Replace("\n", "\\n", StringComparison.Ordinal)
.Replace("\t", "\\t", StringComparison.Ordinal);
return $"\"{escaped}\"";
}
/// <summary>Flattens the editable subset of <see cref="GlobalOptions"/> into path → scalar text.</summary>
/// <summary>收集设置界面管理的配置路径和值。</summary>
private static Dictionary<string, string> BuildManagedScalars(GlobalOptions options)
{
var managed = new Dictionary<string, string>(StringComparer.Ordinal);
@@ -484,10 +425,7 @@ public sealed class SettingsStore : ISettingsStore, IDisposable
return managed;
}
/// <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>
/// <summary>释放写入锁。</summary>
public void Dispose()
{
if (_disposed)
@@ -338,7 +338,7 @@
<value>Enable block word filtering</value>
</data>
<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 name="Settings_TagProvider" xml:space="preserve">
<value>Tag Providers</value>
@@ -436,6 +436,12 @@
<data name="NetEase_LoginSucceeded" xml:space="preserve">
<value>Signed in.</value>
</data>
<data name="NetEase_LoginExpired" xml:space="preserve">
<value>The QR code expired. Close this dialog and try again.</value>
</data>
<data name="NetEase_LoginFailed" xml:space="preserve">
<value>Login did not complete. Close this dialog and try again.</value>
</data>
<data name="Home_Features" xml:space="preserve">
<value>Features</value>
</data>
@@ -338,7 +338,7 @@
<value>启用屏蔽词过滤</value>
</data>
<data name="Settings_BlockWordPath" xml:space="preserve">
<value>屏蔽词文件路径:</value>
<value>屏蔽词文件路径(相对当前工作目录):</value>
</data>
<data name="Settings_TagProvider" xml:space="preserve">
<value>标签源</value>
@@ -436,6 +436,12 @@
<data name="NetEase_LoginSucceeded" xml:space="preserve">
<value>登录成功。</value>
</data>
<data name="NetEase_LoginExpired" xml:space="preserve">
<value>二维码已过期,请关闭窗口后重新登录。</value>
</data>
<data name="NetEase_LoginFailed" xml:space="preserve">
<value>登录未完成,请关闭窗口后重试。</value>
</data>
<data name="Home_Features" xml:space="preserve">
<value>功能特性</value>
</data>
@@ -2,6 +2,7 @@ using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using ZonyLrcTools.Desktop.ViewModels;
using ZonyLrcTools.Desktop.Views.Dialogs;
@@ -24,17 +25,29 @@ public class DialogService : IDialogService
AllowMultiple = false
});
return folders.FirstOrDefault()?.Path.LocalPath;
return folders.FirstOrDefault()?.TryGetLocalPath();
}
public async Task<string?> ShowFilePickerAsync(string title, string[]? filters = null)
{
var files = await ShowFilesPickerAsync(title, filters);
return files.FirstOrDefault();
if (MainWindow == null) return null;
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>();
var fileTypes = BuildFileTypes(filters);
@@ -46,15 +59,17 @@ public class DialogService : IDialogService
AllowMultiple = true,
FileTypeFilter = fileTypes
});
cancellationToken.ThrowIfCancellationRequested();
return files
.Select(f => f.Path.LocalPath)
.Select(f => f.TryGetLocalPath())
.OfType<string>()
.Where(p => !string.IsNullOrEmpty(p))
.ToList();
}
/// <summary>
/// Turn a list of bare extensions (".mp3", "mp3", "*.mp3") into Avalonia file type filters.
/// 将文件扩展名转换为文件选择器筛选条件。
/// </summary>
private static List<FilePickerFileType>? BuildFileTypes(string[]? filters)
{
@@ -100,15 +115,19 @@ public class DialogService : IDialogService
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)
{
viewModel.RequestClose();
viewModel.NotifyClosed();
return;
}
var dialog = new QrCodeLoginDialog(viewModel);
using var registration = cancellationToken.Register(
() => Dispatcher.UIThread.Post(viewModel.RequestClose));
await dialog.ShowDialog(MainWindow);
}
}
@@ -8,16 +8,18 @@ public interface IDialogService
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 ShowMessageAsync(string title, string message);
/// <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>
Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel);
Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default);
}
@@ -8,13 +8,12 @@ public interface INavigationService
event EventHandler<ViewModelBase>? NavigationChanged;
/// <summary>
/// Push a page onto the navigation stack. Use for drill-down (detail pages, wizards).
/// 打开页面并保留返回记录。
/// </summary>
TViewModel NavigateTo<TViewModel>() where TViewModel : ViewModelBase;
/// <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>
TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase;
@@ -24,7 +24,7 @@ public class NavigationService : INavigationService
if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel))
{
// Already showing this page; do not restart it.
// 当前页面无需重复激活。
return viewModel;
}
@@ -40,6 +40,7 @@ public class NavigationService : INavigationService
return viewModel;
}
/// <inheritdoc />
public TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase
{
var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
@@ -79,8 +80,7 @@ public class NavigationService : INavigationService
}
/// <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>
private static async Task SafeActivateAsync(ViewModelBase viewModel)
{
@@ -90,7 +90,7 @@ public class NavigationService : INavigationService
}
catch (Exception)
{
// A failing OnActivated must not crash navigation.
// 页面自行处理错误,避免中断导航。
}
}
@@ -102,7 +102,7 @@ public class NavigationService : INavigationService
}
catch (Exception)
{
// A failing OnDeactivated must not crash navigation.
// 页面自行处理错误,避免中断导航。
}
}
}
@@ -21,9 +21,7 @@ public static class ServiceCollectionExtensions
services.BeginAutoDependencyInject<IWarpHttpClient>();
// 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.ConfigureLocalization();
services.ConfigureToolService();
@@ -43,10 +41,10 @@ public static class ServiceCollectionExtensions
services.AddSingleton<IDialogService, DialogService>();
services.AddSingleton<IThemeService, ThemeService>();
// Stores the NetEase login cookie between launches so the QR dialog is a first-run event.
// 保存网易云登录状态。
services.AddSingleton<NetEaseSessionStore>();
// Remembers a manually chosen KuGou database path (machine state, not a user preference).
// 保存本机酷狗数据库路径。
services.AddSingleton<KugouDatabaseStore>();
// Register ViewModels (Singleton to preserve state across navigation)
@@ -25,7 +25,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
private CancellationTokenSource? _downloadCts;
private readonly Dictionary<string, AlbumFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new();
private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty]
private string? _selectedFolderPath;
@@ -75,6 +75,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:";
public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download";
public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download";
/// <summary>扫描进度提示。</summary>
public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -142,23 +143,23 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync()
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Album_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder;
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
}
private bool CanSelectFolder => !IsScanning && !IsDownloading;
/// <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>
private async Task ScanFilesAsync()
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -176,8 +177,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
try
{
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions))
.ToList();
var files = (await Task.Run(
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0)
{
@@ -193,7 +195,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file =>
warpTask.RunAsync(async () =>
{
var musicInfo = await _tagLoader.LoadTagAsync(file);
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() =>
{
@@ -215,12 +217,16 @@ public partial class AlbumDownloadViewModel : ViewModelBase
ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
});
}));
}, cancellationToken));
await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
@@ -235,7 +241,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
[RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync()
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{
if (_scannedMusicInfos.Count == 0) return;
@@ -252,7 +258,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
}
_downloadCts = new CancellationTokenSource();
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try
{
@@ -283,9 +289,15 @@ public partial class AlbumDownloadViewModel : ViewModelBase
},
_downloadCts.Token);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{
// User cancelled.
// 用户取消下载。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
_localization?["Common_Error"] ?? "Error",
ex.Message);
}
finally
{
@@ -302,6 +314,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
}
/// <summary>
/// 单个音乐文件的封面下载状态。
/// </summary>
public partial class AlbumFileViewModel : ObservableObject
{
[ObservableProperty]
@@ -10,6 +10,9 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// 音乐文件解密页面。
/// </summary>
public partial class DecryptViewModel : ViewModelBase
{
private const string KggExtension = ".kgg";
@@ -23,6 +26,13 @@ public partial class DecryptViewModel : ViewModelBase
private CancellationTokenSource? _decryptCts;
private bool _isInitialized;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
private bool _isInitializing;
[ObservableProperty]
private int _parallelCount = 2;
@@ -42,13 +52,13 @@ public partial class DecryptViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
[NotifyPropertyChangedFor(nameof(CanClear))]
private bool _isDecrypting;
/// <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>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))]
@@ -57,54 +67,78 @@ public partial class DecryptViewModel : ViewModelBase
[ObservableProperty]
private string _kugouDatabaseStatus = string.Empty;
// Localized strings
// 界面文案。
/// <summary>页面标题。</summary>
public string DecryptTitle => _localization?["Decrypt_Title"] ?? "Music Decryption";
/// <summary>页面说明。</summary>
public string DecryptDescription => _localization?["Decrypt_Description"] ?? "Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats";
/// <summary>文件选择提示。</summary>
public string DecryptSelectFiles => _localization?["Decrypt_SelectFiles"] ?? "Select encrypted music files...";
/// <summary>添加文件按钮文案。</summary>
public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files...";
/// <summary>并行任务数标签。</summary>
public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:";
/// <summary>开始解密按钮文案。</summary>
public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt";
/// <summary>停止按钮文案。</summary>
public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop";
/// <summary>文件列表为空时的提示。</summary>
public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting";
/// <summary>清空按钮文案。</summary>
public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear";
/// <summary>文件列表标签。</summary>
public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files";
/// <summary>选择数据库按钮文案。</summary>
public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db...";
/// <summary>数据库缺失状态文案。</summary>
public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing";
/// <summary>查看详情按钮文案。</summary>
public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details";
/// <summary>失败详情窗口标题。</summary>
public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure";
/// <summary>
/// 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>
public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"]
?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)";
/// <summary>是否显示数据库缺失提示。</summary>
public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable;
/// <summary>
/// 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>
public string SelectionSummary => Files.Count == 0
? string.Empty
: $"{Files.Count} {CommonFiles}";
/// <summary>总数标签。</summary>
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
/// <summary>文件数量单位。</summary>
public string CommonFiles => _localization?["Common_Files"] ?? "files";
/// <summary>成功数量标签。</summary>
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
/// <summary>失败数量标签。</summary>
public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:";
/// <summary>文件名列标题。</summary>
public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name";
/// <summary>输出路径列标题。</summary>
public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output";
/// <summary>状态列标题。</summary>
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
// 全部行都被 blocked 时按钮不该亮着,否则点下去只会空转一次。
public bool CanStartDecrypt => !IsDecrypting && Files.Any(f => !f.IsBlocked);
/// <summary>是否存在可以开始解密的文件。</summary>
public bool CanStartDecrypt => !IsDecrypting && !IsInitializing && Files.Any(f => !f.IsBlocked);
/// <summary>文件列表是否为空。</summary>
public bool HasNoFiles => Files.Count == 0;
/// <summary>待解密文件列表。</summary>
public ObservableCollection<DecryptFileViewModel> Files { get; } = new();
/// <summary>
/// 创建音乐解密页面。
/// </summary>
public DecryptViewModel(
IMusicDecryptor musicDecryptor,
IDialogService dialogService,
@@ -135,11 +169,12 @@ public partial class DecryptViewModel : ViewModelBase
}
/// <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>
public override async Task OnActivatedAsync()
{
if (IsDecrypting || IsInitializing) return;
if (!_isInitialized)
{
await InitializeAsync();
@@ -149,26 +184,47 @@ public partial class DecryptViewModel : ViewModelBase
RefreshDatabaseStatus();
}
public async Task InitializeAsync()
/// <summary>
/// 初始化酷狗数据库路径。
/// </summary>
public async Task InitializeAsync(CancellationToken cancellationToken = default)
{
_isInitialized = true;
if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
{
var stored = await _kugouDatabaseStore.LoadAsync().ConfigureAwait(true);
if (!string.IsNullOrWhiteSpace(stored))
{
_kugouKeyProvider.SetDatabasePath(stored);
}
}
if (IsInitializing) return;
RefreshDatabaseStatus();
IsInitializing = true;
try
{
if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
{
var stored = await _kugouDatabaseStore.LoadAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(stored))
{
_kugouKeyProvider.SetDatabasePath(stored);
}
}
RefreshDatabaseStatus();
_isInitialized = true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消初始化,下次进入页面时重试。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", ex.Message);
}
finally
{
IsInitializing = false;
}
}
private void RefreshDatabaseStatus()
{
if (_kugouKeyProvider == null)
{
// No provider at all: keep the page usable, kgg will report the failure itself.
// 未注册密钥提供者时,由解密器报告具体错误。
IsKugouDatabaseAvailable = true;
KugouDatabaseStatus = string.Empty;
return;
@@ -178,7 +234,7 @@ public partial class DecryptViewModel : ViewModelBase
IsKugouDatabaseAvailable = info.IsAvailable;
KugouDatabaseStatus = info.Message;
// Rows added while the database was missing are stale the moment it becomes readable.
// 数据库可用后解除未处理文件的阻止状态。
foreach (var file in Files)
{
if (!IsKggFile(file.FilePath)) continue;
@@ -241,24 +297,35 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(ColumnFileName));
OnPropertyChanged(nameof(ColumnOutputPath));
OnPropertyChanged(nameof(ColumnStatus));
foreach (var file in Files)
{
file.ViewDetailLabel = DecryptViewDetail;
file.StatusMessage = file.IsBlocked
? DecryptStatusMissingDb
: file.IsProcessed
? file.IsSuccessful
? _localization?["Status_Success"] ?? "Success"
: _localization?["Status_Failed"] ?? "Failed"
: _localization?["Status_Pending"] ?? "Pending";
}
}
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SelectFilesAsync()
private async Task SelectFilesAsync(CancellationToken cancellationToken = default)
{
var picked = await _dialogService.ShowFilesPickerAsync(
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;
// 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();
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)))
{
continue;
@@ -277,9 +344,7 @@ public partial class DecryptViewModel : ViewModelBase
ViewDetailLabel = DecryptViewDetail
};
// 详情命令挂在行自己身上,比在模板里通过 $parent 硬转成父 VM 再取命令更稳,
// 也不会因为 DataTemplate 的上下文变化而悄悄失效。
row.ShowDetailCommand = new AsyncRelayCommand(() => ShowDetailAsync(row));
row.ShowDetailCommand = new AsyncRelayCommand(token => ShowDetailAsync(row, token));
Files.Add(row);
}
@@ -287,14 +352,15 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt));
}
private bool CanSelectFiles => !IsDecrypting;
private bool CanSelectFiles => !IsDecrypting && !IsInitializing;
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SpecifyDatabaseAsync()
private async Task SpecifyDatabaseAsync(CancellationToken cancellationToken = default)
{
var picked = await _dialogService.ShowFilePickerAsync(
DecryptSpecifyDatabase,
new[] { ".db" });
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrWhiteSpace(picked))
{
@@ -306,16 +372,15 @@ public partial class DecryptViewModel : ViewModelBase
if (_kugouDatabaseStore != null)
{
await _kugouDatabaseStore.SaveAsync(picked).ConfigureAwait(true);
await _kugouDatabaseStore.SaveAsync(picked, cancellationToken);
}
}
[RelayCommand(CanExecute = nameof(CanStartDecrypt))]
private async Task StartDecryptAsync()
private async Task StartDecryptAsync(CancellationToken cancellationToken = default)
{
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();
IsDecrypting = true;
@@ -329,6 +394,7 @@ public partial class DecryptViewModel : ViewModelBase
file.IsProcessed = false;
file.IsSuccessful = false;
file.OutputPath = null;
file.ErrorDetail = null;
if (!file.IsBlocked)
{
@@ -342,7 +408,7 @@ public partial class DecryptViewModel : ViewModelBase
return;
}
_decryptCts = new CancellationTokenSource();
_decryptCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = _decryptCts.Token;
try
@@ -358,7 +424,11 @@ public partial class DecryptViewModel : ViewModelBase
DecryptionResult result;
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)
{
@@ -379,8 +449,7 @@ public partial class DecryptViewModel : ViewModelBase
}
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.StatusMessage = _localization?["Status_Failed"] ?? "Failed";
FailedCount++;
@@ -389,13 +458,13 @@ public partial class DecryptViewModel : ViewModelBase
var done = CompletedCount + FailedCount;
ProgressPercentage = done * 100.0 / TotalCount;
});
}));
}, token));
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// User cancelled; rows that never ran stay "Pending".
// 用户取消时,未完成的文件保持待处理状态。
}
finally
{
@@ -406,11 +475,11 @@ public partial class DecryptViewModel : ViewModelBase
}
/// <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>
private async Task ShowDetailAsync(DecryptFileViewModel? file)
private async Task ShowDetailAsync(DecryptFileViewModel? file, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail))
{
return;
@@ -436,47 +505,57 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt));
}
/// <summary>
/// 是否可以清空文件列表。
/// </summary>
private bool CanClear => !IsDecrypting && Files.Count > 0;
}
/// <summary>
/// 单个文件的解密状态。
/// </summary>
public partial class DecryptFileViewModel : ObservableObject
{
/// <summary>输入文件路径。</summary>
[ObservableProperty]
private string _filePath = string.Empty;
/// <summary>输入文件名。</summary>
[ObservableProperty]
private string _fileName = string.Empty;
/// <summary>解密后的输出路径。</summary>
[ObservableProperty]
private string? _outputPath;
/// <summary>是否已完成处理。</summary>
[ObservableProperty]
private bool _isProcessed;
/// <summary>是否解密成功。</summary>
[ObservableProperty]
private bool _isSuccessful;
/// <summary>
/// Short label for the status column. Long explanations belong in <see cref="ErrorDetail"/>,
/// which the detail dialog shows in full.
/// 状态列摘要,完整原因保存在 <see cref="ErrorDetail"/>。
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _statusMessage;
/// <summary>解密失败的完整原因。</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _errorDetail;
/// <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>
[ObservableProperty]
private bool _isBlocked;
/// <summary>
/// 详情按钮上的文案。挂在行上,模板就不必再通过 $parent 反向取父 ViewModel。
/// 详情按钮文案。
/// </summary>
[ObservableProperty]
private string? _viewDetailLabel;
@@ -486,5 +565,8 @@ public partial class DecryptFileViewModel : ObservableObject
/// </summary>
public IAsyncRelayCommand? ShowDetailCommand { get; set; }
/// <summary>
/// 是否存在可查看的错误详情。
/// </summary>
public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail);
}
@@ -7,14 +7,16 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <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>
public partial class HomeViewModel : ViewModelBase
{
private readonly INavigationService _navigation;
private readonly IUILocalizationService _localization;
/// <summary>
/// 创建首页。
/// </summary>
public HomeViewModel(INavigationService navigation, IUILocalizationService localization)
{
_navigation = navigation;
@@ -26,22 +28,37 @@ public partial class HomeViewModel : ViewModelBase
[ObservableProperty]
private string _version;
/// <summary>欢迎语。</summary>
public string WelcomeMessage => _localization["Home_Welcome"];
/// <summary>应用说明。</summary>
public string Description => _localization["Home_Description"];
/// <summary>快捷操作标题。</summary>
public string QuickActionsTitle => _localization["Home_QuickActions"];
/// <summary>功能特性标题。</summary>
public string FeaturesTitle => _localization["Home_Features"];
/// <summary>支持格式说明。</summary>
public string FeatureFormats => _localization["Home_FeatureFormats"];
/// <summary>并行下载说明。</summary>
public string FeatureParallel => _localization["Home_FeatureParallel"];
/// <summary>编码支持说明。</summary>
public string FeatureEncodings => _localization["Home_FeatureEncodings"];
/// <summary>跨平台支持说明。</summary>
public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"];
/// <summary>版本标签。</summary>
public string VersionLabel => _localization["Home_Version"];
// Card copy: title + one-line explanation, both localized.
// 功能入口文案。
/// <summary>歌词下载入口标题。</summary>
public string LyricsCardTitle => _localization["Home_DownloadLyrics"];
/// <summary>歌词下载入口说明。</summary>
public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"];
/// <summary>封面下载入口标题。</summary>
public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"];
/// <summary>封面下载入口说明。</summary>
public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"];
/// <summary>音乐解密入口标题。</summary>
public string DecryptCardTitle => _localization["Home_Decrypt"];
/// <summary>音乐解密入口说明。</summary>
public string DecryptCardDescription => _localization["Home_DecryptHint"];
[RelayCommand]
@@ -79,7 +96,7 @@ public partial class HomeViewModel : ViewModelBase
if (!string.IsNullOrWhiteSpace(informational))
{
// Strip the "+<commit sha>" suffix that SourceLink appends.
// 隐藏 SourceLink 添加的提交标识。
var plusIndex = informational.IndexOf('+');
return plusIndex > 0 ? informational[..plusIndex] : informational;
}
@@ -17,17 +17,17 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Which source the lyrics page reads its song list from.
/// 歌词列表的数据来源。
/// </summary>
public enum LyricsScannerKind
{
/// <summary>Scan a local folder for audio files.</summary>
/// <summary>扫描本地音乐文件夹。</summary>
Local = 0,
/// <summary>Read a CSV file containing "song,artist" rows.</summary>
/// <summary>读取歌曲与歌手信息的 CSV 文件。</summary>
Csv = 1,
/// <summary>Pull a NetEase Cloud Music playlist by id.</summary>
/// <summary>读取网易云歌单。</summary>
NetEase = 2
}
@@ -47,9 +47,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private readonly IUILocalizationService? _localization;
private CancellationTokenSource? _downloadCts;
private CancellationTokenSource? _scanCts;
private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new();
private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
@@ -73,6 +72,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(IsLocalScanner))]
[NotifyPropertyChangedFor(nameof(IsCsvScanner))]
[NotifyPropertyChangedFor(nameof(IsNetEaseScanner))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private int _selectedScannerIndex;
@@ -93,6 +93,14 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
private bool _isDownloading;
@@ -102,6 +110,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private bool _isScanning;
@@ -121,10 +132,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
private bool _isNetEaseLoggedIn;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
private bool _isAccountBusy;
[ObservableProperty]
private string? _currentProcessingFile;
// Localized strings
// 界面文案。
public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download";
public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files";
public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder";
@@ -134,32 +158,45 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download";
public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download";
public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
/// <summary>数据来源标签。</summary>
public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source";
/// <summary>扫描按钮文案。</summary>
public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan";
/// <summary>CSV 文件标签。</summary>
public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File";
/// <summary>CSV 文件选择提示。</summary>
public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file...";
/// <summary>CSV 文件选择按钮文案。</summary>
public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose...";
/// <summary>网易云歌单编号标签。</summary>
public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID";
/// <summary>网易云歌单编号输入提示。</summary>
public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)";
/// <summary>输出目录标签。</summary>
public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To";
/// <summary>输出目录选择提示。</summary>
public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written";
/// <summary>输出目录选择按钮文案。</summary>
public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose...";
/// <summary>退出登录按钮文案。</summary>
public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out";
/// <summary>退出登录提示。</summary>
public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ??
"Forget the saved session and scan the QR code again next time.";
/// <summary>登录按钮文案。</summary>
public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…";
/// <summary>登录按钮提示。</summary>
public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ??
"Scan a QR code now instead of waiting until the next scan.";
/// <summary>
/// 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>
public string NetEaseAccountStatus => IsNetEaseLoggedIn
? _localization?["NetEase_LoggedIn"] ?? "Signed in. Scanning a playlist reuses this session."
: _localization?["NetEase_NotLoggedIn"] ?? "Not signed in. Scanning a playlist will show a QR code.";
/// <summary>账号状态标签。</summary>
public string NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -171,7 +208,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
/// <summary>
/// Scanner display names, indexed the same way as <see cref="SelectedScannerIndex"/>.
/// 按 <see cref="SelectedScannerIndex"/> 排列的数据来源名称。
/// </summary>
public string[] ScannerNames =>
[
@@ -184,7 +221,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv;
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;
@@ -222,8 +259,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
_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;
MusicFiles.CollectionChanged += (_, _) =>
@@ -273,75 +309,93 @@ public partial class LyricsDownloadViewModel : ViewModelBase
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))]
private async Task SelectFolderAsync()
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder;
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
}
private bool CanSelectFolder => !IsScanning && !IsDownloading;
/// <summary>
/// 是否可以修改任务来源与输出目录。
/// </summary>
public bool CanEditInputs => !IsScanning && !IsDownloading && !IsAccountBusy;
private bool CanSelectFolder => CanEditInputs;
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectCsvFileAsync()
private async Task SelectCsvFileAsync(CancellationToken cancellationToken = default)
{
var file = await _dialogService.ShowFilePickerAsync(
_localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(file)) return;
SelectedCsvFilePath = file;
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectOutputFolderAsync()
private async Task SelectOutputFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_OutputSelect"] ?? "Select Output Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
OutputDirectory = folder;
}
// ---------------------------------------------------------------- scanning
/// <summary>
/// Whether the current source has enough input to start reading a song list.
/// 当前来源是否具备扫描所需的输入。
/// </summary>
public bool CanScan => !IsScanning && !IsDownloading && SelectedScannerIndex switch
public bool CanScan => CanEditInputs && (SelectedScannerIndex switch
{
(int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath),
(int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath),
(int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds),
_ => false
};
});
/// <summary>
/// Re-read the song list using the currently selected source.
/// 使用当前来源重新读取歌曲列表。
/// </summary>
[RelayCommand(CanExecute = nameof(CanScan))]
private async Task StartScanAsync()
private async Task StartScanAsync(CancellationToken cancellationToken = default)
{
switch ((LyricsScannerKind)SelectedScannerIndex)
{
case LyricsScannerKind.Csv:
await ScanCsvFileAsync();
await ScanCsvFileAsync(cancellationToken);
break;
case LyricsScannerKind.NetEase:
await ScanNetEasePlaylistAsync();
await ScanNetEasePlaylistAsync(cancellationToken);
break;
default:
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
break;
}
}
private async Task ScanFilesAsync()
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -350,12 +404,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try
{
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions))
.ToList();
var files = (await Task.Run(
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0)
{
await ShowNoMusicFilesAsync();
await ShowNoMusicFilesAsync(cancellationToken);
return;
}
@@ -365,7 +420,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file =>
warpTask.RunAsync(async () =>
{
var musicInfo = await _tagLoader.LoadTagAsync(file);
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() =>
{
@@ -378,15 +433,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
});
}));
}, cancellationToken));
await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
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;
@@ -403,16 +462,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try
{
var musicInfos = await _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
SelectedCsvFilePath,
RequireOutputDirectory(),
DefaultFileNamePattern);
var outputDirectory = RequireOutputDirectory();
var musicInfos = await Task.Run(() => _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
SelectedCsvFilePath, outputDirectory, DefaultFileNamePattern, cancellationToken), cancellationToken);
AppendScannedMusicInfos(musicInfos);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
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;
ResetCollections();
IsScanning = true;
using var scanCts = new CancellationTokenSource();
_scanCts = scanCts;
try
{
await RestoreNetEaseSessionAsync();
await RestoreNetEaseSessionAsync(cancellationToken);
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync())
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync(cancellationToken))
{
return;
}
@@ -448,46 +507,43 @@ public partial class LyricsDownloadViewModel : ViewModelBase
DefaultFileNamePattern,
onQrCodeReady: null,
onStateChanged: null,
cancellationToken: scanCts.Token);
cancellationToken: cancellationToken);
await PersistNetEaseSessionAsync();
await PersistNetEaseSessionAsync(cancellationToken);
AppendScannedMusicInfos(musicInfos);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// User closed the login dialog.
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
_scanCts = null;
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;
}
}
/// <summary>
/// Load a previously saved NetEase session so the QR dialog only appears on first use.
/// 恢复已保存的网易云登录状态。
/// </summary>
private async Task RestoreNetEaseSessionAsync()
private async Task RestoreNetEaseSessionAsync(CancellationToken cancellationToken = default)
{
if (_neteaseMusicScanner.IsLoggedIn) return;
var session = await _sessionStore.LoadAsync();
var session = await _sessionStore.LoadAsync(cancellationToken);
if (session == null) return;
_neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken);
}
private async Task PersistNetEaseSessionAsync()
private async Task PersistNetEaseSessionAsync(CancellationToken cancellationToken = default)
{
if (!_neteaseMusicScanner.IsLoggedIn) return;
@@ -495,61 +551,81 @@ public partial class LyricsDownloadViewModel : ViewModelBase
{
Cookie = _neteaseMusicScanner.Cookie,
CsrfToken = _neteaseMusicScanner.CsrfToken,
SavedAt = DateTimeOffset.Now
});
SavedAtUtc = DateTimeOffset.UtcNow
}, cancellationToken);
}
/// <summary>
/// Show the QR dialog and wait for the scan-and-confirm flow to finish.
/// 显示二维码并等待登录或窗口关闭。
/// </summary>
private async Task<bool> LoginToNetEaseAsync()
private async Task<bool> LoginToNetEaseAsync(CancellationToken cancellationToken = default)
{
var loginViewModel = new QrCodeLoginViewModel(_localization);
using var loginCts = new CancellationTokenSource();
loginViewModel.Cancelled += (_, _) => loginCts.Cancel();
using var loginCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
void OnCancelled(object? sender, EventArgs args) => loginCts.Cancel();
loginViewModel.Cancelled += OnCancelled;
var loginTask = Task.Run(async () =>
{
try
{
var expired = false;
var isSuccess = await _neteaseMusicScanner.LoginAsync(
payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)),
state => Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)),
state =>
{
expired = state == NetEaseLoginState.Expired;
Dispatcher.UIThread.Post(() => loginViewModel.SetState(state));
},
loginCts.Token);
if (isSuccess)
await Dispatcher.UIThread.InvokeAsync(() =>
{
Dispatcher.UIThread.Post(() => loginViewModel.Complete());
}
if (isSuccess)
{
loginViewModel.Complete();
}
else if (!expired)
{
loginViewModel.SetError(_localization?["NetEase_LoginFailed"] ??
"Login did not complete. Close this dialog and try again.");
}
});
return isSuccess;
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (loginCts.IsCancellationRequested)
{
return false;
}
catch (Exception ex)
{
Dispatcher.UIThread.Post(() => loginViewModel.SetError(ex.Message));
await Dispatcher.UIThread.InvokeAsync(() => loginViewModel.SetError(ex.Message));
return false;
}
});
// The dialog closes itself once the flow calls Complete(), so this await returns as soon
// as the user either confirms on the phone or gives up.
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel);
try
{
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel, cancellationToken);
}
finally
{
loginViewModel.NotifyClosed();
loginCts.Cancel();
await loginTask;
loginViewModel.Cancelled -= OnCancelled;
}
var isSuccess = await loginTask;
if (isSuccess)
{
await PersistNetEaseSessionAsync();
await PersistNetEaseSessionAsync(cancellationToken);
}
return isSuccess;
}
// ---------------------------------------------------------------- shared helpers
private void ResetCollections()
{
@@ -567,6 +643,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private void AddRow(MusicInfo musicInfo)
{
if (_musicFileMap.ContainsKey(musicInfo.FilePath)) return;
var vm = new MusicFileViewModel
{
FilePath = musicInfo.FilePath,
@@ -581,7 +659,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
/// <summary>
/// Fill the grid from a scanner that returns its list in one shot (CSV, NetEase).
/// 将 CSV 或网易云扫描结果加入列表。
/// </summary>
private void AppendScannedMusicInfos(List<MusicInfo> musicInfos)
{
@@ -611,22 +689,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
return fallback;
}
private Task ShowNoMusicFilesAsync()
private Task ShowNoMusicFilesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
}
private Task ShowErrorAsync(string message)
private Task ShowErrorAsync(string message, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message);
}
// ---------------------------------------------------------------- download
[RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync()
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{
if (_scannedMusicInfos.Count == 0) return;
@@ -643,7 +722,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
}
_downloadCts = new CancellationTokenSource();
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try
{
@@ -683,9 +762,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
},
_downloadCts.Token);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{
// User cancelled
// 用户取消下载。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
@@ -702,54 +785,85 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
/// <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>
[RelayCommand(CanExecute = nameof(IsNetEaseLoggedIn))]
private async Task SignOutNetEaseAsync()
[RelayCommand(CanExecute = nameof(CanSignOutNetEase))]
private async Task SignOutNetEaseAsync(CancellationToken cancellationToken = default)
{
_neteaseMusicScanner.ClearLoginState();
await _sessionStore.ClearAsync();
IsNetEaseLoggedIn = false;
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
IsAccountBusy = true;
try
{
await _sessionStore.ClearAsync(cancellationToken);
_neteaseMusicScanner.ClearLoginState();
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消操作。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
}
}
private bool CanSignInNetEase => !IsNetEaseLoggedIn && !IsScanning && !IsDownloading;
private bool CanSignInNetEase => !IsNetEaseLoggedIn && CanEditInputs;
private bool CanSignOutNetEase => IsNetEaseLoggedIn && CanEditInputs;
/// <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>
[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>
/// 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>
private async Task RefreshNetEaseLoginStateAsync()
{
await RestoreNetEaseSessionAsync();
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
SignOutNetEaseCommand.NotifyCanExecuteChanged();
SignInNetEaseCommand.NotifyCanExecuteChanged();
}
public override async Task OnActivatedAsync()
{
await base.OnActivatedAsync();
await RefreshNetEaseLoginStateAsync();
if (!CanEditInputs) return;
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 NavLyricsDownload => _localization["Nav_LyricsDownload"];
public string NavAlbumDownload => _localization["Nav_AlbumDownload"];
/// <summary>音乐解密导航文案。</summary>
public string NavDecrypt => _localization["Nav_Decrypt"];
public string NavSettings => _localization["Nav_Settings"];
public string HomeDescription => _localization["Home_Description"];
@@ -44,17 +45,20 @@ public partial class MainWindowViewModel : ViewModelBase
_themeService = themeService;
_localization = localization;
_navigation = navigation;
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
_themeService.ThemeChanged += (_, _) =>
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
// Subscribe to language changes
_localization.LanguageChanged += OnLanguageChanged;
// The navigation service is the single owner of "which page is showing".
// 页面切换统一由导航服务管理。
_navigation.NavigationChanged += OnNavigationChanged;
NavigateToIndex(0);
}
// Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed".
// 避免导航通知与侧栏选中状态互相触发。
private bool _isSyncingNavigation;
partial void OnSelectedNavigationIndexChanged(int value)
@@ -69,8 +73,7 @@ public partial class MainWindowViewModel : ViewModelBase
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
{
1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(),
@@ -85,7 +88,7 @@ public partial class MainWindowViewModel : ViewModelBase
{
CurrentPage = viewModel;
// The home page quick actions navigate directly, so the sidebar has to follow them.
// 首页快捷入口跳转时同步侧栏选中项。
var index = IndexOf(viewModel);
if (index < 0 || index == SelectedNavigationIndex)
{
@@ -128,9 +131,6 @@ public partial class MainWindowViewModel : ViewModelBase
[RelayCommand]
private void ToggleTheme()
{
IsDarkTheme = !IsDarkTheme;
_themeService.SetTheme(IsDarkTheme
? Avalonia.Styling.ThemeVariant.Dark
: Avalonia.Styling.ThemeVariant.Light);
_themeService.ToggleTheme();
}
}
@@ -7,16 +7,12 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Drives the NetEase QR-code login dialog.
/// 网易云扫码登录对话框。
/// </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
{
private readonly IUILocalizationService? _localization;
private bool _isClosed;
[ObservableProperty]
private Bitmap? _qrCodeImage;
@@ -28,24 +24,30 @@ public partial class QrCodeLoginViewModel : ObservableObject
private bool _hasImage;
/// <summary>
/// Raised when the login flow wants the dialog closed.
/// 请求关闭登录对话框。
/// </summary>
public event EventHandler? CloseRequested;
/// <summary>
/// Raised when the user closed the dialog before logging in.
/// 登录完成前关闭对话框时触发。
/// </summary>
public event EventHandler? Cancelled;
/// <summary>
/// True once the login succeeded; the dialog stays closable but no longer counts as a cancel.
/// 是否已登录成功。
/// </summary>
public bool IsCompleted { get; private set; }
/// <summary>登录窗口标题。</summary>
public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music";
/// <summary>扫码登录提示。</summary>
public string LoginTip => _localization?["NetEase_LoginTip"] ?? "Scan the QR code with the NetEase Cloud Music app on your phone.";
/// <summary>取消按钮文案。</summary>
public string CancelText => _localization?["Common_Cancel"] ?? "Cancel";
/// <summary>
/// 创建扫码登录对话框状态。
/// </summary>
public QrCodeLoginViewModel(IUILocalizationService? localization = null)
{
_localization = localization;
@@ -57,47 +59,60 @@ public partial class QrCodeLoginViewModel : ObservableObject
private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in.";
/// <summary>
/// Render the QR payload the scanner produced.
/// 显示扫描器提供的二维码。
/// </summary>
public void SetPayload(NetEaseQrCodePayload payload)
{
if (_isClosed) return;
var previousImage = QrCodeImage;
QrCodeImage = RenderQrCode(payload.Content);
HasImage = QrCodeImage != null;
StatusText = WaitText;
previousImage?.Dispose();
StatusText = HasImage
? WaitText
: _localization?["NetEase_LoginFailed"] ?? "Login did not complete. Close this dialog and try again.";
}
/// <summary>
/// Reflect a login-state change reported by the scanner.
/// 更新扫码登录状态。
/// </summary>
public void SetState(NetEaseLoginState state)
{
if (_isClosed) return;
StatusText = state switch
{
NetEaseLoginState.ScanConfirmed => ScannedText,
NetEaseLoginState.Succeeded => SuccessText,
NetEaseLoginState.Expired => _localization?["NetEase_LoginExpired"] ?? "The QR code expired. Close this dialog and try again.",
_ => WaitText
};
}
/// <summary>
/// Push an error message into the dialog.
/// 显示登录错误。
/// </summary>
public void SetError(string message)
{
if (_isClosed) return;
StatusText = message;
}
/// <summary>
/// Mark the flow as finished and close the dialog.
/// 标记登录完成并关闭对话框。
/// </summary>
public void Complete()
{
if (_isClosed) return;
IsCompleted = true;
RequestClose();
}
/// <summary>
/// Ask the dialog to close.
/// 请求关闭对话框。
/// </summary>
public void RequestClose()
{
@@ -105,10 +120,18 @@ public partial class QrCodeLoginViewModel : ObservableObject
}
/// <summary>
/// Called by the dialog when its window closed, for whatever reason.
/// 窗口关闭后停止登录并释放二维码。
/// </summary>
public void NotifyClosed()
{
if (_isClosed) return;
_isClosed = true;
var image = QrCodeImage;
QrCodeImage = null;
HasImage = false;
image?.Dispose();
if (!IsCompleted)
{
Cancelled?.Invoke(this, EventArgs.Empty);
@@ -121,13 +144,13 @@ public partial class QrCodeLoginViewModel : ObservableObject
{
using var generator = new QRCodeGenerator();
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
var pngBytes = new PngByteQRCode(data).GetGraphic(12);
return new Bitmap(new MemoryStream(pngBytes));
using var qrCode = new PngByteQRCode(data);
using var stream = new MemoryStream(qrCode.GetGraphic(12));
return new Bitmap(stream);
}
catch (Exception)
{
// A render failure shows up as the placeholder, not as a crash.
// 二维码无法生成时,由界面显示登录失败提示。
return null;
}
}
@@ -9,12 +9,13 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>设置页面及自动保存状态。</summary>
public partial class SettingsViewModel : ViewModelBase
{
private readonly ISettingsStore _settingsStore;
private readonly IUILocalizationService? _localizationService;
private readonly GlobalOptions _globalOptions;
private bool _isLoading = true; // Prevent saving during initial load
private bool _isLoading = true;
[ObservableProperty]
private bool _followSystemLanguage = true;
@@ -32,7 +33,7 @@ public partial class SettingsViewModel : ViewModelBase
private string _proxyIp = "127.0.0.1";
[ObservableProperty]
private int _proxyPort = 7890;
private int _proxyPort = 4780;
[ObservableProperty]
private bool _isTranslationEnabled;
@@ -61,15 +62,11 @@ public partial class SettingsViewModel : ViewModelBase
[ObservableProperty]
private bool _isRomanOutputEnabled;
/// <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>
/// <summary>是否显示高级设置。</summary>
[ObservableProperty]
private bool _isAdvancedVisible;
// Status line for the settings page: shows where settings are stored and whether the
// last save succeeded.
// 显示配置位置及上次保存结果。
[ObservableProperty]
private string _storageHint = string.Empty;
@@ -83,10 +80,7 @@ public partial class SettingsViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
private bool _hasSaveError;
/// <summary>
/// Encoding choices offered in the settings page. These map to the values accepted by
/// <see cref="GlobalLyricsConfigOptions.FileEncoding"/>.
/// </summary>
/// <summary>可选择的歌词编码。</summary>
public ObservableCollection<string> AvailableEncodings { get; } = new()
{
"utf-8",
@@ -95,10 +89,7 @@ public partial class SettingsViewModel : ViewModelBase
"gbk"
};
/// <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>
/// <summary>预设换行符,与显示列表顺序一致。</summary>
private static readonly string[] LineBreaks =
{
LineBreakType.Unix,
@@ -106,9 +97,7 @@ public partial class SettingsViewModel : ViewModelBase
LineBreakType.MacOs
};
/// <summary>
/// Display names for the line-break selector, parallel to the internal sequence table.
/// </summary>
/// <summary>换行符的显示名称。</summary>
public ObservableCollection<string> LineBreakDisplayNames { get; } = new()
{
"LF (Unix)",
@@ -116,68 +105,103 @@ public partial class SettingsViewModel : ViewModelBase
"CR (macOS)"
};
/// <summary>
/// Value the current settings file uses, for the selected line-break entry.
/// </summary>
private string CurrentLineBreak => LineBreaks[Math.Clamp(SelectedLineBreakIndex, 0, LineBreaks.Length - 1)];
private string CurrentLineBreak => SelectedLineBreakIndex >= 0 && SelectedLineBreakIndex < LineBreaks.Length
? LineBreaks[SelectedLineBreakIndex]
: _globalOptions.Provider?.Lyric?.Config?.LineBreak ?? LineBreakType.Unix;
/// <summary>歌词提供者及搜索顺序。</summary>
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new();
/// <summary>标签提供者及加载顺序。</summary>
public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new();
// Localized strings
// 本地化文本。
/// <summary>设置标题的本地化文本。</summary>
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
/// <summary>语言设置标题的本地化文本。</summary>
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
/// <summary>跟随系统语言的本地化文本。</summary>
public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System";
/// <summary>中文选项的本地化文本。</summary>
public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese";
/// <summary>英文选项的本地化文本。</summary>
public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English";
/// <summary>代理设置标题的本地化文本。</summary>
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
/// <summary>启用代理的本地化文本。</summary>
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
/// <summary>代理地址的本地化文本。</summary>
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
/// <summary>代理端口的本地化文本。</summary>
public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port";
/// <summary>歌词提供者标题的本地化文本。</summary>
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
/// <summary>恢复默认值的本地化文本。</summary>
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
/// <summary>基本设置标题的本地化文本。</summary>
public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics";
/// <summary>高级设置标题的本地化文本。</summary>
public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced";
/// <summary>高级选项开关的本地化文本。</summary>
public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options";
/// <summary>歌词设置标题的本地化文本。</summary>
public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics";
/// <summary>翻译开关的本地化文本。</summary>
public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics";
/// <summary>合并双语歌词开关的本地化文本。</summary>
public string SettingsOneLineMode => _localizationService?["Settings_OneLineMode"] ?? "One-line mode (original + translation on same line)";
/// <summary>仅输出翻译开关的本地化文本。</summary>
public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only";
/// <summary>跳过已有文件开关的本地化文本。</summary>
public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files";
/// <summary>编码选项的本地化文本。</summary>
public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:";
/// <summary>换行符选项的本地化文本。</summary>
public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:";
/// <summary>罗马音开关的本地化文本。</summary>
public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)";
/// <summary>屏蔽词设置标题的本地化文本。</summary>
public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary";
/// <summary>屏蔽词开关的本地化文本。</summary>
public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary";
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";
/// <summary>优先级标题的本地化文本。</summary>
public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: ";
/// <summary>上移按钮的本地化文本。</summary>
public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up";
/// <summary>下移按钮的本地化文本。</summary>
public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down";
/// <summary>提供者顺序说明的本地化文本。</summary>
public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"]
?? "The list order is the search order. Use the arrows to change which source is tried first.";
/// <summary>设置保存位置的本地化文本。</summary>
public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file";
/// <summary>保存成功的本地化文本。</summary>
public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved";
/// <summary>保存失败的本地化文本。</summary>
public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings";
/// <summary>代理重启提示的本地化文本。</summary>
public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"]
?? "Proxy changes take effect the next time the app starts.";
/// <summary>
/// Save feedback: only one of these is ever true, and both stay false before the first save.
/// </summary>
/// <summary>是否显示保存成功提示。</summary>
public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>是否显示保存失败提示。</summary>
public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>创建设置页面。</summary>
public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null)
{
_settingsStore = settingsStore;
_localizationService = localizationService;
_globalOptions = settingsStore.Options;
// Subscribe to language changes
// 跟随应用语言切换更新界面。
if (_localizationService != null)
{
_localizationService.LanguageChanged += OnLanguageChanged;
@@ -186,7 +210,7 @@ public partial class SettingsViewModel : ViewModelBase
LoadSettings();
LoadLanguageSettings();
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
_isLoading = false; // Allow saving after initial load
_isLoading = false;
}
private void OnLanguageChanged(object? sender, EventArgs e)
@@ -225,6 +249,7 @@ public partial class SettingsViewModel : ViewModelBase
OnPropertyChanged(nameof(SettingsSaved));
OnPropertyChanged(nameof(SettingsSaveFailed));
OnPropertyChanged(nameof(SettingsProxyRestartHint));
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
}
private void LoadLanguageSettings()
@@ -238,7 +263,7 @@ public partial class SettingsViewModel : ViewModelBase
{
if (value)
{
// Auto-detect system language
// 使用操作系统语言。
var systemCulture = CultureInfo.InstalledUICulture.Name;
ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US");
}
@@ -294,12 +319,12 @@ public partial class SettingsViewModel : ViewModelBase
private void LoadSettings()
{
// Load network settings
// 加载代理设置。
IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false;
ProxyIp = _globalOptions.NetworkOptions?.Ip ?? "127.0.0.1";
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 7890;
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 4780;
// Load lyrics settings
// 加载歌词设置,保留未列入预设的有效编码。
var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
if (lyricsConfig != null)
{
@@ -307,11 +332,15 @@ public partial class SettingsViewModel : ViewModelBase
IsOneLineMode = lyricsConfig.IsOneLine;
SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles;
SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8";
if (!AvailableEncodings.Contains(SelectedEncoding))
{
AvailableEncodings.Add(SelectedEncoding);
}
IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation;
SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak);
}
// Load block word settings
// 加载屏蔽词设置。
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
if (blockWord != null)
{
@@ -321,7 +350,7 @@ public partial class SettingsViewModel : ViewModelBase
: blockWord.FilePath;
}
// Load romanized output flag from the NetEase provider's extended options
// 罗马音开关保存在网易云提供者的扩展设置中。
var netEase = _globalOptions.Provider?.Lyric?.Plugin?
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
if (netEase?.Additional != null &&
@@ -330,9 +359,7 @@ public partial class SettingsViewModel : ViewModelBase
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;
if (tagProviders != null)
{
@@ -341,8 +368,7 @@ public partial class SettingsViewModel : ViewModelBase
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))
{
AddTagProviderRow(provider.Name, false);
@@ -351,7 +377,7 @@ public partial class SettingsViewModel : ViewModelBase
NormalizeProviderOrder(TagProviders);
}
// Lyrics providers follow the same rule as the tag providers above.
// 歌词提供者与标签提供者采用相同排序规则。
var providers = _globalOptions.Provider?.Lyric?.Plugin;
if (providers != null)
{
@@ -377,13 +403,11 @@ public partial class SettingsViewModel : ViewModelBase
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.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;
TagProviders.Add(row);
}
@@ -403,11 +427,7 @@ public partial class SettingsViewModel : ViewModelBase
LyricsProviders.Add(row);
}
/// <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>
/// <summary>提供者启用状态改变后重新排序并保存。</summary>
private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_isLoading || _isNormalizing)
@@ -442,11 +462,7 @@ public partial class SettingsViewModel : ViewModelBase
private bool _isNormalizing;
/// <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>
/// <summary>启用项在前,优先级按可见顺序从一开始。</summary>
private void NormalizeProviderOrder<T>(ObservableCollection<T> rows) where T : class, IProviderRowViewModel
{
var ordered = rows.Where(r => r.IsEnabled).Concat(rows.Where(r => !r.IsEnabled)).ToList();
@@ -465,8 +481,7 @@ public partial class SettingsViewModel : ViewModelBase
{
var row = ordered[i];
// 禁用行在内存里就写 -1,和配置文件里的语义保持一致;否则一旦某条路径漏掉
// ApplyProviderSelection,就会把一个不存在的「第 5 名」写回 config.yaml。
// 禁用项统一使用 -1。
row.Priority = i < enabledCount ? i + 1 : -1;
row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—";
row.CanMoveUp = i > 0 && i < enabledCount;
@@ -474,11 +489,7 @@ public partial class SettingsViewModel : ViewModelBase
}
}
/// <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>
/// <summary>在启用项范围内移动提供者。</summary>
private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset)
where T : class, IProviderRowViewModel
{
@@ -513,7 +524,7 @@ public partial class SettingsViewModel : ViewModelBase
}
}
return 0;
return -1;
}
private void WriteSettingsToOptions()
@@ -551,18 +562,12 @@ public partial class SettingsViewModel : ViewModelBase
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?.Tag?.Plugin, TagProviders);
}
/// <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>
/// <summary>将歌词提供者的界面顺序写入共享配置。</summary>
private static void ApplyProviderSelection(
IEnumerable<LyricsProviderOptions>? options,
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);
await Task.Delay(SaveDebounceMilliseconds).ConfigureAwait(true);
await Task.Delay(SaveDebounceMilliseconds, cancellationToken).ConfigureAwait(true);
if (pending != Volatile.Read(ref _saveRequestId))
{
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;
SaveStatusText = result.IsSuccess
@@ -635,12 +644,13 @@ public partial class SettingsViewModel : ViewModelBase
private const int SaveDebounceMilliseconds = 400;
[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;
ProxyIp = "127.0.0.1";
ProxyPort = 7890;
ProxyPort = 4780;
IsTranslationEnabled = true;
IsOneLineMode = true;
SkipExistingLyrics = false;
@@ -651,9 +661,9 @@ public partial class SettingsViewModel : ViewModelBase
BlockWordFilePath = "BlockWords.json";
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
// are listed, which the numbering then reflects as 1..n again.
// 恢复随程序附带的默认顺序,额外提供者保留在末尾。
RestoreProviderOrder(LyricsProviders, ["NetEase", "QQ", "KuGou", "KuWo"], row => row.Name);
RestoreProviderOrder(TagProviders, ["Taglib", "FileName"], row => row.Name);
foreach (var row in LyricsProviders)
{
row.IsEnabled = true;
@@ -669,44 +679,59 @@ public partial class SettingsViewModel : ViewModelBase
_isLoading = false;
// Save once after all resets
// 所有默认值恢复后只保存一次。
WriteSettingsToOptions();
var result = await _settingsStore.SaveAsync().ConfigureAwait(true);
var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess
? $"{SettingsSaved}: {result.FilePath}"
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
}
private static void RestoreProviderOrder<T>(ObservableCollection<T> rows, string[] names, Func<T, string> getName)
where T : class
{
var target = 0;
foreach (var name in names)
{
var row = rows.FirstOrDefault(row => string.Equals(getName(row), name, StringComparison.OrdinalIgnoreCase));
if (row is not null)
{
rows.Move(rows.IndexOf(row), target++);
}
}
}
}
/// <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>
/// <summary>可排序的提供者设置行。</summary>
public interface IProviderRowViewModel
{
/// <summary>是否启用。</summary>
bool IsEnabled { get; set; }
/// <summary>搜索优先级,禁用时为 -1。</summary>
int Priority { get; set; }
/// <summary>界面显示的顺序。</summary>
string PriorityLabel { get; set; }
/// <summary>是否可以向上移动。</summary>
bool CanMoveUp { get; set; }
/// <summary>是否可以向下移动。</summary>
bool CanMoveDown { get; set; }
/// <summary>
/// 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>
/// <summary>禁用时降低行透明度。</summary>
double RowOpacity { get; }
/// <summary>向上移动命令。</summary>
IRelayCommand MoveUpCommand { get; }
/// <summary>向下移动命令。</summary>
IRelayCommand MoveDownCommand { get; }
}
/// <summary>歌词提供者设置行。</summary>
public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{
[ObservableProperty]
@@ -716,17 +741,11 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[NotifyPropertyChangedFor(nameof(RowOpacity))]
private bool _isEnabled;
/// <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>
/// <summary>搜索优先级,禁用时为 -1。</summary>
[ObservableProperty]
private int _priority;
/// <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>
/// <summary>显示的顺序,禁用时显示横线。</summary>
[ObservableProperty]
private string _priorityLabel = string.Empty;
@@ -736,13 +755,17 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[ObservableProperty]
private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
}
/// <summary>标签提供者设置行。</summary>
public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{
[ObservableProperty]
@@ -766,9 +789,12 @@ public partial class TagInfoProviderSettingViewModel : ObservableObject, IProvid
[ObservableProperty]
private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
}
@@ -16,7 +16,7 @@
FontWeight="SemiBold"
Margin="0,0,0,12" />
<!-- Message. 用只读 TextBox 而不是 TextBlock,这样正文可以被选中复制。 -->
<!-- 正文可选中并复制。 -->
<TextBox Grid.Row="1"
x:Name="MessageText"
IsReadOnly="True"
@@ -20,7 +20,7 @@
Opacity="0.65"
TextWrapping="Wrap" />
<!-- QR surface: fixed size so the dialog does not jump when the image arrives. -->
<!-- 固定二维码区域尺寸,避免加载时窗口跳动。 -->
<Border Width="240" Height="240"
HorizontalAlignment="Center"
Background="White"
@@ -4,15 +4,24 @@ using ZonyLrcTools.Desktop.ViewModels;
namespace ZonyLrcTools.Desktop.Views.Dialogs;
/// <summary>
/// 网易云扫码登录窗口。
/// </summary>
public partial class QrCodeLoginDialog : Window
{
private QrCodeLoginViewModel? _viewModel;
/// <summary>
/// 初始化登录窗口。
/// </summary>
public QrCodeLoginDialog()
{
InitializeComponent();
}
/// <summary>
/// 使用指定登录状态创建窗口。
/// </summary>
public QrCodeLoginDialog(QrCodeLoginViewModel viewModel) : this()
{
_viewModel = viewModel;
@@ -77,7 +77,6 @@
MinWidth="108" />
<Button Content="{Binding DecryptClear}"
Command="{Binding ClearFilesCommand}"
IsEnabled="{Binding CanClear}"
MinWidth="88" />
</StackPanel>
@@ -2,8 +2,14 @@ using Avalonia.Controls;
namespace ZonyLrcTools.Desktop.Views.Pages;
/// <summary>
/// 音乐解密页面。
/// </summary>
public partial class DecryptPage : UserControl
{
/// <summary>
/// 初始化音乐解密页面。
/// </summary>
public DecryptPage()
{
InitializeComponent();
@@ -36,6 +36,7 @@
<ComboBox Grid.Column="1"
ItemsSource="{Binding ScannerNames}"
SelectedIndex="{Binding SelectedScannerIndex}"
IsEnabled="{Binding CanEditInputs}"
MinWidth="200"
HorizontalAlignment="Left"
Margin="16,0" />
@@ -97,6 +98,7 @@
FontWeight="Medium" />
<TextBox Grid.Column="1"
Text="{Binding SongListIds}"
IsEnabled="{Binding CanEditInputs}"
Watermark="{Binding LyricsSongListWatermark}"
Margin="16,0" />
<Button Grid.Column="2"
@@ -114,8 +116,7 @@
MinWidth="88" />
</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">
<PathIcon Grid.Column="0"
Data="{StaticResource AccountIcon}"
@@ -18,6 +18,7 @@
<PackageReference Include="Avalonia.Fonts.Inter" />
<PackageReference Include="Avalonia.Controls.DataGrid" />
<PackageReference Include="Avalonia.Diagnostics" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="Tmds.DBus.Protocol" />
<!-- MVVM -->
<PackageReference Include="CommunityToolkit.Mvvm" />
<!-- DI & Hosting -->
@@ -30,29 +31,12 @@
<PackageReference Include="System.Text.Encoding.CodePages" />
<!-- Localization -->
<PackageReference Include="Microsoft.Extensions.Localization" />
<!-- QR code rendering for the NetEase QR login dialog -->
<!-- 网易云扫码登录所需的二维码生成器 -->
<PackageReference Include="QRCoder" />
</ItemGroup>
<!--
Trimming is ON by default for RID-specific publishes, taking the self-contained win-x64
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.
-->
<!-- 指定运行平台时默认裁剪,可通过 -p:PublishTrimmed=false 关闭。
反射注入、序列化和无障碍访问所需程序集由 ILLink.Descriptors.xml 保留。 -->
<PropertyGroup Condition="'$(RuntimeIdentifier)' != '' AND '$(PublishTrimmed)' == ''">
<PublishTrimmed>true</PublishTrimmed>
</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 Microsoft.Extensions.DependencyInjection;
using Shouldly;
@@ -7,16 +8,31 @@ using ZonyLrcTools.Common.MusicDecryption;
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
{
/// <summary>
/// 使用真实 NCM 样本验证解密。
/// </summary>
public class NcmMusicDecryptorTests : TestBase
{
/// <summary>
/// 每次使用独立目录,避免历史输出影响解密结果。
/// </summary>
[Fact]
public async Task ConvertMusicAsync_Test()
public async Task ConvertMusicAsync_DecryptsNcmAsync()
{
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
var ncmFilePath = Path.Combine(Directory.GetCurrentDirectory(), "MusicFiles", "Loren Gray - Queen.ncm");
var directory = Directory.CreateTempSubdirectory("zony-ncm-tests-").FullName;
try
{
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
var ncmFilePath = Path.Combine(directory, "Loren Gray - Queen.ncm");
File.Copy(Path.Combine(AppContext.BaseDirectory, "MusicFiles", "Loren Gray - Queen.ncm"), ncmFilePath);
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
result.IsSuccess.ShouldBeTrue();
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
}
finally
{
Directory.Delete(directory, recursive: true);
}
}
}
}
@@ -0,0 +1,59 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using ZonyLrcTools.Common.Infrastructure.Network;
namespace ZonyLrcTools.Tests.Infrastructure.Network;
/// <summary>
/// 验证等待服务器响应时可以取消请求。
/// </summary>
public class WarpHttpCancellationTests
{
/// <summary>
/// 服务端未响应时,取消操作应及时结束请求。
/// </summary>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task CancelsPendingRequestAsync(bool isPost)
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var endpoint = (IPEndPoint)listener.LocalEndpoint;
var url = $"http://127.0.0.1:{endpoint.Port}/";
using var cancellation = new CancellationTokenSource();
var client = new DefaultWarpHttpClient(new LocalClientFactory());
var request = SendRequestAsync(client, url, isPost, cancellation.Token);
using var connection = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5));
cancellation.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => request.WaitAsync(TimeSpan.FromSeconds(5)));
}
private static async Task SendRequestAsync(IWarpHttpClient client, string url, bool isPost,
CancellationToken cancellationToken = default)
{
if (isPost)
{
using var response = await client.PostReturnHttpResponseAsync(url, cancellationToken: cancellationToken);
}
else
{
await client.GetAsync(url, cancellationToken: cancellationToken);
}
}
private sealed class LocalClientFactory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
return new HttpClient(new SocketsHttpHandler { UseProxy = false });
}
}
}
@@ -0,0 +1,62 @@
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using ZonyLrcTools.Common.MusicScanner;
namespace ZonyLrcTools.Tests.MusicScanner;
/// <summary>
/// CSV 换行符与取消行为的回归测试。
/// </summary>
public sealed class CsvNewlineRegressionTests
{
/// <summary>
/// 各平台导出的 CSV 均可读取并去除字段两端空白。
/// </summary>
[Theory]
[InlineData("\n")]
[InlineData("\r\n")]
[InlineData("\r")]
public async Task Scan_AcceptsPlatformNewlinesAsync(string newline)
{
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, "songs.csv");
try
{
await File.WriteAllTextAsync(path,
$"Name,Artist{newline} Song One , Artist One {newline}{newline}Song Two,Artist Two{newline}",
new UTF8Encoding(true));
var scanner = new CsvFileMusicScanner();
var songs = await scanner.GetMusicInfoFromCsvFileAsync(path, directory, "{Artist} - {Name}.lrc");
Assert.Equal(2, songs.Count);
Assert.Equal("Song One", songs[0].Name);
Assert.Equal("Artist One", songs[0].Artist);
Assert.Equal(Path.Combine(directory, "Artist Two - Song Two.lrc"), songs[1].FilePath);
}
finally
{
Directory.Delete(directory, true);
}
}
/// <summary>
/// 已取消的扫描不再访问文件。
/// </summary>
[Fact]
public async Task Scan_PreCanceledDoesNotReadFileAsync()
{
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
var scanner = new CsvFileMusicScanner();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => scanner.GetMusicInfoFromCsvFileAsync(
Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"), "missing.csv"),
Path.GetTempPath(), "{Name}.lrc", cancellation.Token));
}
}
@@ -0,0 +1,246 @@
#nullable enable
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Network;
using ZonyLrcTools.Common.MusicScanner;
namespace ZonyLrcTools.Tests.MusicScanner;
/// <summary>
/// 网易云登录状态、并发与 HTTP 错误的回归测试。
/// </summary>
public sealed class NetEaseSessionRegressionTests
{
/// <summary>
/// 登录成功回调只能在 Cookie 保存后发出。
/// </summary>
[Fact]
public async Task Login_SuccessCallbackSeesCommittedSessionAsync()
{
using var handler = new TestHandler((request, _) => Task.FromResult(
IsKeyRequest(request) ? KeyResponse() : SuccessResponse()));
var scanner = CreateScanner(handler);
var observedLogin = false;
var success = await scanner.LoginAsync(_ => { }, state =>
{
if (state == NetEaseLoginState.Succeeded)
{
observedLogin = scanner.IsLoggedIn && scanner.CsrfToken == "csrf-value";
}
});
Assert.True(success);
Assert.True(observedLogin);
Assert.Contains("MUSIC_U=session-value", scanner.Cookie);
}
/// <summary>
/// 并发登录复用已经建立的会话,不生成互相干扰的二维码。
/// </summary>
[Fact]
public async Task Login_ConcurrentRequestsUseOneQrSessionAsync()
{
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var keyRequests = 0;
using var handler = new TestHandler(async (request, cancellationToken) =>
{
if (IsKeyRequest(request))
{
Interlocked.Increment(ref keyRequests);
await releaseKey.Task.WaitAsync(cancellationToken);
return KeyResponse();
}
return SuccessResponse();
});
var scanner = CreateScanner(handler);
var first = scanner.LoginAsync(_ => { });
var second = scanner.LoginAsync(_ => { });
releaseKey.SetResult();
var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(5));
Assert.All(results, result => Assert.True(result));
Assert.Equal(1, keyRequests);
Assert.True(scanner.IsLoggedIn);
}
/// <summary>
/// 清除登录后,迟到的扫码结果不能恢复已退出的会话。
/// </summary>
[Fact]
public async Task Login_ClearStateRejectsPendingResultAsync()
{
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var handler = new TestHandler(async (request, cancellationToken) =>
{
if (IsKeyRequest(request))
{
await releaseKey.Task.WaitAsync(cancellationToken);
return KeyResponse();
}
return SuccessResponse();
});
var scanner = CreateScanner(handler);
var login = scanner.LoginAsync(_ => { });
scanner.ClearLoginState();
releaseKey.SetResult();
var success = await login.WaitAsync(TimeSpan.FromSeconds(5));
Assert.False(success);
Assert.False(scanner.IsLoggedIn);
Assert.Empty(scanner.CsrfToken);
}
/// <summary>
/// 恢复的会话不能被旧扫码请求覆盖。
/// </summary>
[Fact]
public async Task Login_RestoreStateRejectsPendingResultAsync()
{
var releaseKey = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var handler = new TestHandler(async (request, cancellationToken) =>
{
if (IsKeyRequest(request))
{
await releaseKey.Task.WaitAsync(cancellationToken);
return KeyResponse();
}
return SuccessResponse();
});
var scanner = CreateScanner(handler);
var login = scanner.LoginAsync(_ => { });
scanner.RestoreLoginState("MUSIC_U=restored", "restored-csrf");
releaseKey.SetResult();
await login.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal("MUSIC_U=restored", scanner.Cookie);
Assert.Equal("restored-csrf", scanner.CsrfToken);
}
/// <summary>
/// HTTP 失败不能被响应中的成功业务码掩盖。
/// </summary>
[Fact]
public async Task Login_HttpFailureIsNotSuccessfulAsync()
{
using var handler = new TestHandler((request, _) =>
{
var response = IsKeyRequest(request) ? KeyResponse() : SuccessResponse();
response.StatusCode = HttpStatusCode.ServiceUnavailable;
return Task.FromResult(response);
});
var scanner = CreateScanner(handler);
await Assert.ThrowsAsync<HttpRequestException>(() => scanner.LoginAsync(_ => { }));
Assert.False(scanner.IsLoggedIn);
}
/// <summary>
/// 非扫码状态业务码应失败,而不是永久等待扫码。
/// </summary>
[Theory]
[InlineData("{\"code\":500}")]
[InlineData("{\"code\":803}")]
public async Task Login_InvalidPollResponseFailsAsync(string body)
{
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var handler = new TestHandler((request, _) => Task.FromResult(
IsKeyRequest(request) ? KeyResponse() : JsonResponse(body)));
var scanner = CreateScanner(handler);
await Assert.ThrowsAsync<ErrorCodeException>(() =>
scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token));
Assert.False(scanner.IsLoggedIn);
}
/// <summary>
/// 二维码过期时结束登录并通知调用方。
/// </summary>
[Fact]
public async Task Login_ExpiredQrReturnsFalseAsync()
{
using var handler = new TestHandler((request, _) => Task.FromResult(
IsKeyRequest(request) ? KeyResponse() : JsonResponse("{\"code\":800}")));
var scanner = CreateScanner(handler);
var lastState = NetEaseLoginState.Waiting;
var success = await scanner.LoginAsync(_ => { }, state => lastState = state);
Assert.False(success);
Assert.Equal(NetEaseLoginState.Expired, lastState);
}
/// <summary>
/// 关闭扫码窗口可以取消正在等待的 HTTP 请求。
/// </summary>
[Fact]
public async Task Login_CancellationReachesHttpRequestAsync()
{
using var cancellation = new CancellationTokenSource();
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var handler = new TestHandler(async (_, cancellationToken) =>
{
started.SetResult();
await Task.Delay(Timeout.Infinite, cancellationToken);
return KeyResponse();
});
var scanner = CreateScanner(handler);
var login = scanner.LoginAsync(_ => { }, cancellationToken: cancellation.Token);
await started.Task.WaitAsync(TimeSpan.FromSeconds(5));
cancellation.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => login.WaitAsync(TimeSpan.FromSeconds(5)));
Assert.False(scanner.IsLoggedIn);
}
private static NetEaseMusicSongListMusicScanner CreateScanner(HttpMessageHandler handler)
=> new(new DefaultWarpHttpClient(new TestClientFactory(handler)),
NullLogger<NetEaseMusicSongListMusicScanner>.Instance);
private static bool IsKeyRequest(HttpRequestMessage request)
=> request.RequestUri!.AbsolutePath.EndsWith("/unikey", StringComparison.Ordinal);
private static HttpResponseMessage KeyResponse() => JsonResponse("{\"code\":200,\"unikey\":\"qr-key\"}");
private static HttpResponseMessage SuccessResponse()
{
var response = JsonResponse("{\"code\":803}");
response.Headers.TryAddWithoutValidation("Set-Cookie", new[]
{
"MUSIC_U=session-value; Path=/; Domain=music.163.com; HttpOnly",
"__csrf=csrf-value; Path=/; Domain=music.163.com"
});
return response;
}
private static HttpResponseMessage JsonResponse(string body)
=> new(HttpStatusCode.OK) { Content = new StringContent(body) };
private sealed class TestClientFactory(HttpMessageHandler handler) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => new(handler, disposeHandler: false);
}
private sealed class TestHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> send)
: HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> send(request, cancellationToken);
}
}
@@ -22,6 +22,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\ZonyLrcTools.Cli\ZonyLrcTools.Cli.csproj" />
<ProjectReference Include="..\..\src\ZonyLrcTools.Desktop\ZonyLrcTools.Desktop.csproj" />
</ItemGroup>
<ItemGroup>
+14 -4
View File
@@ -1,7 +1,17 @@
New Features: None
Breaking Changes: None
Enhancement: None
New Features:
- [#172] Complete the Avalonia desktop workflow and add KGG decryption using a matching KuGou database.
Breaking Changes:
- Existing decrypted audio is preserved and reported as an output conflict instead of being overwritten or reported as newly decrypted.
Enhancement:
- Align new C# code with Chinese XML documentation, UTC naming and cancellation-token conventions.
- Preserve user YAML fields/comments and restrict Unix login-session permissions.
- Include third-party notices in distributions and update Tmds.DBus.Protocol to the security-fixed 0.21.3 backport.
Fixed Bugs:
- [#167] Handle macOS code signing issues. (处理 macOS 代码签名问题。)
- [#167] Handle macOS code signing issues. (处理 macOS 代码签名问题。)
- [#172] Correct KGG/KGM detection, QMC2 map decoding, unpadded ekey decoding and concurrent output handling.
- [#172] Keep decrypted key databases in memory; prevent canceled downloads from publishing partial files.
- [#172] Fix QR login races, stale scan results, desktop task threading and trimmed session serialization.