diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index e7555de..fec8070 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -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:
diff --git a/Directory.Packages.props b/Directory.Packages.props
index 60bea96..4bc83e7 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -51,6 +51,8 @@
+
+
diff --git a/README.md b/README.md
index 8cebfcb..93c1611 100644
--- a/README.md
+++ b/README.md
@@ -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)
diff --git a/docs/en_US.md b/docs/en_US.md
index 50f69f8..e8d9a5d 100644
--- a/docs/en_US.md
+++ b/docs/en_US.md
@@ -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)
diff --git a/docs/zh_CN.md b/docs/zh_CN.md
index 8059136..1f1b00c 100644
--- a/docs/zh_CN.md
+++ b/docs/zh_CN.md
@@ -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)
diff --git a/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs b/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs
index a1a66ae..0482063 100644
--- a/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs
+++ b/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs
@@ -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 () =>
{
diff --git a/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs b/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs
index 49b49bd..eff0ba9 100644
--- a/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs
+++ b/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs
@@ -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;
+///
public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
{
private readonly IEnumerable _albumProviders;
+ ///
public IEnumerable AvailableProviders => new Lazy>(() =>
{
return _albumProviders.Where(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
@@ -18,6 +19,9 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
private readonly IWarpLogger _logger;
+ ///
+ /// 创建专辑封面下载器。
+ ///
public AlbumDownloader(IEnumerable albumProviders,
IWarpLogger logger)
{
@@ -25,39 +29,20 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
_logger = logger;
}
+ ///
public async Task DownloadAsync(List needDownloadMusicInfos,
int parallelCount = 2,
Func? 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)}。");
}
diff --git a/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs b/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs
index 3cafb3a..5d93ad9 100644
--- a/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs
+++ b/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs
@@ -1,5 +1,8 @@
namespace ZonyLrcTools.Common.Album;
+///
+/// 下载歌曲对应的专辑封面。
+///
public interface IAlbumDownloader
{
///
@@ -14,5 +17,8 @@ public interface IAlbumDownloader
Func? callback = null,
CancellationToken cancellationToken = default);
+ ///
+ /// 可用的专辑封面来源。
+ ///
IEnumerable AvailableProviders { get; }
}
diff --git a/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs b/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs
index fd852ed..37562ed 100644
--- a/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs
+++ b/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs
@@ -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
/// 异常实例,可为空。
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();
}
///
- /// 使用 级别打印错误日志,并记录异常堆栈。
- ///
- /// 这个方法只负责记录,不会抛出异常。调用点全部位于 catch 块内,
- /// 若在此处重新抛出,异常会穿透调用方的 catch 并终止整批任务
- /// (例如一首歌的编码配置有误会导致整批歌词下载中断)。
- /// 需要向上传播错误时,请由调用方显式决定,而不是让日志方法代劳。
- ///
+ /// 记录错误码与异常,不重新抛出业务异常。
///
/// 日志记录器的实例。
/// 错误码异常实例。
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();
}
///
diff --git a/src/ZonyLrcTools.Common/Infrastructure/Network/DefaultWarpHttpClient.cs b/src/ZonyLrcTools.Common/Infrastructure/Network/DefaultWarpHttpClient.cs
index 73ea369..8bc3a4f 100644
--- a/src/ZonyLrcTools.Common/Infrastructure/Network/DefaultWarpHttpClient.cs
+++ b/src/ZonyLrcTools.Common/Infrastructure/Network/DefaultWarpHttpClient.cs
@@ -18,59 +18,73 @@ namespace ZonyLrcTools.Common.Infrastructure.Network
_httpClientFactory = httpClientFactory;
}
+ ///
public async ValueTask PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null)
+ Action? 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);
}
+ ///
public async ValueTask PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null)
+ Action? 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(parameters, responseString);
}
+ ///
public async ValueTask PostReturnHttpResponseAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null)
+ Action? 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);
}
+ ///
public async ValueTask GetAsync(string url,
object? parameters = null,
- Action? requestOption = null)
+ Action? 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);
}
+ ///
public async ValueTask GetAsync(string url,
object? parameters = null,
- Action? requestOption = null)
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default)
{
- var responseString = await GetAsync(url, parameters, requestOption);
+ var responseString = await GetAsync(url, parameters, requestOption, cancellationToken: cancellationToken);
return ConvertHttpResponseToObject(parameters, responseString);
}
diff --git a/src/ZonyLrcTools.Common/Infrastructure/Network/IWarpHttpClient.cs b/src/ZonyLrcTools.Common/Infrastructure/Network/IWarpHttpClient.cs
index 7d193cb..7f01554 100644
--- a/src/ZonyLrcTools.Common/Infrastructure/Network/IWarpHttpClient.cs
+++ b/src/ZonyLrcTools.Common/Infrastructure/Network/IWarpHttpClient.cs
@@ -12,11 +12,13 @@
/// 请求的参数。
/// 是否以 QueryString 形式携带参数。
/// 请求时的配置动作。
+ /// 取消令牌。
/// 服务端的响应结果。
ValueTask PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null);
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default);
///
/// 根据指定的配置执行 POST 请求,并将结果反序列化为 对象。
@@ -25,17 +27,28 @@
/// 请求的参数。
/// 是否以 QueryString 形式携带参数。
/// 请求时的配置动作。
+ /// 取消令牌。
/// 需要将响应结果反序列化的目标类型。
/// 服务端的响应结果。
ValueTask PostAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null);
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default);
+ ///
+ /// 执行 POST 请求,由调用方释放返回的响应。
+ ///
+ /// 请求地址。
+ /// 请求参数。
+ /// 是否将参数编码为查询字符串。
+ /// 请求配置动作。
+ /// 取消令牌。
ValueTask PostReturnHttpResponseAsync(string url,
object? parameters = null,
bool isQueryStringParam = false,
- Action? requestOption = null);
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default);
///
/// 根据指定的配置执行 GET 请求,并以 作为返回值。
@@ -43,10 +56,12 @@
/// 请求的 URL 地址。
/// 请求的参数。
/// 请求时的配置动作。
+ /// 取消令牌。
/// 服务端的响应结果。
ValueTask GetAsync(string url,
object? parameters = null,
- Action? requestOption = null);
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default);
///
/// 根据指定的配置执行 GET 请求,并将结果反序列化为 对象。
@@ -54,11 +69,13 @@
/// 请求的 URL 地址。
/// 请求的参数。
/// 请求时的配置动作。
+ /// 取消令牌。
/// 需要将响应结果反序列化的目标类型。
/// 服务端的响应结果。
ValueTask GetAsync(
string url,
object? parameters = null,
- Action? requestOption = null);
+ Action? requestOption = null,
+ CancellationToken cancellationToken = default);
}
}
\ No newline at end of file
diff --git a/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs b/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs
index b08637d..e05903a 100644
--- a/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs
+++ b/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs
@@ -42,8 +42,14 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
Func? 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 DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info)
+ private async Task 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 musicInfos)
+ private async Task LogFailedSongFilesInfoAsync(string outFilePath, IEnumerable 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);
}
}
\ No newline at end of file
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs
index 95c7f53..34cb80e 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs
@@ -11,12 +11,16 @@ namespace ZonyLrcTools.Common.MusicDecryption
private readonly IWarpLogger _warpLogger;
private readonly IKugouKeyProvider? _kugouKeyProvider;
+ ///
+ /// 创建音乐解密器。
+ ///
public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null)
{
_warpLogger = warpLogger;
_kugouKeyProvider = kugouKeyProvider;
}
+ ///
public async Task 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);
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs b/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs
index bd9d9e5..4d4e119 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs
@@ -46,7 +46,7 @@ namespace ZonyLrcTools.Common.MusicDecryption
void Invalidate();
///
- /// 判断文件是否是 .kgg(按魔数,不看扩展名)。
+ /// 按魔数和加密版本判断文件是否为 KGG,不看扩展名。
///
bool IsKggFile(string filePath);
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs
index dd35fc6..2ba896e 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs
@@ -15,7 +15,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
///
/// V2 前缀,解码后即 "QQMusic EncV2,Key:"。
///
- 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
///
/// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。
- ///
- /// Base64 段里被忽略的非法字符数量。Base64 解码本身是宽容的(会静默映射成 0),
- /// 这里把它统计出来,让上层能把「密钥损坏」和「没有密钥」区分开。
- ///
///
+ /// 数据库中的密钥。
+ /// Base64 中的非法字符数量,空白不计入。
/// 原始密钥;解码失败时为空数组。
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();
-
- ///
- /// 宽容的 Base64 解码,兼容 URL-safe 变体与不规范的长度。
- /// 输入中不属于 Base64 的字符数量(空白字符会被跳过,不计入)。
- ///
- 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 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 : [];
}
}
}
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs
index 08586be..ecade82 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs
@@ -29,16 +29,17 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private static byte[] Magic => KugouEkeyDatabase.KggMagic;
///
- /// 判断文件是否真的是 .kgg 格式(按魔数而非扩展名)。
+ /// 按魔数和加密版本判断是否为 KGG,避免误判共用魔数的旧版 KGM。
///
public static bool IsKggFile(string filePath)
{
try
{
using var stream = File.OpenRead(filePath);
- Span buffer = stackalloc byte[16];
- return stream.ReadAtLeast(buffer, 16, throwOnEndOfStream: false) == 16
- && buffer.SequenceEqual(Magic);
+ Span 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
/// 解密结果;失败时带有可读的错误说明。
public static async Task 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;
}
///
@@ -221,7 +242,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
return keys.TryGetValue(audioHash, out var ekey) ? ekey : null;
}
- private static string DetectExtension(ReadOnlySpan magic)
+ private static string? DetectExtension(ReadOnlySpan 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;
}
}
}
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs
index b2d48e6..034f80e 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs
@@ -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
///
/// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。
///
- /// 数据库按 4KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥 + 页号派生。
+ /// 数据库按 1KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥和页号派生。
/// 解密后可以读到 ShareFileItems 表里的 ekey,那是 .kgg 文件真正用的解密密钥。
///
///
@@ -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);
- }
-
- ///
- /// 清掉上一次运行留下的明文临时库(正常退出时 finally 已经删过,这里只兜异常退出的底)。
- ///
- 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
- {
- // 删不掉不影响结果,下次进入时还会再清一次。
- }
- }
-
///
/// 把整个加密数据库解密成明文的 SQLite 字节流。
///
@@ -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];
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs
index 5308d79..d412c6b 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs
@@ -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
{
///
@@ -70,6 +68,9 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
private readonly byte[] _key;
+ ///
+ /// 根据短密钥生成查找表。
+ ///
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));
}
}
+ ///
public override byte Decrypt(byte cipher, long offset)
{
var index = offset <= MapIndexBoundary ? offset : offset % MapIndexBoundary;
return (byte)(cipher ^ _key[index % MapKeySize]);
}
+ ///
public override void Decrypt(Span 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;
+ ///
+ /// 根据长密钥生成密钥流。
+ ///
public Qmc2Rc4Cipher(byte[] key)
{
_key = key;
@@ -126,6 +132,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
DeriveKeyStream();
}
+ ///
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]);
}
+ ///
public override void Decrypt(Span data, long offset)
{
// 首段与常规段的算法不同,先按边界切一刀。
@@ -182,7 +190,7 @@ namespace ZonyLrcTools.Common.MusicDecryption.Kugou
///
private static uint ComputeKeyHash(ReadOnlySpan key)
{
- uint hash = 1;
+ var hash = 1u;
foreach (var item in key)
{
if (item == 0)
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs
index 4535531..0cd8627 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs
@@ -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];
diff --git a/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs b/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs
index ff5a56f..4ae7850 100644
--- a/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs
+++ b/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs
@@ -16,10 +16,10 @@ namespace ZonyLrcTools.Common.MusicDecryption
private string? _manualPath;
private string? _databasePath;
- private string? _loadedPath;
private string? _failureReason;
private bool _isLoaded;
+ ///
public string? DatabasePath
{
get
@@ -32,12 +32,14 @@ namespace ZonyLrcTools.Common.MusicDecryption
}
}
+ ///
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;
+ ///
+ public bool IsKggFile(string filePath) => Kugou.KggMusicDecryptor.IsKggFile(filePath);
+ ///
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
}
}
+ ///
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;
diff --git a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs
index 5375a27..2ea8235 100644
--- a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs
+++ b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs
@@ -15,19 +15,19 @@ public class CsvFileMusicScanner : ITransientDependency
/// CSV 文件的路径。
/// 歌词文件的输出目录。
/// 输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。
+ /// 取消令牌。
public async Task> 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();
}
diff --git a/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs b/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs
index ca0ec4e..282635c 100644
--- a/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs
+++ b/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs
@@ -20,16 +20,55 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
private readonly IWarpHttpClient _warpHttpClient;
private readonly ILogger _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;
///
/// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。
///
- public string Cookie { get; set; } = string.Empty;
+ public string Cookie
+ {
+ get
+ {
+ lock (_loginStateLock)
+ {
+ return _cookie;
+ }
+ }
+ set
+ {
+ lock (_loginStateLock)
+ {
+ _cookie = value ?? string.Empty;
+ _loginStateVersion++;
+ }
+ }
+ }
///
/// 登录后的 CSRF Token,通常与 一起持久化。
///
- public string CsrfToken { get; set; } = string.Empty;
+ public string CsrfToken
+ {
+ get
+ {
+ lock (_loginStateLock)
+ {
+ return _csrfToken;
+ }
+ }
+ set
+ {
+ lock (_loginStateLock)
+ {
+ _csrfToken = value ?? string.Empty;
+ _loginStateVersion++;
+ }
+ }
+ }
///
/// 当前是否已经持有登录态。
@@ -51,8 +90,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
///
public void ClearLoginState()
{
- Cookie = string.Empty;
- CsrfToken = string.Empty;
+ RestoreLoginState(string.Empty, string.Empty);
}
///
@@ -62,8 +100,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
/// 与 一起保存的 CSRF Token。
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++;
+ }
}
///
@@ -78,17 +120,44 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action? 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();
+ }
}
///
@@ -111,33 +180,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
Action? 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> GetMusicInfoBySongIdAsync(string songId)
+ var session = GetLoginState();
+
+ async Task> GetMusicInfoBySongIdAsync(string songId, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16);
var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey);
var response = await _warpHttpClient.PostAsync(
- $"{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();
- 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);
+ }
+ }
+
///
/// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。
///
@@ -204,24 +275,27 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency
///
/// 登录状态变化回调。
/// 取消令牌。
- private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync(
+ private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViaQrCodeAsync(
Action? onQrCodeReady,
Action? 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();
- if (string.IsNullOrEmpty(uniKey)) return (null, null);
+ }, cancellationToken: cancellationToken);
+ var keyResponseJson = JObject.Parse(await keyResponse.Content.ReadAsStringAsync(cancellationToken));
+ var uniKey = keyResponseJson.Value("unikey");
+ if (keyResponseJson.Value("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();
@@ -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
///
/// 需要请求的网易云音乐 API 地址。
/// API 请求参数。
+ /// 取消令牌。
///
/// 正常情况下会返回一个 对象。
///
- private async Task PostAsync(string url, object @params)
+ private async Task 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;
+ }
}
}
diff --git a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj
index 84a6d93..e6826c3 100644
--- a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj
+++ b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj
@@ -27,4 +27,16 @@
+
+
+ PreserveNewest
+ PreserveNewest
+ true
+
+
+
+
+
+
+
diff --git a/src/ZonyLrcTools.Desktop/App.axaml b/src/ZonyLrcTools.Desktop/App.axaml
index 115fcdb..acaa972 100644
--- a/src/ZonyLrcTools.Desktop/App.axaml
+++ b/src/ZonyLrcTools.Desktop/App.axaml
@@ -7,11 +7,7 @@
-
+
-
+