diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index e3dcd81..fec8070 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -43,6 +43,59 @@ jobs: outputs: version: ${{ steps.date.outputs.date }} + # 桌面端构建(目前只发布 Windows,见 README 的说明) + build-desktop: + runs-on: windows-latest + steps: + - name: Get build version + id: date + run: echo "date=$(Get-Date -Format 'yyyyMMdd')${{github.run_number}}" >> $env:GITHUB_OUTPUT + shell: pwsh + - name: Checkout Code + uses: actions/checkout@v4 + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 10.0.x + - name: Publish Desktop (win-x64) + working-directory: ./src/ZonyLrcTools.Desktop + run: | + dotnet publish -r win-x64 -c Release -p:PublishSingleFile=true -p:UseAppHost=true -p:DebugType=none --self-contained true + if ($LASTEXITCODE -ne 0) { throw '桌面端发布失败' } + shell: pwsh + # 单文件发布仍需附带 SQLite 原生库、配置模板及第三方许可声明。 + - name: Verify Desktop publish output + working-directory: ./src/ZonyLrcTools.Desktop + run: | + $publish = './bin/Release/net10.0/win-x64/publish' + $exe = Join-Path $publish 'ZonyLrcTools.Desktop.exe' + $sqlite = Join-Path $publish 'e_sqlite3.dll' + if (-not (Test-Path $exe)) { throw "缺少主程序: $exe" } + if (-not (Test-Path $sqlite)) { throw "缺少 SQLite 原生库: $sqlite(.kgg 解密依赖它)" } + if (-not (Test-Path (Join-Path $publish 'config.yaml'))) { throw '缺少 config.yaml 模板' } + if (-not (Test-Path (Join-Path $publish 'THIRD-PARTY-NOTICES.md'))) { throw '缺少第三方许可声明' } + + $totalMb = [math]::Round(((Get-ChildItem $publish -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1MB), 1) + Write-Host "publish 目录校验通过:$((Get-ChildItem $publish -File).Count) 个文件,共 $totalMb MB" + if ($totalMb -gt 90) { + throw "publish 目录有 $totalMb MB,超过 90 MB 上限;这通常意味着 PublishTrimmed 被关掉了" + } + shell: pwsh + - name: Package Desktop + working-directory: ./src/ZonyLrcTools.Desktop + run: | + New-Item -ItemType Directory -Force -Path ./TempFiles | Out-Null + Compress-Archive -Path ./bin/Release/net10.0/win-x64/publish/* -DestinationPath ./TempFiles/ZonyLrcTools.Desktop_win-x64_${{ steps.date.outputs.date }}.zip -Force + shell: pwsh + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + retention-days: 90 + name: release-files-desktop + path: ./src/ZonyLrcTools.Desktop/TempFiles + outputs: + version: ${{ steps.date.outputs.date }} + # macOS 构建(在 macOS runner 上,支持 ad-hoc 签名) build-macos: runs-on: macos-latest @@ -84,7 +137,7 @@ jobs: # Release Job - 合并所有平台的构建产物 release: if: github.event_name == 'push' - needs: [build-linux-windows, build-macos] + needs: [build-linux-windows, build-macos, build-desktop] runs-on: ubuntu-latest steps: - name: Checkout for release notes @@ -99,6 +152,11 @@ jobs: with: name: release-files-macos path: ./TempFiles + - name: Download Desktop artifacts + uses: actions/download-artifact@v4 + with: + name: release-files-desktop + path: ./TempFiles - name: Upload Release uses: ncipollo/release-action@v1 with: diff --git a/Directory.Packages.props b/Directory.Packages.props index 27e3b3d..4bc83e7 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -41,6 +41,9 @@ + + + @@ -48,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/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md new file mode 100644 index 0000000..ccf052a --- /dev/null +++ b/THIRD-PARTY-NOTICES.md @@ -0,0 +1,45 @@ +# Third-Party Notices + +This project contains code derived from the following MIT-licensed works. +The MIT licence requires the copyright notice and permission notice to be +included in all copies or substantial portions of the software, so they are +reproduced in full below. + +--- + +## kgg-dec — KuGou `.kgg` decryption reference implementation + +Source: + +Used by: `src/ZonyLrcTools.Common/MusicDecryption/Kugou/` +(`TcTea.cs`, `EkeyDecoder.cs`, `Qmc2Cipher.cs`, `KugouEkeyDatabase.cs`, +`KggMusicDecryptor.cs`) + +The C# classes above are a port of the TC-TEA / ekey / QMC2 / KGMusicV3.db +algorithms from that project. They were rewritten for this codebase (different +structure, streaming I/O, cancellation support), but the cryptographic +constants and the database page-decryption scheme originate there. + +``` +MIT License + +Copyright (c) 2024 LSR + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` 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 47a0156..0482063 100644 --- a/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs +++ b/src/ZonyLrcTools.Cli/Commands/SubCommand/UtilityCommand.cs @@ -41,13 +41,15 @@ namespace ZonyLrcTools.Cli.Commands.SubCommand { _logger.LogInformation("开始扫描文件夹,请稍等..."); - var files = (await _fileScanner.ScanAsync(Source, DecryptoFactory.KnownExtensions.Select(x => $"*{x}"))) + var files = (await _fileScanner.ScanAsync(Source, + DecryptoFactory.KnownExtensions.Append(".kgg").Distinct().Select(x => $"*{x}"))) .SelectMany(f => f.FilePaths) .ToList(); _logger.LogInformation($"扫描完成,共 {files.Count} 个文件,准备转换。"); - var wrapTask = new WarpTask(4); + // 等待转换结束后释放并发控制资源。 + using var wrapTask = new WarpTask(4); var tasks = files.Select(path => wrapTask.RunAsync(async () => { _logger.LogInformation($"开始转换文件:{path}"); diff --git a/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs b/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs index 715c2b7..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.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,44 +29,110 @@ 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) { - return; + info.IsSuccessful = false; } - var warpTask = new WarpTask(parallelCount); + cancellationToken.ThrowIfCancellationRequested(); + var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase); + + if (parallelCount <= 0) + { + parallelCount = 1; + } + + using var warpTask = new WarpTask(parallelCount); var warpTaskList = needDownloadMusicInfos.Select(info => warpTask.RunAsync(() => Task.Run(async () => { - _logger.LogSuccessful(info); - try { - var album = await provider.DownloadAsync(info.Name, info.Artist); - var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png"); - if (File.Exists(filePath) || album.Length <= 0) + cancellationToken.ThrowIfCancellationRequested(); + + var filePath = Path.ChangeExtension(info.FilePath, ".png"); + if (File.Exists(filePath)) + { + info.IsSuccessful = true; + return; + } + + if (provider == null) { return; } - await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album); + var album = await provider.DownloadAsync(info.Name, info.Artist); + cancellationToken.ThrowIfCancellationRequested(); + if (album.Length == 0) + { + return; + } + + var temporaryPath = $"{filePath}.{Guid.NewGuid():N}.tmp"; + try + { + await File.WriteAllBytesAsync(temporaryPath, album, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + // 完整写入后再发布,且不覆盖其他任务或用户刚创建的封面。 + try + { + File.Move(temporaryPath, filePath); + } + catch (IOException) when (File.Exists(filePath)) + { + // 目标已由其他任务生成,保留已有封面。 + } + } + finally + { + File.Delete(temporaryPath); + } + + info.IsSuccessful = true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; } catch (ErrorCodeException ex) { _logger.LogWarningInfo(ex); } + catch (Exception ex) + { + await _logger.ErrorAsync("下载专辑图像失败。", ex); + } + finally + { + if (callback != null) + { + try + { + await callback(info); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + await _logger.WarnAsync("处理专辑下载回调失败。", ex); + } + } + } }, cancellationToken), cancellationToken)); await Task.WhenAll(warpTaskList); + cancellationToken.ThrowIfCancellationRequested(); await _logger.InfoAsync($"专辑数据下载完成,成功: {needDownloadMusicInfos.Count(m => m.IsSuccessful)} 失败{needDownloadMusicInfos.Count(m => m.IsSuccessful == false)}。"); } -} \ No newline at end of file +} diff --git a/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs b/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs index 4619c35..5d93ad9 100644 --- a/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs +++ b/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs @@ -1,10 +1,24 @@ -namespace ZonyLrcTools.Common.Album; +namespace ZonyLrcTools.Common.Album; +/// +/// 下载歌曲对应的专辑封面。 +/// public interface IAlbumDownloader { + /// + /// 使用给定的歌曲信息下载专辑图像,并输出到音乐文件同目录。 + /// + /// 需要下载专辑图像的歌曲信息。 + /// 下载线程/并发量。 + /// 单首歌曲处理完成之后的回调方法。 + /// 任务取消标记。 Task DownloadAsync(List needDownloadMusicInfos, int parallelCount = 2, + Func? callback = null, CancellationToken cancellationToken = default); + /// + /// 可用的专辑封面来源。 + /// IEnumerable AvailableProviders { get; } -} \ No newline at end of file +} diff --git a/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs b/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs index c7327df..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,25 +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(); } /// - /// 使用 级别打印错误日志,并记录异常堆栈。 + /// 记录错误码与异常,不重新抛出业务异常。 /// /// 日志记录器的实例。 /// 错误码异常实例。 public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception) { - if (exception.ErrorCode < 50000) - { - throw exception; - } - - var sb = new StringBuilder(); - sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}"); - sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}"); - logger.WarnAsync(sb.ToString()).GetAwaiter().GetResult(); + logger.WarnAsync( + $"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}", + exception).GetAwaiter().GetResult(); } /// 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 17edeba..e05903a 100644 --- a/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs +++ b/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs @@ -1,4 +1,4 @@ -using System.Collections.Immutable; +using System.Collections.Immutable; using System.Text; using Microsoft.Extensions.Options; using ZonyLrcTools.Common.Configuration; @@ -42,85 +42,152 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency Func? callback = null, CancellationToken cancellationToken = default) { - await _logger.InfoAsync("开始下载歌词文件数据..."); + foreach (var info in needDownloadMusicInfos) + { + info.IsSuccessful = false; + info.IsPruneMusic = false; + } + cancellationToken.ThrowIfCancellationRequested(); + var providers = AvailableProviders.ToArray(); if (parallelCount <= 0) { parallelCount = 1; } - var warpTask = new WarpTask(parallelCount); + using var warpTask = new WarpTask(parallelCount); var downloadTasks = needDownloadMusicInfos.Select(info => warpTask.RunAsync(() => Task.Run(async () => { - // Try to download lyrics from all available providers. - foreach (var lyricsProvider in AvailableProviders) + try { - await DownloadAndWriteLyricsAsync(lyricsProvider, info); + var isFinished = false; + var hasProviderError = providers.Length == 0; - if (!info.IsSuccessful) continue; - _logger.LogSuccessful(info); - break; + foreach (var lyricsProvider in providers) + { + cancellationToken.ThrowIfCancellationRequested(); + var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info, cancellationToken); + if (result == LyricsDownloadResult.Success) + { + isFinished = true; + break; + } + + hasProviderError |= result == LyricsDownloadResult.Failed; + } + + cancellationToken.ThrowIfCancellationRequested(); + if (!isFinished) + { + // 只有所有来源均返回空结果时,才按纯音乐处理。 + info.IsSuccessful = !hasProviderError; + info.IsPruneMusic = !hasProviderError; + } + } + finally + { + if (callback != null) + { + try + { + await callback(info); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + await _logger.WarnAsync("处理歌曲下载回调失败。", ex); + } + } } - - if (callback != null) await callback(info); }, cancellationToken), cancellationToken)); await Task.WhenAll(downloadTasks); + cancellationToken.ThrowIfCancellationRequested(); var successfulCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: false }); var skippedCount = needDownloadMusicInfos.Count(m => m is { IsSuccessful: true, IsPruneMusic: true }); var failedCount = needDownloadMusicInfos.Count(m => m.IsSuccessful == false); await _logger.InfoAsync($"歌词数据下载完成,成功: {successfulCount} 跳过(纯音乐): {skippedCount} 失败{failedCount}。"); - await LogFailedSongFilesInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.Now:yyyyMMddHHmmss}.txt"), needDownloadMusicInfos); + await LogFailedSongFilesInfoAsync( + Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.UtcNow:yyyyMMddHHmmss}.txt"), + needDownloadMusicInfos, cancellationToken); } - private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info) + private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info, + CancellationToken cancellationToken = default) { try { + cancellationToken.ThrowIfCancellationRequested(); var lyrics = await provider.DownloadAsync(info.Name, info.Artist); + cancellationToken.ThrowIfCancellationRequested(); + // 空结果只表示当前来源未找到歌词,继续尝试其他来源。 if (lyrics.IsPruneMusic) { - info.IsSuccessful = true; - info.IsPruneMusic = true; - return; + return LyricsDownloadResult.Empty; } - var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, - $"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc"); + // 编码成功后再创建文件,避免配置错误破坏原歌词。 + var content = Utf8ToSelectedEncoding(lyrics); - if (File.Exists(newLyricsFilePath)) + var newLyricsFilePath = Path.ChangeExtension(info.FilePath, ".lrc"); + var temporaryPath = $"{newLyricsFilePath}.{Guid.NewGuid():N}.tmp"; + try { - File.Delete(newLyricsFilePath); + await File.WriteAllBytesAsync(temporaryPath, content, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temporaryPath, newLyricsFilePath, overwrite: true); } - - // Write lyrics to file. - await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write)) + finally { - await using (var binaryWriter = new BinaryWriter(fileStream, Encoding.UTF8)) - { - binaryWriter.Write(Utf8ToSelectedEncoding(lyrics)); - binaryWriter.Flush(); - } + File.Delete(temporaryPath); } info.IsSuccessful = true; + info.IsPruneMusic = false; + return LyricsDownloadResult.Success; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; } catch (ErrorCodeException ex) { - _logger.LogWarningInfo(ex); info.IsSuccessful = false; + info.IsPruneMusic = false; + _logger.LogWarningInfo(ex); + return LyricsDownloadResult.Failed; } catch (Exception ex) { - await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。"); info.IsSuccessful = false; + info.IsPruneMusic = false; + await _logger.WarnAsync("当前歌词来源下载失败,将尝试其他来源。", ex); + return LyricsDownloadResult.Failed; } } + /// + /// 单个歌词来源的处理结果。 + /// + private enum LyricsDownloadResult + { + /// 歌词已写入文件。 + Success, + + /// 该来源没有返回歌词(既可能是没有收录,也可能是纯音乐)。 + Empty, + + /// 该来源处理过程中出错。 + Failed + } + // Convert UTF-8 to selected encoding. private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics) { @@ -140,7 +207,8 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency return Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(_options.Provider.Lyric.Config.FileEncoding), lyrics.GetUtf8Bytes()); } - private async Task LogFailedSongFilesInfo(string outFilePath, IEnumerable musicInfos) + private async Task LogFailedSongFilesInfoAsync(string outFilePath, IEnumerable musicInfos, + CancellationToken cancellationToken = default) { var failedSongList = musicInfos.Where(m => m.IsSuccessful == false).ToImmutableList(); if (!failedSongList.Any()) @@ -156,6 +224,6 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency failedSongFiles.AppendLine($"{failedSongFile.Name},{failedSongFile.Artist},{failedSongFile.FilePath}"); } - await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString()); + await File.WriteAllTextAsync(outFilePath, failedSongFiles.ToString(), cancellationToken); } } \ No newline at end of file diff --git a/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs index eec0716..34cb80e 100644 --- a/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs +++ b/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs @@ -1,6 +1,7 @@ -using MusicDecrypto.Library; +using MusicDecrypto.Library; using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.Logging; +using ZonyLrcTools.Common.MusicDecryption.Kugou; namespace ZonyLrcTools.Common.MusicDecryption { @@ -8,37 +9,90 @@ namespace ZonyLrcTools.Common.MusicDecryption public class DefaultMusicDecryptor : IMusicDecryptor, ITransientDependency { private readonly IWarpLogger _warpLogger; + private readonly IKugouKeyProvider? _kugouKeyProvider; - public DefaultMusicDecryptor(IWarpLogger warpLogger) + /// + /// 创建音乐解密器。 + /// + public DefaultMusicDecryptor(IWarpLogger warpLogger, IKugouKeyProvider? kugouKeyProvider = null) { _warpLogger = warpLogger; + _kugouKeyProvider = kugouKeyProvider; } - public async Task ConvertMusicAsync(string filePath) + /// + public async Task ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default) { try { + cancellationToken.ThrowIfCancellationRequested(); + + // .kgg 的密钥存放在酷狗客户端数据库里,MusicDecrypto 覆盖不到这条链路。 + if (KggMusicDecryptor.IsKggFile(filePath)) + { + return await KggMusicDecryptor.ConvertAsync(filePath, _kugouKeyProvider, cancellationToken); + } + await using var buffer = new MarshalMemoryStream(); await using var file = new FileStream(filePath, FileMode.Open, FileAccess.Read); buffer.SetLengthWithPadding(file.Length); - await file.CopyToAsync(buffer); + await file.CopyToAsync(buffer, cancellationToken); using var decrypto = DecryptoFactory.Create(buffer, Path.GetFileName(filePath), message => { }); var outFileName = (await decrypto.DecryptAsync()).NewName; + cancellationToken.ThrowIfCancellationRequested(); var outFilePath = Path.Combine(Path.GetDirectoryName(filePath)!, outFileName); - if (!File.Exists(outFilePath)) + if (File.Exists(outFilePath)) { - await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None); - await buffer.CopyToAsync(outFile); + return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outFilePath}"); + } + + var tempPath = outFilePath + $".{Guid.NewGuid():N}.part"; + var ownsTempFile = false; + try + { + await using (var outFile = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + ownsTempFile = true; + buffer.Position = 0; + await buffer.CopyToAsync(outFile, cancellationToken); + await outFile.FlushAsync(cancellationToken); + } + + cancellationToken.ThrowIfCancellationRequested(); + File.Move(tempPath, outFilePath); + } + finally + { + if (ownsTempFile) + { + try + { + File.Delete(tempPath); + } + catch (IOException) + { + // 保留原始转换结果或异常。 + } + catch (UnauthorizedAccessException) + { + // 保留原始转换结果或异常。 + } + } } return DecryptionResult.Success(outFilePath); } + catch (OperationCanceledException) + { + // 用户主动取消,交给调用方区分处理。 + throw; + } catch (Exception e) { return DecryptionResult.Failed(e.Message); } } } -} \ No newline at end of file +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs b/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs new file mode 100644 index 0000000..4d4e119 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs @@ -0,0 +1,63 @@ +namespace ZonyLrcTools.Common.MusicDecryption +{ + /// + /// 酷狗数据库的探测结果。 + /// + /// 数据库是否可用(文件存在且能解出密钥)。 + /// 实际生效的数据库路径;不可用时为 null。 + /// 能从数据库里读出的密钥条目数量。 + /// 给用户看的说明文字。 + public sealed record KugouDatabaseInfo(bool IsAvailable, string? DatabasePath, int KeyCount, string Message); + + /// + /// .kgg 解密前置条件的查询入口。 + /// + /// .kgg 的音频用 QMC2 加密,而每个文件自己的 ekey 不在文件里, + /// 需要从酷狗客户端本地的 KGMusicV3.db 里按音频哈希查出来。 + /// GUI 需要提前知道“库在不在、这个文件有没有密钥”,才能在用户点开始之前给出提示。 + /// + /// + public interface IKugouKeyProvider + { + /// + /// 当前生效的数据库路径;没有可用数据库时为 null。 + /// + string? DatabasePath { get; } + + /// + /// 手动指定数据库路径;null 或空字符串表示恢复自动探测。 + /// + void SetDatabasePath(string? path); + + /// + /// 探测当前可用的数据库。 + /// + /// 实现应当缓存结果:整库解密需要几十毫秒,而查一次密钥只要零点几毫秒。 + /// + /// + KugouDatabaseInfo Probe(); + + /// + /// 作废缓存,让下一次访问重新读取数据库。 + /// + /// 用户在酷狗里新下载了歌曲、或换了一份数据库文件之后需要调用,否则读到的还是旧快照。 + /// + /// + void Invalidate(); + + /// + /// 按魔数和加密版本判断文件是否为 KGG,不看扩展名。 + /// + bool IsKggFile(string filePath); + + /// + /// 读出 .kgg 文件头里的音频哈希;不是合法的 .kgg 时返回 null。 + /// + string? ReadAudioHash(string filePath); + + /// + /// 取出该音频哈希对应的 ekey;没有时返回 null。 + /// + string? FindKey(string audioHash); + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs index b0c146d..1ef208d 100644 --- a/src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs +++ b/src/ZonyLrcTools.Common/MusicDecryption/IMusicDecryptor.cs @@ -1,4 +1,4 @@ -using MusicDecrypto.Library; +using MusicDecrypto.Library; namespace ZonyLrcTools.Common.MusicDecryption { @@ -14,7 +14,8 @@ namespace ZonyLrcTools.Common.MusicDecryption /// 将加密数据歌曲文件转换为可识别的歌曲格式。 /// /// 加密歌曲文件的路径。 + /// 取消令牌,用于中断大文件的转换。 /// 转换结果。 - Task ConvertMusicAsync(string filePath); + Task ConvertMusicAsync(string filePath, CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs new file mode 100644 index 0000000..2ba896e --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs @@ -0,0 +1,147 @@ +// Ported from the MIT-licensed reference implementation: +// https://github.com/lizipeng0013/kgg-dec.mirror +// Copyright (c) 2024 LSR +// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. + +using System.Text; + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// 酷狗/QQ 音乐的 ekey 解码器。 + /// + internal static class EkeyDecoder + { + /// + /// V2 前缀,解码后即 "QQMusic EncV2,Key:"。 + /// + private const string V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6"; + + private static readonly byte[] V2Key1 = + [ + 0x33, 0x38, 0x36, 0x5A, 0x4A, 0x59, 0x21, 0x40, 0x23, 0x2A, 0x24, 0x25, 0x5E, 0x26, 0x29, 0x28 + ]; + + private static readonly byte[] V2Key2 = + [ + 0x2A, 0x2A, 0x23, 0x21, 0x28, 0x23, 0x24, 0x25, 0x26, 0x5E, 0x61, 0x31, 0x63, 0x5A, 0x2C, 0x54 + ]; + + /// + /// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。 + /// + /// 原始密钥;解码失败时为空数组。 + public static byte[] Decode(string ekey) => Decode(ekey, out _); + + /// + /// 将数据库中的 ekey 字符串还原为 QMC2 使用的原始密钥。 + /// + /// 数据库中的密钥。 + /// Base64 中的非法字符数量,空白不计入。 + /// 原始密钥;解码失败时为空数组。 + public static byte[] Decode(string ekey, out int invalidCharCount) + { + invalidCharCount = 0; + if (string.IsNullOrEmpty(ekey)) + { + return []; + } + + if (ekey.StartsWith(V2Prefix, StringComparison.Ordinal)) + { + var raw = Encoding.Latin1.GetBytes(ekey[V2Prefix.Length..]); + var inner = TcTea.CbcDecrypt(raw, TcTea.ToRoundKeys(V2Key1)); + if (inner.Length == 0) + { + return []; + } + + inner = TcTea.CbcDecrypt(inner, TcTea.ToRoundKeys(V2Key2)); + if (inner.Length == 0) + { + return []; + } + + return DecodeV1(Encoding.Latin1.GetString(inner), out invalidCharCount); + } + + return DecodeV1(ekey, out invalidCharCount); + } + + private static byte[] DecodeV1(string ekey, out int invalidCharCount) + { + var result = Base64Decode(ekey, out invalidCharCount); + if (result.Length < 8) + { + return []; + } + + var teaKey = new[] + { + 0x69005600u | ((uint)result[0] << 16) | result[1], + 0x46003800u | ((uint)result[2] << 16) | result[3], + 0x2b002000u | ((uint)result[4] << 16) | result[5], + 0x15000b00u | ((uint)result[6] << 16) | result[7] + }; + + var decrypted = TcTea.CbcDecrypt(result[8..], teaKey); + if (decrypted.Length == 0) + { + return []; + } + + var output = new byte[8 + decrypted.Length]; + result.AsSpan(0, 8).CopyTo(output); + decrypted.CopyTo(output.AsSpan(8)); + return output; + } + + private static byte[] Base64Decode(string input, out int invalidCount) + { + var normalized = new char[input.Length + 3]; + var length = 0; + invalidCount = 0; + foreach (var value in input) + { + if (value is ' ' or '\r' or '\n' or '\t') + { + continue; + } + + if (value is not (>= 'A' and <= 'Z' or >= 'a' and <= 'z' or >= '0' and <= '9' + or '+' or '/' or '-' or '_' or '=')) + { + invalidCount++; + continue; + } + + normalized[length++] = value switch + { + '-' => '+', + '_' => '/', + _ => value + }; + } + + if (invalidCount != 0 || length == 0 || length % 4 == 1) + { + return []; + } + + // 兼容省略末尾填充的密钥,由标准解码器校验填充位置。 + while (length % 4 != 0) + { + normalized[length++] = '='; + } + + var padding = normalized[length - 1] == '=' ? 1 : 0; + if (normalized[length - 2] == '=') + { + padding++; + } + + var output = new byte[length / 4 * 3 - padding]; + return Convert.TryFromBase64Chars(normalized.AsSpan(0, length), output, out _) ? output : []; + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs new file mode 100644 index 0000000..ecade82 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs @@ -0,0 +1,263 @@ +// Ported from the MIT-licensed reference implementation: +// https://github.com/lizipeng0013/kgg-dec.mirror +// Copyright (c) 2024 LSR +// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. + +using System.Buffers.Binary; +using System.Text; + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// 酷狗 .kgg 文件的解密器。 + /// + /// .kgg 的音频主体用 QMC2 加密,而每个文件自己的 ekey 并不在文件里, + /// 需要从酷狗客户端本地的 KGMusicV3.db 中按音频哈希查出来。 + /// 因此这个格式无法脱离酷狗客户端单独解密。 + /// + /// + internal static class KggMusicDecryptor + { + private const int HeaderSize = KugouEkeyDatabase.KggHeaderSize; + private const int BufferSize = 1024 * 1024; + private const uint ExpectedEncodingVersion = 5; + private const uint ExpectedHashLength = 0x20; + + /// + /// .kgg 文件的 16 字节魔数。 + /// + private static byte[] Magic => KugouEkeyDatabase.KggMagic; + + /// + /// 按魔数和加密版本判断是否为 KGG,避免误判共用魔数的旧版 KGM。 + /// + public static bool IsKggFile(string filePath) + { + try + { + using var stream = File.OpenRead(filePath); + 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 + { + return false; + } + } + + /// + /// 解密 .kgg 文件。 + /// + /// 待解密的文件路径。 + /// 密钥来源;为 null 时使用自动探测到的酷狗数据库。 + /// 取消令牌。 + /// 解密结果;失败时带有可读的错误说明。 + public static async Task ConvertAsync(string filePath, + IKugouKeyProvider? keyProvider, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!File.Exists(filePath)) + { + return DecryptionResult.Failed($"文件不存在: {filePath}"); + } + + await using var input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, true); + + var header = new byte[HeaderSize]; + if (await input.ReadAtLeastAsync(header, HeaderSize, throwOnEndOfStream: false, cancellationToken) != + HeaderSize) + { + return DecryptionResult.Failed("文件过小,不是有效的 kgg 文件。"); + } + + if (!header.AsSpan(0, Magic.Length).SequenceEqual(Magic)) + { + return DecryptionResult.Failed("文件头校验失败,不是有效的 kgg 文件。"); + } + + var offsetToAudio = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10)); + if (offsetToAudio < HeaderSize || offsetToAudio > input.Length - 4) + { + return DecryptionResult.Failed("kgg 音频偏移超出有效范围。"); + } + + var encodingVersion = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14)); + if (encodingVersion != ExpectedEncodingVersion) + { + return DecryptionResult.Failed($"不支持的 kgg 加密版本 0x{encodingVersion:X2},目前只支持 0x05。"); + } + + var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44)); + if (hashLength != ExpectedHashLength) + { + return DecryptionResult.Failed($"kgg 音频哈希长度异常(期望 0x20,实际 0x{hashLength:X2})。"); + } + + var audioHash = Encoding.ASCII.GetString(header, 0x48, (int)hashLength); + + if (!HasDatabase(keyProvider)) + { + return DecryptionResult.Failed(keyProvider?.Probe().Message ?? KugouEkeyDatabase.BuildMissingDatabaseMessage()); + } + + var ekey = ResolveEkey(keyProvider, audioHash); + cancellationToken.ThrowIfCancellationRequested(); + if (string.IsNullOrEmpty(ekey)) + { + return DecryptionResult.Failed( + $"在酷狗数据库中没有找到该文件的解密密钥(音频哈希 {audioHash})。" + + "通常表示这首歌尚未在酷狗客户端里播放或下载过。"); + } + + var qmcKey = EkeyDecoder.Decode(ekey, out var invalidCharCount); + if (invalidCharCount > 0) + { + return DecryptionResult.Failed( + $"酷狗数据库里的 ekey 已损坏(有 {invalidCharCount} 个非法 Base64 字符),无法解码。" + + "通常表示数据库文件被写坏了,可以尝试重新登录酷狗客户端刷新该记录。"); + } + + var cipher = Qmc2Cipher.Create(qmcKey); + if (cipher == null) + { + return DecryptionResult.Failed("ekey 解码失败,无法构造解密器。"); + } + + input.Seek(offsetToAudio, SeekOrigin.Begin); + + // 先解密开头 4 字节用于判断真实格式,再回去完整解密一遍。 + var magic = new byte[4]; + if (await input.ReadAtLeastAsync(magic, 4, throwOnEndOfStream: false, cancellationToken) != 4) + { + return DecryptionResult.Failed("kgg 音频数据为空。"); + } + + cipher.Decrypt(magic, 0); + var extension = DetectExtension(magic); + if (extension == null) + { + return DecryptionResult.Failed("解密后的音频格式无法识别,文件或密钥可能已损坏。"); + } + + input.Seek(offsetToAudio, SeekOrigin.Begin); + + var outputPath = Path.Combine( + Path.GetDirectoryName(filePath)!, + $"{Path.GetFileNameWithoutExtension(filePath)}.{extension}"); + + // 期望的输出字节数,用于校验写盘是否完整。 + var expectedLength = input.Length - offsetToAudio; + + if (File.Exists(outputPath)) + { + return DecryptionResult.Failed($"输出文件已存在,未覆盖:{outputPath}"); + } + + // 每次转换独占临时文件,仅在完整写入后发布,且不覆盖已有输出。 + var tempPath = outputPath + $".{Guid.NewGuid():N}.part"; + var ownsTempFile = false; + try + { + await using (var output = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, + BufferSize, true)) + { + ownsTempFile = true; + var buffer = new byte[BufferSize]; + var offset = 0L; + while (true) + { + var read = await input.ReadAsync(buffer, cancellationToken); + if (read == 0) + { + break; + } + + cipher.Decrypt(buffer.AsSpan(0, read), offset); + await output.WriteAsync(buffer.AsMemory(0, read), cancellationToken); + offset += read; + } + + await output.FlushAsync(cancellationToken); + + if (offset != expectedLength) + { + throw new IOException($"解密写入的字节数不匹配(期望 {expectedLength},实际 {offset})。"); + } + } + + cancellationToken.ThrowIfCancellationRequested(); + File.Move(tempPath, outputPath); + } + finally + { + if (ownsTempFile) + { + TryDelete(tempPath); + } + } + + return DecryptionResult.Success(outputPath); + } + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch + { + // 保留原始转换结果或异常。 + } + } + + private static bool HasDatabase(IKugouKeyProvider? keyProvider) + { + return keyProvider != null ? keyProvider.DatabasePath != null : KugouEkeyDatabase.FindDatabasePath() != null; + } + + /// + /// 取出音频哈希对应的 ekey;优先走外部提供的密钥来源。 + /// + public static string? ResolveEkey(IKugouKeyProvider? keyProvider, string audioHash) + { + if (keyProvider != null) + { + return keyProvider.FindKey(audioHash); + } + + var databasePath = KugouEkeyDatabase.FindDatabasePath(); + if (databasePath == null) + { + return null; + } + + var keys = KugouEkeyDatabase.ReadEncryptionKeys(databasePath); + return keys.TryGetValue(audioHash, out var ekey) ? ekey : null; + } + + private static string? DetectExtension(ReadOnlySpan magic) + { + if (magic.SequenceEqual("fLaC"u8)) + { + return "flac"; + } + + if (magic.SequenceEqual("OggS"u8)) + { + return "ogg"; + } + + return magic[..3].SequenceEqual("ID3"u8) + || (magic[0] == 0xFF && (magic[1] & 0xE0) == 0xE0 && (magic[1] & 0x06) != 0) + ? "mp3" + : null; + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs new file mode 100644 index 0000000..034f80e --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs @@ -0,0 +1,311 @@ +// Ported from the MIT-licensed reference implementation: +// https://github.com/lizipeng0013/kgg-dec.mirror +// Copyright (c) 2024 LSR +// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. + +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Data.Sqlite; + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。 + /// + /// 数据库按 1KB 分页做了 AES-128-CBC 加密,每页的密钥与 IV 由主密钥和页号派生。 + /// 解密后可以读到 ShareFileItems 表里的 ekey,那是 .kgg 文件真正用的解密密钥。 + /// + /// + internal static class KugouEkeyDatabase + { + /// + /// .kgg 文件头的长度,音频数据从这个位置之后开始。 + /// + internal const int KggHeaderSize = 0x400; + + /// + /// .kgg 文件的 16 字节魔数。 + /// + internal static readonly byte[] KggMagic = + [ + 0x7C, 0xD5, 0x32, 0xEB, 0x86, 0x02, 0x7F, 0x4B, + 0xA8, 0xAF, 0xA6, 0x8E, 0x0F, 0xFF, 0x99, 0x14 + ]; + + private const int PageSize = 0x400; + private const uint PageKeySalt = 0x546C4173; + private const uint IvMultiplier = 0x7FFFFF07; + private const uint IvDivisor = 0xce26; + private const uint IvBase = 0x9EF4; + + /// + /// 酷狗客户端内置的主密钥。 + /// + private static readonly byte[] MasterKey = + [ + 0x1d, 0x61, 0x31, 0x45, 0xb2, 0x47, 0xbf, 0x7f, + 0x3d, 0x18, 0x96, 0x72, 0x14, 0x4f, 0xe4, 0xbf + ]; + + private static readonly byte[] SqliteHeader = + [ + (byte)'S', (byte)'Q', (byte)'L', (byte)'i', (byte)'t', (byte)'e', (byte)' ', + (byte)'f', (byte)'o', (byte)'r', (byte)'m', (byte)'a', (byte)'t', (byte)' ', (byte)'3', 0 + ]; + + /// + /// 从数据库里读出所有非空的 ekey。 + /// + /// 音频哈希到 ekey 的映射;文件不存在或解密失败时返回空字典。 + public static IReadOnlyDictionary ReadEncryptionKeys(string databasePath) + { + return ReadEncryptionKeys(databasePath, out _); + } + + /// + /// 从数据库里读出所有非空的 ekey,并在失败时给出可读的原因。 + /// + /// 读取失败的原因有多种(文件不存在 / 不是酷狗数据库 / 主密钥不匹配 / 表结构缺失 / 权限不足), + /// 这些在 UI 上的处置完全不同,因此不能再把所有异常压成「没有密钥」。 + /// + /// + /// 数据库文件路径。 + /// 读取失败时的原因说明;成功时为 null。 + public static IReadOnlyDictionary ReadEncryptionKeys(string databasePath, out string? failureReason) + { + failureReason = null; + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + + if (string.IsNullOrWhiteSpace(databasePath)) + { + failureReason = "没有指定酷狗数据库路径。"; + return result; + } + + if (!File.Exists(databasePath)) + { + failureReason = $"数据库文件不存在:{databasePath}"; + return result; + } + + byte[] plain; + try + { + plain = DecryptDatabase(databasePath); + } + catch (Exception ex) + { + failureReason = $"数据库解密失败(文件可能不是酷狗 KGMusicV3.db,或版本不受支持):{ex.Message}"; + return result; + } + + if (plain.Length == 0) + { + failureReason = $"数据库解密后内容为空,格式不像酷狗 KGMusicV3.db:{databasePath}"; + return result; + } + + // 直接从内存解析,避免明文密钥落盘和并发清理临时文件的竞争。 + var pinned = GCHandle.Alloc(plain, GCHandleType.Pinned); + try + { + using var connection = new SqliteConnection("Data Source=:memory:;Pooling=False"); + connection.Open(); + var error = SQLitePCL.raw.sqlite3_deserialize(connection.Handle, "main", + pinned.AddrOfPinnedObject(), plain.Length, plain.Length, SQLitePCL.raw.SQLITE_DESERIALIZE_READONLY); + if (error != SQLitePCL.raw.SQLITE_OK) + { + throw new SqliteException("无法读取解密后的酷狗数据库。", error); + } + + using var command = connection.CreateCommand(); + command.CommandText = "select EncryptionKeyId, EncryptionKey from ShareFileItems where EncryptionKey != ''"; + using var reader = command.ExecuteReader(); + while (reader.Read()) + { + if (reader.IsDBNull(0) || reader.IsDBNull(1)) + { + continue; + } + + var keyId = reader.GetString(0); + var ekey = reader.GetString(1); + if (keyId.Length > 0 && ekey.Length > 0) + { + result[keyId] = ekey; + } + } + } + catch (Exception ex) + { + failureReason = $"数据库内容读取失败(表 ShareFileItems 可能不存在):{ex.Message}"; + return new Dictionary(StringComparer.OrdinalIgnoreCase); + } + finally + { + pinned.Free(); + } + + return result; + } + + /// + /// 把整个加密数据库解密成明文的 SQLite 字节流。 + /// + private static byte[] DecryptDatabase(string databasePath) + { + using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read); + + var sourceLength = source.Length; + if (sourceLength == 0 || sourceLength > Array.MaxLength || sourceLength % PageSize != 0) + { + return []; + } + + var length = (int)sourceLength; + var pageCount = length / PageSize; + var plain = new byte[length]; + var headerBuffer = new byte[8]; + + // 复用同一个 Aes 实例:每页只是换 Key,避免 16000+ 次 Aes.Create() 的对象构造开销。 + using var aes = Aes.Create(); + aes.Mode = CipherMode.CBC; + aes.Padding = PaddingMode.None; + + for (var pageIndex = 1; pageIndex <= pageCount; pageIndex++) + { + var target = plain.AsSpan((pageIndex - 1) * PageSize, PageSize); + source.ReadExactly(target); + + DerivePageKeyIv((uint)pageIndex, out var key, out var iv); + + if (pageIndex == 1) + { + // 首页前 16 字节是明文文件头,真正从 0x10 开始加密; + // 解密前要把 0x08..0x10 复制到 0x10 处作为 CBC 的密文块。 + target.Slice(0x10, 8).CopyTo(headerBuffer); + target.Slice(0x08, 8).CopyTo(target[0x10..]); + + AesCbcDecryptInPlace(aes, target[0x10..], key, iv); + + if (!target.Slice(0x10, 8).SequenceEqual(headerBuffer)) + { + return []; + } + + SqliteHeader.CopyTo(target); + } + else + { + AesCbcDecryptInPlace(aes, target, key, iv); + } + } + + return plain; + } + + private static void AesCbcDecryptInPlace(Aes aes, Span buffer, byte[] key, byte[] iv) + { + aes.Key = key; + + // 两个坑都要显式避开: + // 1) 参数顺序是 TryDecryptCbc(ciphertext, iv, destination, out written, padding), + // 写成 (buffer, buffer, iv, ...) 会把 buffer 自己当 IV、把真正的 IV 覆盖掉; + // 2) padding 的默认值是 PKCS7 而不是实例上的 aes.Padding,分页数据是整块无填充的, + // 不传 PaddingMode.None 就会在每页末尾抛「Padding is invalid」。 + if (!aes.TryDecryptCbc(buffer, iv, buffer, out var written, PaddingMode.None) || + written != buffer.Length) + { + throw new CryptographicException("酷狗数据库分页解密失败。"); + } + } + + /// + /// 按页号派生出该页使用的 AES 密钥与 IV。 + /// + private static void DerivePageKeyIv(uint pageNumber, out byte[] key, out byte[] iv) + { + var buffer = new byte[0x18]; + MasterKey.CopyTo(buffer, 0); + BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x10), pageNumber); + BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(0x14), PageKeySalt); + + key = MD5.HashData(buffer); + + // IV 由一个线性同余式的四次迭代结果拼成。 + var value = pageNumber + 1; + for (var i = 0; i < 16; i += 4) + { + unchecked + { + var quotient = value / IvDivisor; + var product = IvMultiplier * quotient; + var next = IvBase * value - product; + if ((next & 0x8000_0000) != 0) + { + next += IvMultiplier; + } + + value = next; + BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(i), value); + } + } + + iv = MD5.HashData(buffer.AsSpan(0, 0x10)); + } + + /// + /// 酷狗客户端数据库的常见位置。 + /// + public static IEnumerable EnumerateCandidatePaths() + { + var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + if (!string.IsNullOrEmpty(roaming)) + { + yield return Path.Combine(roaming, "KuGou8", "KGMusicV3.db"); + yield return Path.Combine(roaming, "KuGou", "KGMusicV3.db"); + } + + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (!string.IsNullOrEmpty(localAppData)) + { + yield return Path.Combine(localAppData, "KuGou8", "KGMusicV3.db"); + yield return Path.Combine(localAppData, "KuGou", "KGMusicV3.db"); + } + } + + /// + /// 找到第一个存在的数据库路径。 + /// + public static string? FindDatabasePath() + { + foreach (var path in EnumerateCandidatePaths()) + { + if (File.Exists(path)) + { + return path; + } + } + + return null; + } + + /// + /// 让用户能看懂的错误信息。 + /// + public static string BuildMissingDatabaseMessage() + { + var builder = new StringBuilder(); + builder.Append("未找到酷狗客户端数据库 KGMusicV3.db,无法获取解密密钥。"); + builder.Append("请确认已安装酷狗音乐并至少登录过一次。已尝试的路径:"); + foreach (var path in EnumerateCandidatePaths()) + { + builder.Append(' ').Append(path).Append(';'); + } + + return builder.ToString(); + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs new file mode 100644 index 0000000..d412c6b --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs @@ -0,0 +1,260 @@ +// Ported from the MIT-licensed reference implementation: +// https://github.com/lizipeng0013/kgg-dec.mirror +// Copyright (c) 2024 LSR +// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// QMC2 加密流的解密器基类,负责按偏移量流式解出明文。 + /// + internal abstract class Qmc2Cipher + { + /// + /// 首段的长度,这一段的密钥派生方式与其他段不同。 + /// + protected const int FirstSegmentSize = 0x80; + + /// + /// 其余段落的长度。 + /// + protected const int OtherSegmentSize = 0x1400; + + /// + /// 解密数据流中的一个字节。 + /// + /// 密文中的该字节。 + /// 该字节在完整音频流中的偏移量。 + public abstract byte Decrypt(byte cipher, long offset); + + /// + /// 就地把一段数据解密。 + /// + /// 批量接口,避免逐字节走虚函数调用;几十 MB 的文件靠逐字节会慢到不可接受。 + /// + /// + /// 待解密的密文,解密结果原地写回。 + /// 这段数据在完整音频流中的起始偏移量。 + public virtual void Decrypt(Span data, long offset) + { + for (var i = 0; i < data.Length; i++) + { + data[i] = Decrypt(data[i], offset + i); + } + } + + /// + /// 根据解码后的 ekey 长度选择具体的实现。 + /// + public static Qmc2Cipher? Create(byte[] key) + { + if (key.Length == 0) + { + return null; + } + + return key.Length < 300 ? new Qmc2MapCipher(key) : new Qmc2Rc4Cipher(key); + } + } + + /// + /// 短密钥(长度小于 300)使用的查表型解密器。 + /// + internal sealed class Qmc2MapCipher : Qmc2Cipher + { + private const int MapIndexOffset = 71214; + private const int MapKeySize = 128; + private const int MapIndexBoundary = 0x7FFF; + + private readonly byte[] _key; + + /// + /// 根据短密钥生成查找表。 + /// + public Qmc2MapCipher(byte[] key) + { + _key = new byte[MapKeySize]; + var length = key.Length; + for (var i = 0; i < MapKeySize; i++) + { + var j = (int)(((long)i * i + MapIndexOffset) % length); + var shift = (j + 4) % 8; + var value = key[j]; + _key[i] = (byte)((value << shift) | (value >> shift)); + } + } + + /// + 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++) + { + var position = offset + i; + var index = position <= MapIndexBoundary ? position : position % MapIndexBoundary; + data[i] ^= _key[index % MapKeySize]; + } + } + } + + /// + /// 长密钥使用的 RC4 派生流解密器。 + /// + internal sealed class Qmc2Rc4Cipher : Qmc2Cipher + { + /// + /// 每段从密钥流中取用的前置长度上限。 + /// + private const int SegmentSkipMask = 0x1FF; + + /// + /// 密钥流的长度,比普通段多出 512 字节用于起始偏移。 + /// + private const int KeyStreamSize = OtherSegmentSize + 512; + + private readonly byte[] _key; + private readonly byte[] _keyStream = new byte[KeyStreamSize]; + private readonly uint _keyHash; + + /// + /// 根据长密钥生成密钥流。 + /// + public Qmc2Rc4Cipher(byte[] key) + { + _key = key; + _keyHash = ComputeKeyHash(key); + DeriveKeyStream(); + } + + /// + public override byte Decrypt(byte cipher, long offset) + { + if (offset < FirstSegmentSize) + { + // 首段的索引直接由当前偏移推导,且随偏移逐字节变化。 + var seed = _key[(int)(offset % _key.Length)]; + var index = GetSegmentKey(_keyHash, offset, seed) % _key.Length; + return (byte)(cipher ^ _key[index]); + } + + var segmentIndex = offset / OtherSegmentSize; + var segmentOffset = offset % OtherSegmentSize; + var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask; + return (byte)(cipher ^ _keyStream[skipLength + segmentOffset]); + } + + /// + public override void Decrypt(Span data, long offset) + { + // 首段与常规段的算法不同,先按边界切一刀。 + if (offset < FirstSegmentSize) + { + var length = (int)Math.Min(data.Length, FirstSegmentSize - offset); + for (var i = 0; i < length; i++) + { + var seed = _key[(int)((offset + i) % _key.Length)]; + var index = GetSegmentKey(_keyHash, offset + i, seed) % _key.Length; + data[i] ^= _key[index]; + } + + offset += length; + data = data[length..]; + } + + while (data.Length > 0) + { + var segmentIndex = offset / OtherSegmentSize; + var segmentOffset = (int)(offset % OtherSegmentSize); + var skipLength = GetSegmentKey(_keyHash, segmentIndex, _key[segmentIndex % _key.Length]) & SegmentSkipMask; + var length = Math.Min(data.Length, OtherSegmentSize - segmentOffset); + + var stream = _keyStream.AsSpan((int)skipLength + segmentOffset, length); + for (var i = 0; i < length; i++) + { + data[i] ^= stream[i]; + } + + offset += length; + data = data[length..]; + } + } + + /// + /// 把密钥压成一个 32 位的乘法哈希,遇到溢出就提前结束。 + /// + private static uint ComputeKeyHash(ReadOnlySpan key) + { + var hash = 1u; + foreach (var item in key) + { + if (item == 0) + { + continue; + } + + var next = hash * item; + if (next <= hash) + { + break; + } + + hash = next; + } + + return hash; + } + + /// + /// 按段号与种子计算出该段在密钥或密钥流中的起始位置。 + /// + /// 中间结果可能远超 int 上限,必须用 long 承载,否则会截断出错位。 + /// + /// + private static long GetSegmentKey(uint hash, long segmentId, int seed) + { + if (seed == 0) + { + return 0; + } + + return (long)(hash / (double)(seed * (segmentId + 1)) * 100.0); + } + + /// + /// 用 RC4 的 KSA 生成密钥流。 + /// + private void DeriveKeyStream() + { + var length = _key.Length; + var state = new byte[length]; + for (var i = 0; i < length; i++) + { + state[i] = (byte)i; + } + + // 这里的 i / j 必须是宽于 byte 的整数,长度 512 时 byte 会回绕。 + var j = 0; + for (var i = 0; i < length; i++) + { + j = (j + state[i] + _key[i]) % length; + (state[i], state[j]) = (state[j], state[i]); + } + + var a = 0; + var b = 0; + for (var i = 0; i < KeyStreamSize; i++) + { + a = (a + 1) % length; + b = (b + state[a]) % length; + (state[a], state[b]) = (state[b], state[a]); + _keyStream[i] = state[(state[a] + state[b]) % length]; + } + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs new file mode 100644 index 0000000..0cd8627 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs @@ -0,0 +1,139 @@ +// Ported from the MIT-licensed reference implementation: +// https://github.com/lizipeng0013/kgg-dec.mirror +// Copyright (c) 2024 LSR +// The original licence text is reproduced in THIRD-PARTY-NOTICES.md at the repository root. + +using System.Buffers.Binary; + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// 腾讯 TEA(TC-TEA)加解密实现,用于解析酷狗的 ekey 密文。 + /// + /// 这里只实现了 QMC2 所需的部分:单块 ECB 解密与带双 IV 链的 CBC 解密。 + /// 算法来源于酷狗客户端的实际行为,与 MusicDecrypto 内置的格式无关。 + /// + /// + internal static class TcTea + { + private const int Rounds = 16; + private const uint Delta = 0x9e3779b9; + + /// + /// 16 轮累加后的 sum 值,等价于 Rounds * Delta 在 uint32 下的溢出结果。 + /// + private const uint ExpectedSum = 0xE3779B90; + + private const int BlockSize = 8; + private const int FixedSaltLength = 2; + private const int ZeroPaddingLength = 7; + private const int HeaderSize = BlockSize * 2; + + private static uint SingleRound(uint value, uint sum, uint key1, uint key2) + { + return ((value << 4) + key1) ^ (value + sum) ^ ((value >> 5) + key2); + } + + /// + /// TEA 单块解密(ECB)。 + /// + public static ulong DecryptBlock(ulong value, ReadOnlySpan key) + { + var y = (uint)(value >> 32); + var z = (uint)value; + var sum = ExpectedSum; + + for (var i = 0; i < Rounds; i++) + { + z -= SingleRound(y, sum, key[2], key[3]); + y -= SingleRound(z, sum, key[0], key[1]); + sum -= Delta; + } + + return ((ulong)y << 32) | z; + } + + /// + /// TC-TEA 的 CBC 解密,带自定义的头部跳过与零填充校验。 + /// + /// 参数与返回值都用数组而非 Span,是因为内部要用局部函数保存解密状态。 + /// + /// + /// 解密后的明文;若校验失败则返回空数组。 + public static byte[] CbcDecrypt(byte[] cipher, uint[] key) + { + // 由于填充方案的特殊性,密文至少要两个块长。 + if (cipher.Length % BlockSize != 0 || cipher.Length < HeaderSize) + { + return []; + } + + var iv1 = 0UL; + var iv2 = 0UL; + var inOffset = 0; + var header = new byte[HeaderSize]; + + // 解密一轮,把结果写到 target 指定的 8 字节位置。 + void DecryptRound(byte[] target, int targetOffset) + { + var iv1Next = BinaryPrimitives.ReadUInt64BigEndian(cipher.AsSpan(inOffset)); + var iv2Next = DecryptBlock(iv1Next ^ iv2, key); + var plain = iv2Next ^ iv1; + + iv1 = iv1Next; + iv2 = iv2Next; + BinaryPrimitives.WriteUInt64BigEndian(target.AsSpan(targetOffset), plain); + inOffset += BlockSize; + } + + DecryptRound(header, 0); + DecryptRound(header, BlockSize); + + var headerSkipLength = 1 + (header[0] & 7) + FixedSaltLength; + var realPlainLength = cipher.Length - headerSkipLength - ZeroPaddingLength; + if (realPlainLength <= 0) + { + return []; + } + + var result = new byte[realPlainLength]; + + // 先拷出头部块里剩余的明文。 + var copyLength = Math.Min(HeaderSize - headerSkipLength, realPlainLength); + Array.Copy(header, headerSkipLength, result, 0, copyLength); + var outOffset = copyLength; + + if (realPlainLength != copyLength) + { + for (var i = cipher.Length - BlockSize * 3; i != 0; i -= BlockSize) + { + DecryptRound(header, 0); + Array.Copy(header, 0, result, outOffset, BlockSize); + outOffset += BlockSize; + } + + // 最后一个块只取首字节,且必须落在 header 的第二个块位置,供下方零填充校验使用。 + DecryptRound(header, BlockSize); + result[outOffset] = header[BlockSize]; + } + + // 校验零填充:末尾 8 字节左移一位后必须为 0。 + var verify = BinaryPrimitives.ReadUInt64BigEndian(header.AsSpan(BlockSize)) << 8; + return verify != 0 ? [] : result; + } + + /// + /// 将 16 字节的密钥按大端拆成 4 个 uint32,供 TEA 使用。 + /// + public static uint[] ToRoundKeys(byte[] key) + { + var result = new uint[4]; + for (var i = 0; i < 4; i++) + { + result[i] = BinaryPrimitives.ReadUInt32BigEndian(key.AsSpan(i * 4)); + } + + return result; + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs b/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs new file mode 100644 index 0000000..4ae7850 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs @@ -0,0 +1,195 @@ +using System.Buffers.Binary; +using System.Text; +using ZonyLrcTools.Common.Infrastructure.DependencyInject; + +namespace ZonyLrcTools.Common.MusicDecryption +{ + /// + public class KugouKeyProvider : IKugouKeyProvider, ISingletonDependency + { + private const int HeaderSize = Kugou.KugouEkeyDatabase.KggHeaderSize; + private const int AudioHashOffset = 0x48; + private const int AudioHashLength = 0x20; + + private readonly object _syncRoot = new(); + private readonly Dictionary _keys = new(StringComparer.OrdinalIgnoreCase); + + private string? _manualPath; + private string? _databasePath; + private string? _failureReason; + private bool _isLoaded; + + /// + public string? DatabasePath + { + get + { + lock (_syncRoot) + { + EnsureLoaded(); + return _databasePath; + } + } + } + + /// + public void SetDatabasePath(string? path) + { + lock (_syncRoot) + { + var normalized = string.IsNullOrWhiteSpace(path) ? null : path; + if (string.Equals(normalized, _manualPath, + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + { + // 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。 + return; + } + + _manualPath = normalized; + Invalidate(); + } + } + + /// + /// 探测当前可用的酷狗数据库。 + /// + /// 结果会被缓存:整库解密需要几十毫秒,而真正查一次密钥只要 0.1 毫秒。 + /// 只有在 改变了路径、或显式调用 时才会重新读取。 + /// + /// + public KugouDatabaseInfo Probe() + { + lock (_syncRoot) + { + EnsureLoaded(); + + if (_databasePath == null) + { + var message = _manualPath != null + ? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}" + : _failureReason ?? Kugou.KugouEkeyDatabase.BuildMissingDatabaseMessage(); + + return new KugouDatabaseInfo(false, null, 0, message); + } + + return _keys.Count == 0 + ? new KugouDatabaseInfo(false, _databasePath, 0, + $"已找到酷狗数据库,但里面没有任何解密密钥:{_databasePath}") + : new KugouDatabaseInfo(true, _databasePath, _keys.Count, + $"已读取 {_keys.Count} 个解密密钥:{_databasePath}"); + } + } + + /// + /// 让下一次访问重新读取数据库(例如用户在酷狗里新下载了歌曲)。 + /// + public void Invalidate() + { + lock (_syncRoot) + { + _isLoaded = false; + _keys.Clear(); + _databasePath = null; + _failureReason = null; + } + } + + /// + public bool IsKggFile(string filePath) => Kugou.KggMusicDecryptor.IsKggFile(filePath); + + /// + public string? ReadAudioHash(string filePath) + { + try + { + using var stream = File.OpenRead(filePath); + var header = new byte[HeaderSize]; + if (stream.ReadAtLeast(header, HeaderSize, throwOnEndOfStream: false) != HeaderSize) + { + return null; + } + + if (!header.AsSpan(0, 16).SequenceEqual(Kugou.KugouEkeyDatabase.KggMagic)) + { + return null; + } + + var audioOffset = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x10)); + if (BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x14)) != 5 + || audioOffset < HeaderSize || audioOffset > stream.Length - 4) + { + return null; + } + + var hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44)); + if (hashLength != AudioHashLength) + { + return null; + } + + return Encoding.ASCII.GetString(header, AudioHashOffset, (int)hashLength); + } + catch + { + return null; + } + } + + /// + public string? FindKey(string audioHash) + { + if (string.IsNullOrEmpty(audioHash)) + { + return null; + } + + lock (_syncRoot) + { + EnsureLoaded(); + return _keys.TryGetValue(audioHash, out var ekey) && !string.IsNullOrEmpty(ekey) ? ekey : null; + } + } + + private void EnsureLoaded() + { + if (_isLoaded) + { + return; + } + + _isLoaded = true; + _keys.Clear(); + _databasePath = null; + _failureReason = null; + + var path = _manualPath; + if (path == null) + { + path = Kugou.KugouEkeyDatabase.FindDatabasePath(); + if (path == null) + { + return; + } + } + else if (!File.Exists(path)) + { + _failureReason = "文件不存在"; + return; + } + + var keys = Kugou.KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason); + if (keys.Count == 0) + { + _failureReason = failureReason ?? "没有读到任何密钥"; + + return; + } + + _databasePath = path; + foreach (var pair in keys) + { + _keys[pair.Key] = pair.Value; + } + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs index 825a4a5..2ea8235 100644 --- a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs +++ b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs @@ -15,22 +15,28 @@ 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 csvFileLines = csvFileContent.Split([Environment.NewLine], StringSplitOptions.RemoveEmptyEntries); - return csvFileLines.Skip(1).Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern)) + var csvFileContent = await File.ReadAllTextAsync(csvFilePath, encoding, cancellationToken); + + // 兼容不同操作系统导出的换行符。 + var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); + return csvFileLines.Skip(1) + .Where(line => line.Contains(',')) + .Select(line => GetMusicInfoFromCsvFileLine(line, outputDirectory, pattern)) .ToList(); } private MusicInfo GetMusicInfoFromCsvFileLine(string csvFileLine, string outputDirectory, string pattern) { var csvFileLineItems = csvFileLine.Split(','); - var name = csvFileLineItems[0]; - var artist = csvFileLineItems[1]; + var name = csvFileLineItems[0].Trim(); + var artist = csvFileLineItems.Length > 1 ? csvFileLineItems[1].Trim() : string.Empty; var fakeFilePath = Path.Combine(outputDirectory, pattern.Replace("{Name}", name).Replace("{Artist}", artist)); var musicInfo = new MusicInfo(fakeFilePath, name, artist); return musicInfo; diff --git a/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs b/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs index 120cf95..282635c 100644 --- a/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs +++ b/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs @@ -20,9 +20,60 @@ 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; - private string Cookie { get; set; } = string.Empty; - private string CsrfToken { get; set; } = string.Empty; + /// + /// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。 + /// + public string Cookie + { + get + { + lock (_loginStateLock) + { + return _cookie; + } + } + set + { + lock (_loginStateLock) + { + _cookie = value ?? string.Empty; + _loginStateVersion++; + } + } + } + + /// + /// 登录后的 CSRF Token,通常与 一起持久化。 + /// + public string CsrfToken + { + get + { + lock (_loginStateLock) + { + return _csrfToken; + } + } + set + { + lock (_loginStateLock) + { + _csrfToken = value ?? string.Empty; + _loginStateVersion++; + } + } + } + + /// + /// 当前是否已经持有登录态。 + /// + public bool IsLoggedIn => !string.IsNullOrEmpty(Cookie); /// /// 构建一个新的 对象。 @@ -34,34 +85,122 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency _logger = logger; } + /// + /// 清除当前登录态,下次调用歌单接口时会重新要求扫码。 + /// + public void ClearLoginState() + { + RestoreLoginState(string.Empty, string.Empty); + } + + /// + /// 恢复一个已有的登录态,供 GUI 从本地缓存中读回 Cookie 之后调用。 + /// + /// 之前登录成功时保存的 Cookie。 + /// 与 一起保存的 CSRF Token。 + public void RestoreLoginState(string cookie, string csrfToken) + { + lock (_loginStateLock) + { + _cookie = cookie ?? string.Empty; + _csrfToken = csrfToken ?? string.Empty; + _loginStateVersion++; + } + } + + /// + /// 主动触发一次扫码登录(如果已经登录则直接返回 true)。 + /// + /// 二维码就绪回调。 + /// 登录状态变化回调,GUI 用它显示「已扫码,请在手机上确认」之类的中间态。 + /// 取消令牌。 + /// 登录成功时为 true。 + public async Task LoginAsync( + Action? onQrCodeReady = null, + Action? onStateChanged = null, + CancellationToken cancellationToken = default) + { + await _loginSemaphore.WaitAsync(cancellationToken); + try + { + var session = GetLoginState(); + if (!string.IsNullOrEmpty(session.Cookie)) + { + onStateChanged?.Invoke(NetEaseLoginState.Succeeded); + return true; + } + + var loginResponse = await LoginViaQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + var cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty; + lock (_loginStateLock) + { + // 退出或恢复会话后,不能再提交旧二维码的登录结果。 + if (session.Version != _loginStateVersion) + { + return false; + } + + _cookie = cookie; + _csrfToken = loginResponse.csrfToken ?? string.Empty; + _loginStateVersion++; + } + + if (string.IsNullOrEmpty(cookie)) + { + return false; + } + + onStateChanged?.Invoke(NetEaseLoginState.Succeeded); + return true; + } + finally + { + _loginSemaphore.Release(); + } + } + /// /// 从网易云歌单获取需要下载的歌曲列表,调用这个 API 需要用户登录,否则获取的歌单数据不全。 /// - /// 网易云音乐歌单的 ID。 + /// 网易云音乐歌单的 ID,多个歌单以分号分隔。 /// 歌词文件的输出路径。 /// 输出的歌词文件格式,默认是 "{Artist} - {Title}.lrc" 的形式。 + /// + /// 二维码就绪时的回调。CLI 不传,走原有的终端 ASCII 输出;GUI 传入后会收到可渲染的二维码数据。 + /// + /// 登录状态变化回调。 + /// 取消令牌,用于中断扫码等待与歌单请求。 /// 返回获取到的歌曲列表。 - public async Task> GetMusicInfoFromNetEaseMusicSongListAsync(string songListIds, string outputDirectory, string pattern) + public async Task> GetMusicInfoFromNetEaseMusicSongListAsync( + string songListIds, + string outputDirectory, + string pattern, + Action? onQrCodeReady = null, + Action? onStateChanged = null, + CancellationToken cancellationToken = default) { - if (string.IsNullOrEmpty(Cookie)) + if (!await LoginAsync(onQrCodeReady, onStateChanged, cancellationToken)) { - var loginResponse = await LoginViqQrCodeAsync(); - Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty; - CsrfToken = loginResponse.csrfToken ?? string.Empty; + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); } - async Task> 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, @@ -69,11 +208,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency limit = 1000, }, secretKey, encSecKey)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); - }); + }, cancellationToken: cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); if (response.Code != 200 || response.PlayList?.SongList == null) { - throw new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding); + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); } return response.PlayList.SongList @@ -88,16 +228,25 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency } var musicInfoList = new List(); - foreach (var songListId in songListIds.Split(';')) + foreach (var songListId in songListIds.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { - _logger.LogInformation("正在获取歌单 {SongListId} 的歌曲列表。", songListId); - var musicInfos = await GetMusicInfoBySongIdAsync(songListId); + cancellationToken.ThrowIfCancellationRequested(); + + var musicInfos = await GetMusicInfoBySongIdAsync(songListId, cancellationToken); musicInfoList.AddRange(musicInfos); } return musicInfoList; } + private (string Cookie, string CsrfToken, long Version) GetLoginState() + { + lock (_loginStateLock) + { + return (_cookie, _csrfToken, _loginStateVersion); + } + } + /// /// 用于加密请求参数,具体加密算法请参考网易云音乐的 JS 代码。 /// @@ -121,73 +270,103 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency /// /// 通过二维码登录网易云音乐,登录成功后返回 Cookie 和 CSRF Token。 /// - private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync() + /// + /// 二维码就绪回调。为空时保持原有行为 —— 把 ASCII 二维码打到日志里,供 CLI 在终端展示。 + /// + /// 登录状态变化回调。 + /// 取消令牌。 + private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViaQrCodeAsync( + Action? onQrCodeReady, + Action? onStateChanged, + CancellationToken cancellationToken = default) { - // Get unikey. - var qrCodeKeyJson = await (await PostAsync($"{Host}/weapi/login/qrcode/unikey", new + using var keyResponse = await PostAsync($"{Host}/weapi/login/qrcode/unikey", new { type = 1 - })).Content.ReadAsStringAsync(); - var uniKey = JObject.Parse(qrCodeKeyJson).SelectToken("$.unikey")!.Value(); - 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(); - var qrCodeData = qrGenerator.CreateQrCode($"{Host}/login?codekey={uniKey}", - QRCodeGenerator.ECCLevel.L); - var qrCode = new AsciiQRCode(qrCodeData); + using var qrGenerator = new QRCodeGenerator(); + var qrContent = $"{Host}/login?codekey={uniKey}"; + using var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L); + using var qrCode = new AsciiQRCode(qrCodeData); var asciiQrCodeString = qrCode.GetGraphic(1, drawQuietZones: false); - _logger.LogInformation("请使用网易云 APP 扫码登录:"); - _logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString); - - // Wait for login success. - var isLogin = false; - while (!isLogin) + if (onQrCodeReady != null) { - var (isSuccess, cookieContainer) = await CheckIsLoginAsync(uniKey); - isLogin = isSuccess; + onQrCodeReady(new NetEaseQrCodePayload(qrContent, uniKey, asciiQrCodeString)); + } + else + { + _logger.LogInformation("请使用网易云 APP 扫码登录:"); + _logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString); + } - if (!isLogin) + onStateChanged?.Invoke(NetEaseLoginState.Waiting); + var lastState = NetEaseLoginState.Waiting; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + + var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken); + + if (state != lastState && state != NetEaseLoginState.Succeeded) { - await Task.Delay(2000); + lastState = state; + onStateChanged?.Invoke(state); } - else + + if (state == NetEaseLoginState.Succeeded) { return (cookieContainer?.GetCookies(new Uri(Host))["__csrf"]?.Value, cookieContainer); } - } - return (null, null); + if (state == NetEaseLoginState.Expired) + { + // 二维码已失效,继续轮询没有意义。 + return (null, null); + } + + await Task.Delay(2000, cancellationToken); + } } - /// - /// 使用 检测是否登录成功。 - /// - /// 由网易云 API 生成的唯一 Key,用于登录。 - /// - /// 当登录成功的时候,元组 isSuccess 会为 true,cookieContainer 会包含登录成功后的 Cookie。
- /// 如果登录失败,isSuccess 会为 false,cookieContainer 会为 null。 - ///
- private async Task<(bool isSuccess, CookieContainer? cookieContainer)> CheckIsLoginAsync(string uniKey) + private async Task<(NetEaseLoginState state, CookieContainer? cookieContainer)> CheckIsLoginAsync( + string uniKey, + CancellationToken cancellationToken = default) { - var responseMessage = await PostAsync($"{Host}/weapi/login/qrcode/client/login", new + using var responseMessage = await PostAsync($"{Host}/weapi/login/qrcode/client/login", new { key = uniKey, type = 1 - }); + }, cancellationToken: cancellationToken); - var responseString = await responseMessage.Content.ReadAsStringAsync(); + var responseString = await responseMessage.Content.ReadAsStringAsync(cancellationToken); var responseCode = JObject.Parse(responseString)["code"]?.Value(); - if (responseCode != 803) + switch (responseCode) { - return (false, null); + // 800 二维码过期、801 等待扫码、802 已扫码待确认、803 登录成功。 + case 800: + return (NetEaseLoginState.Expired, null); + case 801: + return (NetEaseLoginState.Waiting, null); + case 802: + return (NetEaseLoginState.ScanConfirmed, null); + case 803: + break; + default: + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); } if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies)) { - return (false, null); + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); } var cookieContainer = new CookieContainer(); @@ -196,7 +375,12 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency cookieContainer.SetCookies(new Uri(Host), cookie); } - return (true, cookieContainer); + if (cookieContainer.GetCookies(new Uri(Host)).Count == 0) + { + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); + } + + return (NetEaseLoginState.Succeeded, cookieContainer); } /// @@ -204,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; + } } -} \ No newline at end of file +} diff --git a/src/ZonyLrcTools.Common/MusicScanner/NetEaseQrCodePayload.cs b/src/ZonyLrcTools.Common/MusicScanner/NetEaseQrCodePayload.cs new file mode 100644 index 0000000..8783302 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicScanner/NetEaseQrCodePayload.cs @@ -0,0 +1,27 @@ +namespace ZonyLrcTools.Common.MusicScanner; + +/// +/// 网易云音乐扫码登录的二维码数据。 +/// +/// 二维码指向的 URL,GUI 侧用它渲染二维码图片。 +/// 本次登录的唯一 Key,用于轮询登录状态。 +/// ASCII 形态的二维码,CLI 在终端里直接打印它。 +public sealed record NetEaseQrCodePayload(string Content, string UniKey, string AsciiGraphic); + +/// +/// 网易云音乐扫码登录的状态。 +/// +public enum NetEaseLoginState +{ + /// 二维码已生成,等待用户扫码。 + Waiting, + + /// 用户已扫码,等待在手机上确认。 + ScanConfirmed, + + /// 登录成功。 + Succeeded, + + /// 二维码已过期,需要重新获取。 + Expired +} diff --git a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj index 8cd7019..e6826c3 100644 --- a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj +++ b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj @@ -7,6 +7,9 @@ + + + @@ -24,4 +27,16 @@ + + + PreserveNewest + PreserveNewest + true + + + + + + + diff --git a/src/ZonyLrcTools.Desktop/App.axaml b/src/ZonyLrcTools.Desktop/App.axaml index afe9cbc..acaa972 100644 --- a/src/ZonyLrcTools.Desktop/App.axaml +++ b/src/ZonyLrcTools.Desktop/App.axaml @@ -6,6 +6,46 @@ + + + + + + + + + + + + + @@ -19,6 +59,13 @@ M3.55 19.09L4.96 20.5L6.76 18.71L5.34 17.29M12 6C8.69 6 6 8.69 6 12S8.69 18 12 18 18 15.31 18 12 15.31 6 12 6M20 13H23V11H20M17.24 18.71L19.04 20.5L20.45 19.09L18.66 17.29M20.45 5.41L19.04 4L17.24 5.79L18.66 7.21M13 1H11V4H13M6.76 5.79L4.96 4L3.55 5.41L5.34 7.21L6.76 5.79M1 13H4V11H1M13 20H11V23H13Z M5,20H19V18H5M19,9H15V3H9V9H5L12,16L19,9Z M10,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V8C22,6.89 21.1,6 20,6H12L10,4Z + M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z + M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M11,16.5L6.5,12L7.91,10.59L11,13.67L16.59,8.09L18,9.5L11,16.5Z + M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z + M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z + M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z + M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z + M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z diff --git a/src/ZonyLrcTools.Desktop/ILLink.Descriptors.xml b/src/ZonyLrcTools.Desktop/ILLink.Descriptors.xml new file mode 100644 index 0000000..c1b5856 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/ILLink.Descriptors.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs new file mode 100644 index 0000000..3e9024c --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs @@ -0,0 +1,103 @@ +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 解析桌面应用的配置目录。 +/// 优先使用便携目录;不可写时回退到当前用户的应用数据目录。 +public static class AppPaths +{ + private const string ApplicationFolderName = "ZonyLrcTools"; + private const string ConfigFileName = "config.yaml"; + + private static readonly Lazy LazyConfigDirectory = new(ResolveConfigDirectory); + + /// 配置文件所在目录。 + public static string ConfigDirectory => LazyConfigDirectory.Value; + + /// 配置文件的完整路径。 + public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName); + + /// 首次启动时将随程序附带的配置复制到用户目录。 + public static void EnsureConfigFile() + { + if (File.Exists(ConfigFilePath)) + { + return; + } + + var template = Path.Combine(AppContext.BaseDirectory, ConfigFileName); + if (!File.Exists(template)) + { + return; + } + + if (string.Equals( + Path.GetFullPath(template), + Path.GetFullPath(ConfigFilePath), + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) + { + return; + } + + try + { + File.Copy(template, ConfigFilePath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // 模板无法复制时由调用方处理缺失配置。 + } + } + + private static string ResolveConfigDirectory() + { + var baseDirectory = AppContext.BaseDirectory; + if (IsWritable(baseDirectory)) + { + return baseDirectory; + } + + var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + var fallback = Path.Combine(roaming, ApplicationFolderName); + + try + { + Directory.CreateDirectory(fallback); + if (IsWritable(fallback)) + { + return fallback; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // 没有可写目录时仍允许读取便携目录的配置。 + } + + return baseDirectory; + } + + private static bool IsWritable(string directory) + { + if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory)) + { + return false; + } + + var probe = Path.Combine(directory, $".write-probe-{Guid.NewGuid():N}"); + + try + { + using var stream = new FileStream( + probe, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + bufferSize: 1, + FileOptions.DeleteOnClose); + + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs new file mode 100644 index 0000000..78aeaa2 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs @@ -0,0 +1,26 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using ZonyLrcTools.Common.Configuration; +using ZonyLrcTools.Common.Infrastructure.DependencyInject; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 桌面配置服务注册。 +public static class ConfigurationServiceCollectionExtensions +{ + /// 从可写配置目录加载配置并注册设置存储。 + public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services) + { + AppPaths.EnsureConfigFile(); + + var configuration = new ConfigurationBuilder() + .SetBasePath(AppPaths.ConfigDirectory) + .AddYamlFile(Path.GetFileName(AppPaths.ConfigFilePath), optional: true, reloadOnChange: false) + .Build(); + + services.Configure(configuration); + services.AddSingleton(); + + return services; + } +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs new file mode 100644 index 0000000..1454b3e --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs @@ -0,0 +1,29 @@ +using ZonyLrcTools.Common.Configuration; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 设置保存结果。 +/// 是否保存成功。 +/// 保存成功的文件路径。 +/// 保存失败的原因。 +public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage) +{ + /// 创建保存成功的结果。 + public static SettingsSaveResult Success(string filePath) => new(true, filePath, null); + + /// 创建保存失败的结果。 + public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage); +} + +/// 统一管理共享配置及其持久化。 +public interface ISettingsStore +{ + /// 应用共享配置,修改后对按操作读取配置的组件立即生效。 + GlobalOptions Options { get; } + + /// 当前配置文件的完整路径。 + string ConfigFilePath { get; } + + /// 保存界面管理的配置值,不覆盖无法安全修改的文件。 + Task SaveAsync(CancellationToken cancellationToken = default); +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs new file mode 100644 index 0000000..f6809d8 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs @@ -0,0 +1,89 @@ +using System.Text.Json; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 保存本机手动选择的酷狗数据库路径。 +public sealed class KugouDatabaseStore +{ + private const string FileName = "kugou.database.json"; + + private readonly SemaphoreSlim _lock = new(1, 1); + + /// 本机状态文件的完整路径。 + public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); + + /// 读取数据库路径;文件缺失或损坏时返回空。 + public async Task LoadAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + if (!File.Exists(FilePath)) + { + return null; + } + + var json = await File.ReadAllTextAsync(FilePath, cancellationToken); + var stored = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.KugouDatabaseSetting); + + return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + // 缓存损坏时恢复自动查找。 + return null; + } + finally + { + _lock.Release(); + } + } + + /// 保存数据库路径。 + public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + var setting = new KugouDatabaseSetting { DatabasePath = databasePath }; + await DesktopStateFile.WriteAsync(FilePath, setting, + DesktopStateJsonContext.Default.KugouDatabaseSetting, ownerOnly: false, cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // 缓存写入失败不影响本次使用。 + } + finally + { + _lock.Release(); + } + } + + /// 忘记手动路径,恢复自动查找。 + public async Task ClearAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + if (File.Exists(FilePath)) + { + File.Delete(FilePath); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // 调用方仍可使用本次自动查找结果。 + } + finally + { + _lock.Release(); + } + } +} + +/// 酷狗数据库路径的持久化格式。 +public sealed class KugouDatabaseSetting +{ + /// 数据库的完整路径。 + public string DatabasePath { get; set; } = string.Empty; +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs new file mode 100644 index 0000000..8cb5398 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs @@ -0,0 +1,141 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 持久化网易云登录会话。 +/// 会话属于登录凭据;Unix 文件仅限当前用户读写,Windows 继承目录权限。 +public sealed class NetEaseSessionStore +{ + private const string FileName = "netease.session.json"; + + private readonly SemaphoreSlim _lock = new(1, 1); + + /// 会话文件的完整路径。 + public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); + + /// 是否存在已保存的会话。 + public bool HasStoredSession => File.Exists(FilePath); + + /// 读取会话;文件缺失或损坏时返回空。 + public async Task LoadAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + if (!File.Exists(FilePath)) + { + return null; + } + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(FilePath, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + + var json = await File.ReadAllTextAsync(FilePath, cancellationToken); + var session = JsonSerializer.Deserialize(json, DesktopStateJsonContext.Default.NetEaseSession); + + return string.IsNullOrEmpty(session?.Cookie) ? null : session; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + // 损坏的缓存按未登录处理。 + return null; + } + finally + { + _lock.Release(); + } + } + + /// 保存会话。 + public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + await DesktopStateFile.WriteAsync(FilePath, session, + DesktopStateJsonContext.Default.NetEaseSession, ownerOnly: true, cancellationToken); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // 缓存写入失败不影响本次会话。 + } + finally + { + _lock.Release(); + } + } + + /// 删除已保存的会话。 + public async Task ClearAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + cancellationToken.ThrowIfCancellationRequested(); + File.Delete(FilePath); + } + finally + { + _lock.Release(); + } + } +} + +/// 网易云登录凭据。 +public sealed class NetEaseSession +{ + /// 登录 Cookie。 + public string Cookie { get; set; } = string.Empty; + + /// 请求校验令牌。 + public string CsrfToken { get; set; } = string.Empty; + + /// 会话保存时间,使用 UTC。 + 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(string path, T value, JsonTypeInfo 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); + } + } +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs new file mode 100644 index 0000000..cc63ddf --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs @@ -0,0 +1,39 @@ +using YamlDotNet.Core; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.EventEmitters; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// 将含控制字符的文本输出为单行双引号标量。 +public sealed class QuotedScalarEventEmitter : ChainedEventEmitter +{ + /// 创建标量输出器。 + public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) + { + } + + /// + public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) + { + if (eventInfo.Source.Value is string text && NeedsQuoting(text)) + { + eventInfo.Style = ScalarStyle.DoubleQuoted; + } + + base.Emit(eventInfo, emitter); + } + + private static bool NeedsQuoting(string text) + { + foreach (var c in text) + { + if (c is '\n' or '\r' or '\t' or '"' or '\\') + { + return true; + } + } + + // 保留首尾空格,避免普通标量读取时丢失。 + return text.Length > 0 && (text[0] == ' ' || text[^1] == ' '); + } +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs new file mode 100644 index 0000000..d660504 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs @@ -0,0 +1,439 @@ +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Options; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.RepresentationModel; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; +using ZonyLrcTools.Common.Configuration; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// 只修改界面管理的值,保留其他配置和注释;无法安全修改时返回错误。 +public sealed class SettingsStore : ISettingsStore, IDisposable +{ + private const string RegeneratedHeaderText = "# ZonyLrcTools X 配置文件"; + + private readonly ISerializer _serializer; + private readonly IDeserializer _deserializer; + private readonly SemaphoreSlim _writeLock = new(1, 1); + private bool _disposed; + + /// 使用应用共享配置创建设置存储。 + public SettingsStore(IOptions options) + { + Options = options.Value; + + _serializer = new SerializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) + // 换行符保持双引号转义形式,便于手工编辑。 + .WithEventEmitter(next => new QuotedScalarEventEmitter(next)) + .Build(); + + _deserializer = new DeserializerBuilder() + .WithNamingConvention(CamelCaseNamingConvention.Instance) + .IgnoreUnmatchedProperties() + .Build(); + } + + /// + public GlobalOptions Options { get; } + + /// + public string ConfigFilePath => AppPaths.ConfigFilePath; + + /// + public async Task SaveAsync(CancellationToken cancellationToken = default) + { + await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + var targetPath = ConfigFilePath; + var managed = BuildManagedScalars(Options); + + var text = await TryPatchInPlaceAsync(targetPath, managed, cancellationToken).ConfigureAwait(false) + ?? BuildFromScratch(); + + var directory = Path.GetDirectoryName(targetPath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + // 使用独立临时文件,避免多个进程互相截断写入。 + var tempPath = targetPath + $".{Guid.NewGuid():N}.tmp"; + try + { + await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken) + .ConfigureAwait(false); + cancellationToken.ThrowIfCancellationRequested(); + File.Move(tempPath, targetPath, overwrite: true); + } + finally + { + File.Delete(tempPath); + } + + return SettingsSaveResult.Success(targetPath); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + return SettingsSaveResult.Failure(ex.Message); + } + finally + { + _writeLock.Release(); + } + } + + /// 按 YAML 节点位置修改配置;仅文件不存在时允许重新生成。 + private async Task TryPatchInPlaceAsync( + string path, + IReadOnlyDictionary managed, + CancellationToken cancellationToken = default) + { + if (!File.Exists(path)) + { + return null; + } + + var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + var patched = PatchText(original, managed); + if (!VerifyRoundTrip(patched, managed)) + { + throw new InvalidDataException("无法安全修改配置文件,请检查 YAML 内容。原文件未更改。"); + } + + return patched; + } + + private string BuildFromScratch() + { + // 新文件使用统一的 LF 行尾。 + var body = _serializer.Serialize(Options); + return RegeneratedHeaderText + "\n" + body; + } + + private bool VerifyRoundTrip(string yaml, IReadOnlyDictionary managed) + { + try + { + var parsed = _deserializer.Deserialize(yaml); + if (parsed == null) + { + return false; + } + + foreach (var (key, expected) in managed) + { + if (!string.Equals(ReadScalar(parsed, key), expected, StringComparison.Ordinal)) + { + return false; + } + } + + return true; + } + catch + { + return false; + } + } + + /// 读取反序列化后的受管配置值。 + private static string? ReadScalar(GlobalOptions options, string path) + { + if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal)) + { + var close = path.IndexOf(']'); + if (close < 0) + { + return null; + } + + var name = path["provider.lyric.plugin[".Length..close]; + var leaf = path[(close + 2)..]; + var plugin = options.Provider?.Lyric?.Plugin?.FirstOrDefault(p => p?.Name == name); + if (plugin == null) + { + return null; + } + + return leaf switch + { + "priority" => plugin.Priority.ToString(CultureInfo.InvariantCulture), + "depth" => plugin.Depth.ToString(CultureInfo.InvariantCulture), + "additional.isEnableRomanOutput" => + plugin.Additional != null && plugin.Additional.TryGetValue("isEnableRomanOutput", out var v) + ? Normalize(v) + : null, + _ => null + }; + } + + if (path.StartsWith("provider.tag.plugin[", StringComparison.Ordinal)) + { + var close = path.IndexOf(']'); + if (close < 0) + { + return null; + } + + var name = path["provider.tag.plugin[".Length..close]; + var leaf = path[(close + 2)..]; + var plugin = options.Provider?.Tag?.Plugin?.FirstOrDefault(p => p?.Name == name); + if (plugin == null) + { + return null; + } + + return leaf == "priority" ? plugin.Priority.ToString(CultureInfo.InvariantCulture) : null; + } + + return path switch + { + "networkOptions.isEnable" => Normalize(options.NetworkOptions?.IsEnable), + "networkOptions.ip" => options.NetworkOptions?.Ip, + "networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture), + "provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine), + // 换行符不能去除空白。 + "provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak, + "provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation), + "provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation), + "provider.lyric.config.isSkipExistLyricFiles" => Normalize(options.Provider?.Lyric?.Config?.IsSkipExistLyricFiles), + "provider.lyric.config.fileEncoding" => options.Provider?.Lyric?.Config?.FileEncoding, + "provider.tag.blockWord.isEnable" => Normalize(options.Provider?.Tag?.BlockWord?.IsEnable), + "provider.tag.blockWord.filePath" => options.Provider?.Tag?.BlockWord?.FilePath, + _ => null + }; + } + + /// 统一布尔值的文本形式。 + private static string Normalize(bool value) => value ? "true" : "false"; + + private static string? Normalize(bool? value) => value.HasValue ? Normalize(value.Value) : null; + + private static string Normalize(string? raw) => raw switch + { + null => string.Empty, + "True" => "true", + "False" => "false", + _ => raw + }; + + /// 用解析器的位置替换标量,保留流式映射、注释和未管理的字段。 + private static string PatchText(string original, IReadOnlyDictionary managed) + { + var stream = new YamlStream(); + stream.Load(new StringReader(original)); + if (stream.Documents.Count != 1 || stream.Documents[0].RootNode is not YamlMappingNode root) + { + throw new InvalidDataException("配置必须是单个 YAML 映射文档。"); + } + + var edits = new List<(int Start, int End, string Text)>(); + var additions = new Dictionary>(ReferenceEqualityComparer.Instance); + foreach (var (path, value) in managed) + { + var parts = path.Split('.'); + var current = (YamlNode)root; + for (var i = 0; i < parts.Length; i++) + { + if (!current.Anchor.IsEmpty || current is not YamlMappingNode mapping) + { + throw new InvalidDataException($"无法安全修改带锚点或非映射的配置:{path}"); + } + + var part = parts[i]; + var bracket = part.IndexOf('['); + var key = bracket < 0 ? part : part[..bracket]; + if (!mapping.Children.TryGetValue(new YamlScalarNode(key), out var child)) + { + if (bracket >= 0) + { + throw new InvalidDataException($"配置源已更改,请重新启动应用:{path}"); + } + + if (!additions.TryGetValue(mapping, out var fields)) + { + fields = new Dictionary(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(StringComparer.Ordinal); + fields.Add(parts[j], nested); + } + fields = (Dictionary)nested; + } + fields[parts[^1]] = value; + break; + } + + if (bracket >= 0) + { + var name = part[(bracket + 1)..^1]; + child = (child as YamlSequenceNode)?.Children.OfType() + .SingleOrDefault(item => item.Children.TryGetValue(new YamlScalarNode("name"), out var node) + && node is YamlScalarNode scalar && scalar.Value == name) + ?? throw new InvalidDataException($"找不到配置源:{name}"); + } + + current = child; + if (i != parts.Length - 1) + { + continue; + } + if (child is not YamlScalarNode existing || !child.Anchor.IsEmpty) + { + throw new InvalidDataException($"无法安全修改非标量或带锚点的配置:{path}"); + } + if (existing.Value == value) + { + continue; + } + if (existing.Style is ScalarStyle.Literal or ScalarStyle.Folded) + { + throw new InvalidDataException($"请先将多行配置值改为双引号形式:{path}。原文件未更改。"); + } + + edits.Add(((int)child.Start.Index, (int)child.End.Index, QuoteScalar(value))); + } + } + + var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + foreach (var (mapping, fields) in additions) + { + if (mapping.Style == MappingStyle.Flow) + { + // 在首个键之前插入;空映射则插入到左花括号之后。 + var position = mapping.Children.Count > 0 + ? (int)mapping.Children.First().Key.Start.Index + : (int)mapping.End.Index + 1; + var text = string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")); + edits.Add((position, position, text + (mapping.Children.Count > 0 ? ", " : string.Empty))); + } + else + { + var first = mapping.Children.First().Key; + var indent = new string(' ', (int)first.Start.Column - 1); + var text = string.Join(newline + indent, + fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")); + edits.Add(((int)first.Start.Index, (int)first.Start.Index, text + newline + indent)); + } + } + + var builder = new StringBuilder(original); + var nextStart = original.Length; + foreach (var edit in edits.OrderByDescending(edit => edit.Start)) + { + if (edit.End > nextStart) + { + throw new InvalidDataException("配置包含重叠的 YAML 别名,无法安全修改。"); + } + builder.Remove(edit.Start, edit.End - edit.Start).Insert(edit.Start, edit.Text); + nextStart = edit.Start; + } + return builder.ToString(); + } + + private static string FormatValue(object value) => value is Dictionary fields + ? "{ " + string.Join(", ", fields.Select(pair => $"{QuoteScalar(pair.Key)}: {FormatValue(pair.Value)}")) + " }" + : QuoteScalar((string)value); + + private static string QuoteScalar(string value) => "\"" + value + .Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal) + .Replace("\r", "\\r", StringComparison.Ordinal) + .Replace("\n", "\\n", StringComparison.Ordinal) + .Replace("\t", "\\t", StringComparison.Ordinal) + .Replace("\0", "\\0", StringComparison.Ordinal) + "\""; + + /// 收集设置界面管理的配置路径和值。 + private static Dictionary BuildManagedScalars(GlobalOptions options) + { + var managed = new Dictionary(StringComparer.Ordinal); + + if (options.NetworkOptions != null) + { + managed["networkOptions.isEnable"] = Normalize(options.NetworkOptions.IsEnable); + managed["networkOptions.ip"] = options.NetworkOptions.Ip ?? string.Empty; + managed["networkOptions.port"] = options.NetworkOptions.Port.ToString(CultureInfo.InvariantCulture); + } + + var config = options.Provider?.Lyric?.Config; + if (config != null) + { + managed["provider.lyric.config.isOneLine"] = Normalize(config.IsOneLine); + managed["provider.lyric.config.lineBreak"] = config.LineBreak ?? string.Empty; + managed["provider.lyric.config.isEnableTranslation"] = Normalize(config.IsEnableTranslation); + managed["provider.lyric.config.isOnlyOutputTranslation"] = Normalize(config.IsOnlyOutputTranslation); + managed["provider.lyric.config.isSkipExistLyricFiles"] = Normalize(config.IsSkipExistLyricFiles); + managed["provider.lyric.config.fileEncoding"] = config.FileEncoding ?? string.Empty; + } + + var blockWord = options.Provider?.Tag?.BlockWord; + if (blockWord != null) + { + managed["provider.tag.blockWord.isEnable"] = Normalize(blockWord.IsEnable); + managed["provider.tag.blockWord.filePath"] = blockWord.FilePath ?? string.Empty; + } + + foreach (var plugin in options.Provider?.Lyric?.Plugin ?? []) + { + if (plugin?.Name == null) + { + continue; + } + + var prefix = $"provider.lyric.plugin[{plugin.Name}]"; + managed[$"{prefix}.priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture); + managed[$"{prefix}.depth"] = plugin.Depth.ToString(CultureInfo.InvariantCulture); + + if (plugin.Additional != null && + plugin.Additional.TryGetValue("isEnableRomanOutput", out var roman)) + { + managed[$"{prefix}.additional.isEnableRomanOutput"] = Normalize(roman); + } + } + + foreach (var plugin in options.Provider?.Tag?.Plugin ?? []) + { + if (plugin?.Name == null) + { + continue; + } + + managed[$"provider.tag.plugin[{plugin.Name}].priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture); + } + + return managed; + } + + /// 释放写入锁。 + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _writeLock.Dispose(); + } +} diff --git a/src/ZonyLrcTools.Desktop/Resources/UIStrings.en-US.resx b/src/ZonyLrcTools.Desktop/Resources/UIStrings.en-US.resx index 7af86e1..3b16b42 100644 --- a/src/ZonyLrcTools.Desktop/Resources/UIStrings.en-US.resx +++ b/src/ZonyLrcTools.Desktop/Resources/UIStrings.en-US.resx @@ -79,10 +79,10 @@ Music Folder - Select a folder containing music files... + Select a folder containing music files… - Browse... + Browse… Parallel Tasks @@ -100,10 +100,10 @@ Idle - Scanning files... + Scanning files… - Downloading lyrics... + Downloading lyrics… Download Complete @@ -134,10 +134,10 @@ Music Folder - Select a folder containing music files... + Select a folder containing music files… - Browse... + Browse… Parallel Tasks @@ -258,4 +258,263 @@ No music files found in the selected folder. + + + Music Decryption + + + Music Decryption + + + Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats + + + Select encrypted music files… + + + Add Files… + + + Parallel: + + + Start Decrypt + + + Stop + + + No files yet, add files to start decrypting + + + Clear + + + Files + + + File Name + + + Output + + + Basic Settings + + + Advanced Settings + + + Show advanced settings + + + Lyrics Settings + + + Enable translation lyrics + + + One-line mode (original + translation on the same line) + + + Only output translation lyrics + + + Skip existing lyrics files + + + File Encoding: + + + Line Break: + + + Output romanized lyrics + + + Block Words + + + Enable block word filtering + + + Block Words File (relative to current working directory): + + + Tag Providers + + + Priority + + + Configuration File + + + Settings saved + + + Failed to save settings + + + Restart the application for proxy changes to take effect. + + + Reset all settings to their default values? + + + Quick Actions + + + Decrypt Music + + + Supports NetEase, QQ Music, KuGou and KuWo lyric sources + + + Parallel downloads with automatic overwrite protection + + + Multiple file encodings and translated lyrics output + + + Runs on Windows, Linux and macOS + + + Get Started + + + Source + + + Local Folder + + + CSV File + + + NetEase Playlist + + + Scan + + + CSV File + + + Select a CSV file… + + + Choose… + + + Playlist ID + + + e.g. 7224428149 (separate multiple ids with ;) + + + Save To + + + Where the .lrc files should be written + + + Choose… + + + Sign in to NetEase Cloud Music + + + Scan the QR code with the NetEase Cloud Music app on your phone. + + + Waiting for you to scan… + + + Scanned, please confirm on your phone. + + + Signed in. + + + The QR code expired. Close this dialog and try again. + + + Login did not complete. Close this dialog and try again. + + + Features + + + Version + + + Batch download lyrics for your music files + + + Fetch album artwork for your collection + + + Decrypt protected music files + + + Move up + + + Move down + + + kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song) + + + Choose Database… + + + {0} decryption keys loaded + + + KuGou database not found, kgg files cannot be decrypted + + + Locate Database… + + + KuGou database missing + + + View details + + + Decryption failure + + + The list order is the search order. Use the arrows on the right to change which source is tried first. + + + Sign out + + + Forget the saved session so the next playlist scan asks for a QR login again. + + + Signed out. The next playlist scan will ask for a QR login. + + + Sign in… + + + Scan a QR code now instead of waiting until the next scan. + + + Signed in. Scanning a playlist reuses this session. + + + Not signed in. Scanning a playlist will show a QR code. + + + Account + + + Copy + diff --git a/src/ZonyLrcTools.Desktop/Resources/UIStrings.resx b/src/ZonyLrcTools.Desktop/Resources/UIStrings.resx index b07f28e..ddb58ad 100644 --- a/src/ZonyLrcTools.Desktop/Resources/UIStrings.resx +++ b/src/ZonyLrcTools.Desktop/Resources/UIStrings.resx @@ -79,10 +79,10 @@ 音乐文件夹 - 请选择包含音乐文件的目录... + 请选择包含音乐文件的目录… - 浏览... + 浏览… 并行任务数 @@ -100,10 +100,10 @@ 等待中 - 正在扫描文件... + 正在扫描文件… - 正在下载歌词... + 正在下载歌词… 下载完成 @@ -134,10 +134,10 @@ 音乐文件夹 - 请选择包含音乐文件的目录... + 请选择包含音乐文件的目录… - 浏览... + 浏览… 并行任务数 @@ -258,4 +258,263 @@ 在所选文件夹中没有找到任何音乐文件。 + + + 音乐解密 + + + 音乐解密 + + + 将加密的音乐文件(ncm / qmc / kgm / kgg / kwm)转换为可播放格式 + + + 请选择要解密的加密音乐文件… + + + 添加文件… + + + 并行数: + + + 开始解密 + + + 停止 + + + 暂无文件,请添加文件后开始解密 + + + 清空 + + + 文件 + + + 文件名 + + + 输出路径 + + + 基础设置 + + + 高级设置 + + + 显示高级设置 + + + 歌词设置 + + + 启用翻译歌词 + + + 单行模式(原文与翻译在同一行) + + + 只输出翻译歌词 + + + 跳过已存在的歌词文件 + + + 文件编码: + + + 换行符: + + + 输出罗马音歌词 + + + 屏蔽词 + + + 启用屏蔽词过滤 + + + 屏蔽词文件路径(相对当前工作目录): + + + 标签源 + + + 优先级 + + + 配置文件位置 + + + 设置已保存 + + + 设置保存失败 + + + 修改代理设置后需要重启程序才能生效。 + + + 确定要将所有设置恢复为默认值吗? + + + 快速操作 + + + 解密音乐 + + + 支持网易云、QQ音乐、酷狗、酷我四大歌词源 + + + 多线程并行下载,自动规避覆盖 + + + 支持多种文件编码与翻译歌词输出 + + + 跨平台运行,支持 Windows、Linux 与 macOS + + + 开始使用 + + + 来源 + + + 本地文件夹 + + + CSV 文件 + + + 网易云歌单 + + + 解析 + + + CSV 文件 + + + 请选择 CSV 文件… + + + 选择… + + + 歌单 ID + + + 例如 7224428149(多个歌单用分号分隔) + + + 保存到 + + + 歌词文件的输出目录 + + + 选择… + + + 登录网易云音乐 + + + 请使用手机上的网易云音乐 App 扫描二维码。 + + + 等待扫码… + + + 已扫码,请在手机上确认。 + + + 登录成功。 + + + 二维码已过期,请关闭窗口后重新登录。 + + + 登录未完成,请关闭窗口后重试。 + + + 功能特性 + + + 版本 + + + 批量下载音乐文件的歌词 + + + 为音乐库获取专辑封面 + + + 解密受保护的音乐文件 + + + 上移 + + + 下移 + + + kgg 解密需要酷狗数据库 KGMusicV3.db(酷狗下载过该歌曲才会写入密钥) + + + 选择数据库文件… + + + 已读取 {0} 个解密密钥 + + + 未找到酷狗数据库,kgg 文件将无法解密 + + + 指定数据库… + + + 缺少酷狗数据库 + + + 查看详情 + + + 解密失败原因 + + + 列表顺序即搜索顺序,用右侧箭头调整优先尝试哪一家。 + + + 退出登录 + + + 清除已保存的登录状态,下次解析歌单需要重新扫码。 + + + 已退出登录,下次解析歌单需要重新扫码。 + + + 登录… + + + 立即扫码登录,不必等到下次解析歌单。 + + + 已登录,解析歌单会直接使用这个会话。 + + + 未登录,解析歌单时会弹出二维码。 + + + 账号状态 + + + 复制 + diff --git a/src/ZonyLrcTools.Desktop/Services/DialogService.cs b/src/ZonyLrcTools.Desktop/Services/DialogService.cs index 9e3706e..284fdf2 100644 --- a/src/ZonyLrcTools.Desktop/Services/DialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/DialogService.cs @@ -2,6 +2,8 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform.Storage; +using Avalonia.Threading; +using ZonyLrcTools.Desktop.ViewModels; using ZonyLrcTools.Desktop.Views.Dialogs; namespace ZonyLrcTools.Desktop.Services; @@ -23,27 +25,77 @@ public class DialogService : IDialogService AllowMultiple = false }); - return folders.FirstOrDefault()?.Path.LocalPath; + return folders.FirstOrDefault()?.TryGetLocalPath(); } public async Task ShowFilePickerAsync(string title, string[]? filters = null) { if (MainWindow == null) return null; - var fileTypes = filters?.Select(f => new FilePickerFileType(f) - { - Patterns = new[] { f } - }).ToList(); - var files = await MainWindow.StorageProvider.OpenFilePickerAsync( new FilePickerOpenOptions { Title = title, AllowMultiple = false, - FileTypeFilter = fileTypes + FileTypeFilter = BuildFileTypes(filters) }); - return files.FirstOrDefault()?.Path.LocalPath; + return files.FirstOrDefault()?.TryGetLocalPath(); + } + + /// + public async Task> ShowFilesPickerAsync(string title, string[]? filters = null, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (MainWindow == null) return Array.Empty(); + + var fileTypes = BuildFileTypes(filters); + + var files = await MainWindow.StorageProvider.OpenFilePickerAsync( + new FilePickerOpenOptions + { + Title = title, + AllowMultiple = true, + FileTypeFilter = fileTypes + }); + cancellationToken.ThrowIfCancellationRequested(); + + return files + .Select(f => f.TryGetLocalPath()) + .OfType() + .Where(p => !string.IsNullOrEmpty(p)) + .ToList(); + } + + /// + /// 将文件扩展名转换为文件选择器筛选条件。 + /// + private static List? BuildFileTypes(string[]? filters) + { + if (filters == null || filters.Length == 0) + { + return null; + } + + var patterns = filters + .Where(f => !string.IsNullOrWhiteSpace(f)) + .Select(f => f.StartsWith('*') ? f : $"*.{f.TrimStart('.')}") + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + if (patterns.Length == 0) + { + return null; + } + + var name = string.Join(" / ", patterns.Select(p => p.TrimStart('*', '.'))); + + return new List + { + new(name) { Patterns = patterns }, + new("All files") { Patterns = new[] { "*" } } + }; } public async Task ShowConfirmDialogAsync(string title, string message) @@ -62,4 +114,20 @@ public class DialogService : IDialogService var dialog = new MessageDialog(title, message); await dialog.ShowDialog(MainWindow); } + + /// + public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (MainWindow == null) + { + viewModel.NotifyClosed(); + return; + } + + var dialog = new QrCodeLoginDialog(viewModel); + using var registration = cancellationToken.Register( + () => Dispatcher.UIThread.Post(viewModel.RequestClose)); + await dialog.ShowDialog(MainWindow); + } } diff --git a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs index 0428216..d562881 100644 --- a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs @@ -1,9 +1,25 @@ +using ZonyLrcTools.Desktop.ViewModels; + namespace ZonyLrcTools.Desktop.Services; public interface IDialogService { Task ShowFolderPickerAsync(string title); + Task ShowFilePickerAsync(string title, string[]? filters = null); + + /// + /// 选择多个本地文件。 + /// + Task> ShowFilesPickerAsync(string title, string[]? filters = null, + CancellationToken cancellationToken = default); + Task ShowConfirmDialogAsync(string title, string message); + Task ShowMessageAsync(string title, string message); + + /// + /// 显示网易云扫码登录对话框,关闭窗口后返回。 + /// + Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel, CancellationToken cancellationToken = default); } diff --git a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs index f3697f0..52b1405 100644 --- a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs @@ -7,7 +7,16 @@ public interface INavigationService ViewModelBase? CurrentViewModel { get; } event EventHandler? NavigationChanged; + /// + /// 打开页面并保留返回记录。 + /// TViewModel NavigateTo() where TViewModel : ViewModelBase; + + /// + /// 切换顶层页面并清空返回记录。 + /// + TViewModel NavigateRoot() where TViewModel : ViewModelBase; + void GoBack(); bool CanGoBack { get; } } diff --git a/src/ZonyLrcTools.Desktop/Services/NavigationService.cs b/src/ZonyLrcTools.Desktop/Services/NavigationService.cs index 57fa5e2..5836f65 100644 --- a/src/ZonyLrcTools.Desktop/Services/NavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/NavigationService.cs @@ -22,13 +22,44 @@ public class NavigationService : INavigationService { var viewModel = _serviceProvider.GetRequiredService(); - if (_navigationStack.TryPeek(out var current)) + if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel)) { - _ = current.OnDeactivatedAsync(); + // 当前页面无需重复激活。 + return viewModel; + } + + if (_navigationStack.TryPeek(out current)) + { + _ = SafeDeactivateAsync(current); } _navigationStack.Push(viewModel); - _ = viewModel.OnActivatedAsync(); + _ = SafeActivateAsync(viewModel); + + NavigationChanged?.Invoke(this, viewModel); + return viewModel; + } + + /// + public TViewModel NavigateRoot() where TViewModel : ViewModelBase + { + var viewModel = _serviceProvider.GetRequiredService(); + + if (_navigationStack.Count == 1 && ReferenceEquals(_navigationStack.Peek(), viewModel)) + { + return viewModel; + } + + while (_navigationStack.TryPop(out var previous)) + { + if (!ReferenceEquals(previous, viewModel)) + { + _ = SafeDeactivateAsync(previous); + } + } + + _navigationStack.Push(viewModel); + _ = SafeActivateAsync(viewModel); NavigationChanged?.Invoke(this, viewModel); return viewModel; @@ -39,12 +70,39 @@ public class NavigationService : INavigationService if (!CanGoBack) return; var current = _navigationStack.Pop(); - _ = current.OnDeactivatedAsync(); + _ = SafeDeactivateAsync(current); if (_navigationStack.TryPeek(out var previous)) { - _ = previous.OnActivatedAsync(); + _ = SafeActivateAsync(previous); NavigationChanged?.Invoke(this, previous); } } + + /// + /// 页面激活失败时不打断导航。 + /// + private static async Task SafeActivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnActivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // 页面自行处理错误,避免中断导航。 + } + } + + private static async Task SafeDeactivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnDeactivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // 页面自行处理错误,避免中断导航。 + } + } } diff --git a/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs b/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs index 7f42578..d729430 100644 --- a/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs +++ b/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.Logging; using ZonyLrcTools.Common.Infrastructure.Network; +using ZonyLrcTools.Desktop.Infrastructure.Configuration; using ZonyLrcTools.Desktop.Infrastructure.Localization; using ZonyLrcTools.Desktop.ViewModels; @@ -20,7 +21,8 @@ public static class ServiceCollectionExtensions services.BeginAutoDependencyInject(); // Configure Common services - services.ConfigureConfiguration(); + // 桌面端使用可写的配置目录,避免只读安装位置导致保存失败。 + services.ConfigureDesktopConfiguration(); services.ConfigureLocalization(); services.ConfigureToolService(); @@ -39,11 +41,18 @@ public static class ServiceCollectionExtensions services.AddSingleton(); services.AddSingleton(); + // 保存网易云登录状态。 + services.AddSingleton(); + + // 保存本机酷狗数据库路径。 + services.AddSingleton(); + // Register ViewModels (Singleton to preserve state across navigation) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); return services; diff --git a/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs index 6e2b6a7..405a758 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs @@ -1,7 +1,14 @@ using System.Collections.ObjectModel; +using Avalonia.Threading; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Options; +using ZonyLrcTools.Common; using ZonyLrcTools.Common.Album; +using ZonyLrcTools.Common.Configuration; +using ZonyLrcTools.Common.Infrastructure.IO; +using ZonyLrcTools.Common.Infrastructure.Threading; +using ZonyLrcTools.Common.TagInfo; using ZonyLrcTools.Desktop.Infrastructure.Localization; using ZonyLrcTools.Desktop.Services; @@ -11,9 +18,14 @@ public partial class AlbumDownloadViewModel : ViewModelBase { private readonly IAlbumDownloader _albumDownloader; private readonly IDialogService _dialogService; + private readonly IFileScanner _fileScanner; + private readonly ITagLoader _tagLoader; + private readonly GlobalOptions _options; private readonly IUILocalizationService? _localization; private CancellationTokenSource? _downloadCts; + private readonly Dictionary _musicFileMap = new(); + private readonly List _scannedMusicInfos = new(); [ObservableProperty] private string? _selectedFolderPath; @@ -34,9 +46,26 @@ public partial class AlbumDownloadViewModel : ViewModelBase private double _progressPercentage; [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] [NotifyPropertyChangedFor(nameof(CanStartDownload))] private bool _isDownloading; + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] + [NotifyPropertyChangedFor(nameof(CanStartDownload))] + private bool _isScanning; + + [ObservableProperty] + private int _scanProgressCount; + + [ObservableProperty] + private int _scanTotalCount; + + [ObservableProperty] + private double _scanProgressPercentage; + // Localized strings public string AlbumTitle => _localization?["Album_Title"] ?? "Album Cover Download"; public string AlbumDescription => _localization?["Album_Description"] ?? "Download album artwork for your music collection"; @@ -46,6 +75,8 @@ public partial class AlbumDownloadViewModel : ViewModelBase public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:"; public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download"; public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download"; + /// 扫描进度提示。 + public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files..."; public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; public string CommonFiles => _localization?["Common_Files"] ?? "files"; public string CommonSuccess => _localization?["Common_Success"] ?? "Success:"; @@ -54,21 +85,27 @@ public partial class AlbumDownloadViewModel : ViewModelBase public string ColumnArtist => _localization?["Column_Artist"] ?? "Artist"; public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; - public bool CanStartDownload => !IsDownloading && !string.IsNullOrEmpty(SelectedFolderPath); + public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0; public bool HasNoFiles => MusicFiles.Count == 0; public string EmptyStateText => _localization?["Album_EmptyState"] ?? "No tasks yet, please select a folder to start scanning"; - public ObservableCollection MusicFiles { get; } = new(); + public ObservableCollection MusicFiles { get; } = new(); public AlbumDownloadViewModel( IAlbumDownloader albumDownloader, IDialogService dialogService, + IFileScanner fileScanner, + ITagLoader tagLoader, + IOptions options, IUILocalizationService? localization = null) { _albumDownloader = albumDownloader; _dialogService = dialogService; + _fileScanner = fileScanner; + _tagLoader = tagLoader; + _options = options.Value; _localization = localization; if (_localization != null) @@ -79,6 +116,8 @@ public partial class AlbumDownloadViewModel : ViewModelBase MusicFiles.CollectionChanged += (_, _) => { OnPropertyChanged(nameof(HasNoFiles)); + OnPropertyChanged(nameof(CanStartDownload)); + StartDownloadCommand.NotifyCanExecuteChanged(); }; } @@ -92,6 +131,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(AlbumParallel)); OnPropertyChanged(nameof(AlbumStartDownload)); OnPropertyChanged(nameof(AlbumStopDownload)); + OnPropertyChanged(nameof(AlbumScanning)); OnPropertyChanged(nameof(CommonTotal)); OnPropertyChanged(nameof(CommonFiles)); OnPropertyChanged(nameof(CommonSuccess)); @@ -102,36 +142,162 @@ public partial class AlbumDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(EmptyStateText)); } - [RelayCommand] - private async Task SelectFolderAsync() + [RelayCommand(CanExecute = nameof(CanSelectFolder))] + private async Task SelectFolderAsync(CancellationToken cancellationToken = default) { - var folder = await _dialogService.ShowFolderPickerAsync("Select Music Folder"); + var folder = await _dialogService.ShowFolderPickerAsync( + _localization?["Album_SelectFolder"] ?? "Select Music Folder"); + cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(folder)) return; SelectedFolderPath = folder; - OnPropertyChanged(nameof(CanStartDownload)); + await ScanFilesAsync(cancellationToken); } - [RelayCommand] - private async Task StartDownloadAsync() + private bool CanSelectFolder => !IsScanning && !IsDownloading; + + /// + /// 扫描文件并读取音乐标签。 + /// + private async Task ScanFilesAsync(CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(SelectedFolderPath)) return; + IsScanning = true; + MusicFiles.Clear(); + _musicFileMap.Clear(); + _scannedMusicInfos.Clear(); + ScanProgressCount = 0; + ScanTotalCount = 0; + ScanProgressPercentage = 0; + TotalCount = 0; + CompletedCount = 0; + FailedCount = 0; + ProgressPercentage = 0; + + try + { + var files = (await Task.Run( + () => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions), + cancellationToken)).ToList(); + + if (files.Count == 0) + { + await _dialogService.ShowMessageAsync( + _localization?["Common_Info"] ?? "Info", + _localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder."); + return; + } + + ScanTotalCount = files.Count; + + using var warpTask = new WarpTask(ParallelCount); + var scanTasks = files.Select(file => + warpTask.RunAsync(async () => + { + var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken); + + await Dispatcher.UIThread.InvokeAsync(() => + { + if (musicInfo != null && + (!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist))) + { + var vm = new AlbumFileViewModel + { + FilePath = musicInfo.FilePath, + Name = musicInfo.Name, + Artist = musicInfo.Artist, + StatusMessage = _localization?["Status_Pending"] ?? "Pending" + }; + MusicFiles.Add(vm); + _musicFileMap[musicInfo.FilePath] = vm; + _scannedMusicInfos.Add(musicInfo); + } + + ScanProgressCount++; + ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount; + }); + }, cancellationToken)); + + await Task.WhenAll(scanTasks); + + TotalCount = MusicFiles.Count; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消扫描。 + } + catch (Exception ex) + { + await _dialogService.ShowMessageAsync( + _localization?["Common_Error"] ?? "Error", + ex.Message); + } + finally + { + IsScanning = false; + OnPropertyChanged(nameof(CanStartDownload)); + } + } + + [RelayCommand(CanExecute = nameof(CanStartDownload))] + private async Task StartDownloadAsync(CancellationToken cancellationToken = default) + { + if (_scannedMusicInfos.Count == 0) return; + IsDownloading = true; CompletedCount = 0; FailedCount = 0; ProgressPercentage = 0; + TotalCount = _scannedMusicInfos.Count; - _downloadCts = new CancellationTokenSource(); + foreach (var vm in MusicFiles) + { + vm.IsProcessed = false; + vm.IsSuccessful = false; + vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; + } + + _downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); try { - // TODO: Implement actual download logic using _albumDownloader - await Task.Delay(1000, _downloadCts.Token); // Placeholder + await _albumDownloader.DownloadAsync( + _scannedMusicInfos, + ParallelCount, + async musicInfo => + { + await Dispatcher.UIThread.InvokeAsync(() => + { + if (_musicFileMap.TryGetValue(musicInfo.FilePath, out var vm)) + { + vm.IsProcessed = true; + vm.IsSuccessful = musicInfo.IsSuccessful; + vm.StatusMessage = musicInfo.IsSuccessful + ? _localization?["Status_Success"] ?? "Success" + : _localization?["Status_Failed"] ?? "Failed"; + } + + if (musicInfo.IsSuccessful) + CompletedCount++; + else + FailedCount++; + + var done = CompletedCount + FailedCount; + ProgressPercentage = done * 100.0 / TotalCount; + }); + }, + _downloadCts.Token); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested) { - // User cancelled + // 用户取消下载。 + } + catch (Exception ex) + { + await _dialogService.ShowMessageAsync( + _localization?["Common_Error"] ?? "Error", + ex.Message); } finally { @@ -147,3 +313,27 @@ public partial class AlbumDownloadViewModel : ViewModelBase _downloadCts?.Cancel(); } } + +/// +/// 单个音乐文件的封面下载状态。 +/// +public partial class AlbumFileViewModel : ObservableObject +{ + [ObservableProperty] + private string _filePath = string.Empty; + + [ObservableProperty] + private string _name = string.Empty; + + [ObservableProperty] + private string _artist = string.Empty; + + [ObservableProperty] + private bool _isProcessed; + + [ObservableProperty] + private bool _isSuccessful; + + [ObservableProperty] + private string? _statusMessage; +} diff --git a/src/ZonyLrcTools.Desktop/ViewModels/DecryptViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/DecryptViewModel.cs new file mode 100644 index 0000000..0dd5aba --- /dev/null +++ b/src/ZonyLrcTools.Desktop/ViewModels/DecryptViewModel.cs @@ -0,0 +1,572 @@ +using System.Collections.ObjectModel; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using ZonyLrcTools.Common.Infrastructure.Threading; +using ZonyLrcTools.Common.MusicDecryption; +using ZonyLrcTools.Desktop.Infrastructure.Configuration; +using ZonyLrcTools.Desktop.Infrastructure.Localization; +using ZonyLrcTools.Desktop.Services; + +namespace ZonyLrcTools.Desktop.ViewModels; + +/// +/// 音乐文件解密页面。 +/// +public partial class DecryptViewModel : ViewModelBase +{ + private const string KggExtension = ".kgg"; + + private readonly IMusicDecryptor _musicDecryptor; + private readonly IDialogService _dialogService; + private readonly IUILocalizationService? _localization; + private readonly IKugouKeyProvider? _kugouKeyProvider; + private readonly KugouDatabaseStore? _kugouDatabaseStore; + + private CancellationTokenSource? _decryptCts; + private bool _isInitialized; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))] + [NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))] + [NotifyPropertyChangedFor(nameof(CanStartDecrypt))] + private bool _isInitializing; + + [ObservableProperty] + private int _parallelCount = 2; + + [ObservableProperty] + private int _totalCount; + + [ObservableProperty] + private int _completedCount; + + [ObservableProperty] + private int _failedCount; + + [ObservableProperty] + private double _progressPercentage; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))] + [NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))] + [NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))] + [NotifyPropertyChangedFor(nameof(CanStartDecrypt))] + [NotifyPropertyChangedFor(nameof(CanClear))] + private bool _isDecrypting; + + /// + /// 是否可以读取酷狗解密密钥数据库。 + /// + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))] + private bool _isKugouDatabaseAvailable; + + [ObservableProperty] + private string _kugouDatabaseStatus = string.Empty; + + // 界面文案。 + /// 页面标题。 + public string DecryptTitle => _localization?["Decrypt_Title"] ?? "Music Decryption"; + /// 页面说明。 + public string DecryptDescription => _localization?["Decrypt_Description"] ?? "Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats"; + /// 文件选择提示。 + public string DecryptSelectFiles => _localization?["Decrypt_SelectFiles"] ?? "Select encrypted music files..."; + /// 添加文件按钮文案。 + public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files..."; + /// 并行任务数标签。 + public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:"; + /// 开始解密按钮文案。 + public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt"; + /// 停止按钮文案。 + public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop"; + /// 文件列表为空时的提示。 + public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting"; + /// 清空按钮文案。 + public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear"; + /// 文件列表标签。 + public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files"; + /// 选择数据库按钮文案。 + public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db..."; + /// 数据库缺失状态文案。 + public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing"; + /// 查看详情按钮文案。 + public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details"; + /// 失败详情窗口标题。 + public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure"; + + /// + /// 酷狗数据库缺失时的提示。 + /// + public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"] + ?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)"; + + /// 是否显示数据库缺失提示。 + public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable; + + /// + /// 已选文件数量。 + /// + public string SelectionSummary => Files.Count == 0 + ? string.Empty + : $"{Files.Count} {CommonFiles}"; + + /// 总数标签。 + public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; + /// 文件数量单位。 + public string CommonFiles => _localization?["Common_Files"] ?? "files"; + /// 成功数量标签。 + public string CommonSuccess => _localization?["Common_Success"] ?? "Success:"; + /// 失败数量标签。 + public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:"; + /// 文件名列标题。 + public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name"; + /// 输出路径列标题。 + public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output"; + /// 状态列标题。 + public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; + + /// 是否存在可以开始解密的文件。 + public bool CanStartDecrypt => !IsDecrypting && !IsInitializing && Files.Any(f => !f.IsBlocked); + /// 文件列表是否为空。 + public bool HasNoFiles => Files.Count == 0; + + /// 待解密文件列表。 + public ObservableCollection Files { get; } = new(); + + /// + /// 创建音乐解密页面。 + /// + public DecryptViewModel( + IMusicDecryptor musicDecryptor, + IDialogService dialogService, + IUILocalizationService? localization = null, + IKugouKeyProvider? kugouKeyProvider = null, + KugouDatabaseStore? kugouDatabaseStore = null) + { + _musicDecryptor = musicDecryptor; + _dialogService = dialogService; + _localization = localization; + _kugouKeyProvider = kugouKeyProvider; + _kugouDatabaseStore = kugouDatabaseStore; + + if (_localization != null) + { + _localization.LanguageChanged += OnLanguageChanged; + } + + Files.CollectionChanged += (_, _) => + { + OnPropertyChanged(nameof(HasNoFiles)); + OnPropertyChanged(nameof(CanStartDecrypt)); + OnPropertyChanged(nameof(SelectionSummary)); + OnPropertyChanged(nameof(CanClear)); + StartDecryptCommand.NotifyCanExecuteChanged(); + ClearFilesCommand.NotifyCanExecuteChanged(); + }; + } + + /// + /// 恢复已保存的数据库路径并刷新文件状态。 + /// + public override async Task OnActivatedAsync() + { + if (IsDecrypting || IsInitializing) return; + + if (!_isInitialized) + { + await InitializeAsync(); + return; + } + + RefreshDatabaseStatus(); + } + + /// + /// 初始化酷狗数据库路径。 + /// + public async Task InitializeAsync(CancellationToken cancellationToken = default) + { + if (IsInitializing) return; + + IsInitializing = true; + try + { + if (_kugouDatabaseStore != null && _kugouKeyProvider != null) + { + var stored = await _kugouDatabaseStore.LoadAsync(cancellationToken); + if (!string.IsNullOrWhiteSpace(stored)) + { + _kugouKeyProvider.SetDatabasePath(stored); + } + } + + RefreshDatabaseStatus(); + _isInitialized = true; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消初始化,下次进入页面时重试。 + } + catch (Exception ex) + { + await _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", ex.Message); + } + finally + { + IsInitializing = false; + } + } + + private void RefreshDatabaseStatus() + { + if (_kugouKeyProvider == null) + { + // 未注册密钥提供者时,由解密器报告具体错误。 + IsKugouDatabaseAvailable = true; + KugouDatabaseStatus = string.Empty; + return; + } + + var info = _kugouKeyProvider.Probe(); + IsKugouDatabaseAvailable = info.IsAvailable; + KugouDatabaseStatus = info.Message; + + // 数据库可用后解除未处理文件的阻止状态。 + foreach (var file in Files) + { + if (!IsKggFile(file.FilePath)) continue; + + if (info.IsAvailable && file.IsBlocked) + { + file.IsBlocked = false; + file.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; + } + else if (!info.IsAvailable && !file.IsProcessed) + { + file.IsBlocked = true; + file.StatusMessage = DecryptStatusMissingDb; + } + } + + OnPropertyChanged(nameof(CanStartDecrypt)); + StartDecryptCommand.NotifyCanExecuteChanged(); + } + + /// + /// 判断某个文件是否依赖酷狗数据库才能解密。 + /// + /// 优先按魔数判断(改名成 .mp3 的 kgg 也能被识别),没有 provider 时退回扩展名。 + /// 这样「能不能解密」的判断和 Common 里的解密器是同一套口径。 + /// + /// + private bool IsKggFile(string path) + { + if (_kugouKeyProvider != null) + { + return _kugouKeyProvider.IsKggFile(path); + } + + return string.Equals(Path.GetExtension(path), KggExtension, StringComparison.OrdinalIgnoreCase); + } + + private void OnLanguageChanged(object? sender, EventArgs e) + { + OnPropertyChanged(nameof(DecryptTitle)); + OnPropertyChanged(nameof(DecryptDescription)); + OnPropertyChanged(nameof(DecryptSelectFiles)); + OnPropertyChanged(nameof(DecryptBrowse)); + OnPropertyChanged(nameof(DecryptParallel)); + OnPropertyChanged(nameof(DecryptStart)); + OnPropertyChanged(nameof(DecryptStop)); + OnPropertyChanged(nameof(DecryptEmptyState)); + OnPropertyChanged(nameof(DecryptClear)); + OnPropertyChanged(nameof(DecryptFilesLabel)); + OnPropertyChanged(nameof(DecryptSpecifyDatabase)); + OnPropertyChanged(nameof(DecryptStatusMissingDb)); + OnPropertyChanged(nameof(DecryptViewDetail)); + OnPropertyChanged(nameof(DecryptFailureTitle)); + OnPropertyChanged(nameof(DecryptKugouRequirement)); + OnPropertyChanged(nameof(SelectionSummary)); + OnPropertyChanged(nameof(CommonTotal)); + OnPropertyChanged(nameof(CommonFiles)); + OnPropertyChanged(nameof(CommonSuccess)); + OnPropertyChanged(nameof(CommonFailed)); + OnPropertyChanged(nameof(ColumnFileName)); + OnPropertyChanged(nameof(ColumnOutputPath)); + OnPropertyChanged(nameof(ColumnStatus)); + + foreach (var file in Files) + { + file.ViewDetailLabel = DecryptViewDetail; + file.StatusMessage = file.IsBlocked + ? DecryptStatusMissingDb + : file.IsProcessed + ? file.IsSuccessful + ? _localization?["Status_Success"] ?? "Success" + : _localization?["Status_Failed"] ?? "Failed" + : _localization?["Status_Pending"] ?? "Pending"; + } + } + + [RelayCommand(CanExecute = nameof(CanSelectFiles))] + private async Task SelectFilesAsync(CancellationToken cancellationToken = default) + { + var picked = await _dialogService.ShowFilesPickerAsync( + DecryptSelectFiles, + [".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm"], + cancellationToken); + if (picked.Count == 0) return; + + // 同一批文件只检查一次数据库。 + RefreshDatabaseStatus(); + + foreach (var path in picked) + { + // 避免重复添加同一文件。 + if (Files.Any(f => string.Equals(f.FilePath, path, StringComparison.OrdinalIgnoreCase))) + { + continue; + } + + var isBlocked = IsKggFile(path) && !IsKugouDatabaseAvailable; + + var row = new DecryptFileViewModel + { + FilePath = path, + FileName = Path.GetFileName(path), + StatusMessage = isBlocked + ? DecryptStatusMissingDb + : _localization?["Status_Pending"] ?? "Pending", + IsBlocked = isBlocked, + ViewDetailLabel = DecryptViewDetail + }; + + row.ShowDetailCommand = new AsyncRelayCommand(token => ShowDetailAsync(row, token)); + Files.Add(row); + } + + TotalCount = Files.Count; + OnPropertyChanged(nameof(CanStartDecrypt)); + } + + private bool CanSelectFiles => !IsDecrypting && !IsInitializing; + + [RelayCommand(CanExecute = nameof(CanSelectFiles))] + private async Task SpecifyDatabaseAsync(CancellationToken cancellationToken = default) + { + var picked = await _dialogService.ShowFilePickerAsync( + DecryptSpecifyDatabase, + new[] { ".db" }); + cancellationToken.ThrowIfCancellationRequested(); + + if (string.IsNullOrWhiteSpace(picked)) + { + return; + } + + _kugouKeyProvider?.SetDatabasePath(picked); + RefreshDatabaseStatus(); + + if (_kugouDatabaseStore != null) + { + await _kugouDatabaseStore.SaveAsync(picked, cancellationToken); + } + } + + [RelayCommand(CanExecute = nameof(CanStartDecrypt))] + private async Task StartDecryptAsync(CancellationToken cancellationToken = default) + { + if (Files.Count == 0) return; + // 缺少密钥数据库的文件不加入本次任务。 + var runnable = Files.Where(f => !f.IsBlocked).ToList(); + + IsDecrypting = true; + CompletedCount = 0; + FailedCount = 0; + ProgressPercentage = 0; + TotalCount = runnable.Count; + + foreach (var file in Files) + { + file.IsProcessed = false; + file.IsSuccessful = false; + file.OutputPath = null; + file.ErrorDetail = null; + + if (!file.IsBlocked) + { + file.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; + } + } + + if (runnable.Count == 0) + { + IsDecrypting = false; + return; + } + + _decryptCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var token = _decryptCts.Token; + + try + { + var parallel = ParallelCount <= 0 ? 1 : ParallelCount; + + using var warpTask = new WarpTask(parallel); + + var tasks = runnable.Select(file => warpTask.RunAsync(async () => + { + token.ThrowIfCancellationRequested(); + + DecryptionResult result; + try + { + result = await Task.Run(() => _musicDecryptor.ConvertMusicAsync(file.FilePath, token), token); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + result = DecryptionResult.Failed(ex.Message); + } + + await Dispatcher.UIThread.InvokeAsync(() => + { + file.IsProcessed = true; + file.IsSuccessful = result.IsSuccess; + + if (result.IsSuccess) + { + file.OutputPath = result.OutputFilePath; + file.ErrorDetail = null; + file.StatusMessage = _localization?["Status_Success"] ?? "Success"; + CompletedCount++; + } + else + { + // 状态列只显示摘要,完整错误在详情对话框展示。 + file.ErrorDetail = result.ErrorMessage; + file.StatusMessage = _localization?["Status_Failed"] ?? "Failed"; + FailedCount++; + } + + var done = CompletedCount + FailedCount; + ProgressPercentage = done * 100.0 / TotalCount; + }); + }, token)); + + await Task.WhenAll(tasks); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // 用户取消时,未完成的文件保持待处理状态。 + } + finally + { + IsDecrypting = false; + _decryptCts?.Dispose(); + _decryptCts = null; + } + } + + /// + /// 显示文件解密失败的完整原因。 + /// + private async Task ShowDetailAsync(DecryptFileViewModel? file, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail)) + { + return; + } + + await _dialogService.ShowMessageAsync(DecryptFailureTitle, file.ErrorDetail); + } + + [RelayCommand] + private void CancelDecrypt() + { + _decryptCts?.Cancel(); + } + + [RelayCommand(CanExecute = nameof(CanClear))] + private void ClearFiles() + { + Files.Clear(); + TotalCount = 0; + CompletedCount = 0; + FailedCount = 0; + ProgressPercentage = 0; + OnPropertyChanged(nameof(CanStartDecrypt)); + } + + /// + /// 是否可以清空文件列表。 + /// + private bool CanClear => !IsDecrypting && Files.Count > 0; +} + +/// +/// 单个文件的解密状态。 +/// +public partial class DecryptFileViewModel : ObservableObject +{ + /// 输入文件路径。 + [ObservableProperty] + private string _filePath = string.Empty; + + /// 输入文件名。 + [ObservableProperty] + private string _fileName = string.Empty; + + /// 解密后的输出路径。 + [ObservableProperty] + private string? _outputPath; + + /// 是否已完成处理。 + [ObservableProperty] + private bool _isProcessed; + + /// 是否解密成功。 + [ObservableProperty] + private bool _isSuccessful; + + /// + /// 状态列摘要,完整原因保存在 。 + /// + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasErrorDetail))] + private string? _statusMessage; + + /// 解密失败的完整原因。 + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasErrorDetail))] + private string? _errorDetail; + + /// + /// 是否因缺少酷狗数据库而无法开始解密。 + /// + [ObservableProperty] + private bool _isBlocked; + + /// + /// 详情按钮文案。 + /// + [ObservableProperty] + private string? _viewDetailLabel; + + /// + /// 由父 ViewModel 在创建行时注入,用来打开失败详情对话框。 + /// + public IAsyncRelayCommand? ShowDetailCommand { get; set; } + + /// + /// 是否存在可查看的错误详情。 + /// + public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail); +} diff --git a/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs index 197da45..4c20e56 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs @@ -1,15 +1,106 @@ +using System.Reflection; using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using ZonyLrcTools.Desktop.Infrastructure.Localization; +using ZonyLrcTools.Desktop.Services; namespace ZonyLrcTools.Desktop.ViewModels; +/// +/// 首页与功能入口。 +/// public partial class HomeViewModel : ViewModelBase { - [ObservableProperty] - private string _welcomeMessage = "Welcome to ZonyLrcTools X"; + private readonly INavigationService _navigation; + private readonly IUILocalizationService _localization; + + /// + /// 创建首页。 + /// + public HomeViewModel(INavigationService navigation, IUILocalizationService localization) + { + _navigation = navigation; + _localization = localization; + _localization.LanguageChanged += OnLanguageChanged; + _version = ResolveVersion(); + } [ObservableProperty] - private string _description = "A cross-platform tool for downloading lyrics and album covers for your music collection."; + private string _version; - [ObservableProperty] - private string _version = "4.0.3"; + /// 欢迎语。 + public string WelcomeMessage => _localization["Home_Welcome"]; + /// 应用说明。 + public string Description => _localization["Home_Description"]; + /// 快捷操作标题。 + public string QuickActionsTitle => _localization["Home_QuickActions"]; + /// 功能特性标题。 + public string FeaturesTitle => _localization["Home_Features"]; + /// 支持格式说明。 + public string FeatureFormats => _localization["Home_FeatureFormats"]; + /// 并行下载说明。 + public string FeatureParallel => _localization["Home_FeatureParallel"]; + /// 编码支持说明。 + public string FeatureEncodings => _localization["Home_FeatureEncodings"]; + /// 跨平台支持说明。 + public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"]; + /// 版本标签。 + public string VersionLabel => _localization["Home_Version"]; + + // 功能入口文案。 + /// 歌词下载入口标题。 + public string LyricsCardTitle => _localization["Home_DownloadLyrics"]; + /// 歌词下载入口说明。 + public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"]; + /// 封面下载入口标题。 + public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"]; + /// 封面下载入口说明。 + public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"]; + /// 音乐解密入口标题。 + public string DecryptCardTitle => _localization["Home_Decrypt"]; + /// 音乐解密入口说明。 + public string DecryptCardDescription => _localization["Home_DecryptHint"]; + + [RelayCommand] + private void OpenLyrics() => _navigation.NavigateRoot(); + + [RelayCommand] + private void OpenAlbum() => _navigation.NavigateRoot(); + + [RelayCommand] + private void OpenDecrypt() => _navigation.NavigateRoot(); + + private void OnLanguageChanged(object? sender, EventArgs e) + { + OnPropertyChanged(nameof(WelcomeMessage)); + OnPropertyChanged(nameof(Description)); + OnPropertyChanged(nameof(QuickActionsTitle)); + OnPropertyChanged(nameof(FeaturesTitle)); + OnPropertyChanged(nameof(FeatureFormats)); + OnPropertyChanged(nameof(FeatureParallel)); + OnPropertyChanged(nameof(FeatureEncodings)); + OnPropertyChanged(nameof(FeatureCrossPlatform)); + OnPropertyChanged(nameof(VersionLabel)); + OnPropertyChanged(nameof(LyricsCardTitle)); + OnPropertyChanged(nameof(LyricsCardDescription)); + OnPropertyChanged(nameof(AlbumCardTitle)); + OnPropertyChanged(nameof(AlbumCardDescription)); + OnPropertyChanged(nameof(DecryptCardTitle)); + OnPropertyChanged(nameof(DecryptCardDescription)); + } + + private static string ResolveVersion() + { + var assembly = typeof(HomeViewModel).Assembly; + var informational = assembly.GetCustomAttribute()?.InformationalVersion; + + if (!string.IsNullOrWhiteSpace(informational)) + { + // 隐藏 SourceLink 添加的提交标识。 + var plusIndex = informational.IndexOf('+'); + return plusIndex > 0 ? informational[..plusIndex] : informational; + } + + return assembly.GetName().Version?.ToString(3) ?? "4.0.3"; + } } diff --git a/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs index c028dfb..0a97d8b 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs @@ -8,28 +8,74 @@ using ZonyLrcTools.Common.Configuration; using ZonyLrcTools.Common.Infrastructure.IO; using ZonyLrcTools.Common.Infrastructure.Threading; using ZonyLrcTools.Common.Lyrics; +using ZonyLrcTools.Common.MusicScanner; using ZonyLrcTools.Common.TagInfo; +using ZonyLrcTools.Desktop.Infrastructure.Configuration; using ZonyLrcTools.Desktop.Infrastructure.Localization; using ZonyLrcTools.Desktop.Services; namespace ZonyLrcTools.Desktop.ViewModels; +/// +/// 歌词列表的数据来源。 +/// +public enum LyricsScannerKind +{ + /// 扫描本地音乐文件夹。 + Local = 0, + + /// 读取歌曲与歌手信息的 CSV 文件。 + Csv = 1, + + /// 读取网易云歌单。 + NetEase = 2 +} + public partial class LyricsDownloadViewModel : ViewModelBase { + private const string DefaultOutputDirectoryName = "DownloadedLrc"; + private const string DefaultFileNamePattern = "{Artist} - {Name}.lrc"; + private readonly ILyricsDownloader _lyricsDownloader; private readonly IDialogService _dialogService; private readonly IFileScanner _fileScanner; private readonly ITagLoader _tagLoader; + private readonly CsvFileMusicScanner _csvFileMusicScanner; + private readonly NetEaseMusicSongListMusicScanner _neteaseMusicScanner; + private readonly NetEaseSessionStore _sessionStore; private readonly GlobalOptions _options; private readonly IUILocalizationService? _localization; private CancellationTokenSource? _downloadCts; - private Dictionary _musicFileMap = new(); - private List _scannedMusicInfos = new(); + private readonly Dictionary _musicFileMap = new(); + private readonly List _scannedMusicInfos = new(); [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyPropertyChangedFor(nameof(CanScan))] private string? _selectedFolderPath; + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyPropertyChangedFor(nameof(CanScan))] + private string? _selectedCsvFilePath; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyPropertyChangedFor(nameof(CanScan))] + private string? _songListIds; + + [ObservableProperty] + private string? _outputDirectory; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsLocalScanner))] + [NotifyPropertyChangedFor(nameof(IsCsvScanner))] + [NotifyPropertyChangedFor(nameof(IsNetEaseScanner))] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyPropertyChangedFor(nameof(CanScan))] + private int _selectedScannerIndex; + [ObservableProperty] private int _parallelCount = 2; @@ -47,13 +93,28 @@ public partial class LyricsDownloadViewModel : ViewModelBase [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] + [NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))] + [NotifyPropertyChangedFor(nameof(CanScan))] + [NotifyPropertyChangedFor(nameof(CanEditInputs))] [NotifyPropertyChangedFor(nameof(CanStartDownload))] private bool _isDownloading; [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] + [NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))] + [NotifyPropertyChangedFor(nameof(CanEditInputs))] [NotifyPropertyChangedFor(nameof(CanStartDownload))] + [NotifyPropertyChangedFor(nameof(CanScan))] private bool _isScanning; [ObservableProperty] @@ -65,10 +126,29 @@ public partial class LyricsDownloadViewModel : ViewModelBase [ObservableProperty] private double _scanProgressPercentage; + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(NetEaseAccountStatus))] + [NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))] + [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] + private bool _isNetEaseLoggedIn; + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] + [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] + [NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))] + [NotifyPropertyChangedFor(nameof(CanStartDownload))] + [NotifyPropertyChangedFor(nameof(CanScan))] + [NotifyPropertyChangedFor(nameof(CanEditInputs))] + private bool _isAccountBusy; + [ObservableProperty] private string? _currentProcessingFile; - // Localized strings + // 界面文案。 public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download"; public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files"; public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder"; @@ -78,6 +158,46 @@ public partial class LyricsDownloadViewModel : ViewModelBase public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download"; public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download"; public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files..."; + /// 数据来源标签。 + public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source"; + /// 扫描按钮文案。 + public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan"; + /// CSV 文件标签。 + public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File"; + /// CSV 文件选择提示。 + public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file..."; + /// CSV 文件选择按钮文案。 + public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose..."; + /// 网易云歌单编号标签。 + public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID"; + /// 网易云歌单编号输入提示。 + public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)"; + /// 输出目录标签。 + public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To"; + /// 输出目录选择提示。 + public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written"; + /// 输出目录选择按钮文案。 + public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose..."; + /// 退出登录按钮文案。 + public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out"; + /// 退出登录提示。 + public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ?? + "Forget the saved session and scan the QR code again next time."; + /// 登录按钮文案。 + public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…"; + /// 登录按钮提示。 + public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ?? + "Scan a QR code now instead of waiting until the next scan."; + + /// + /// 当前网易云登录状态。 + /// + 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."; + + /// 账号状态标签。 + public string NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account"; public string CommonTotal => _localization?["Common_Total"] ?? "Total:"; public string CommonFiles => _localization?["Common_Files"] ?? "files"; public string CommonSuccess => _localization?["Common_Success"] ?? "Success:"; @@ -87,7 +207,21 @@ public partial class LyricsDownloadViewModel : ViewModelBase public string ColumnFilePath => _localization?["Column_FilePath"] ?? "File Path"; public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; - public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0; + /// + /// 按 排列的数据来源名称。 + /// + public string[] ScannerNames => + [ + _localization?["Scanner_Local"] ?? "Local Folder", + _localization?["Scanner_Csv"] ?? "CSV File", + _localization?["Scanner_NetEase"] ?? "NetEase Playlist" + ]; + + public bool IsLocalScanner => SelectedScannerIndex == (int)LyricsScannerKind.Local; + public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv; + public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase; + + public bool CanStartDownload => CanEditInputs && MusicFiles.Count > 0; public bool HasNoFiles => MusicFiles.Count == 0; @@ -100,6 +234,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase IDialogService dialogService, IFileScanner fileScanner, ITagLoader tagLoader, + CsvFileMusicScanner csvFileMusicScanner, + NetEaseMusicSongListMusicScanner neteaseMusicScanner, + NetEaseSessionStore sessionStore, IOptions options, IUILocalizationService? localization = null) { @@ -107,18 +244,29 @@ public partial class LyricsDownloadViewModel : ViewModelBase _dialogService = dialogService; _fileScanner = fileScanner; _tagLoader = tagLoader; + _csvFileMusicScanner = csvFileMusicScanner; + _neteaseMusicScanner = neteaseMusicScanner; + _sessionStore = sessionStore; _options = options.Value; _localization = localization; + OutputDirectory = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), + DefaultOutputDirectoryName); + if (_localization != null) { _localization.LanguageChanged += OnLanguageChanged; } + // 扫描器为单例,页面直接复用已恢复的登录状态。 + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + MusicFiles.CollectionChanged += (_, _) => { OnPropertyChanged(nameof(HasNoFiles)); OnPropertyChanged(nameof(CanStartDownload)); + StartDownloadCommand.NotifyCanExecuteChanged(); }; } @@ -133,6 +281,22 @@ public partial class LyricsDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(LyricsStartDownload)); OnPropertyChanged(nameof(LyricsStopDownload)); OnPropertyChanged(nameof(LyricsScanning)); + OnPropertyChanged(nameof(LyricsScannerLabel)); + OnPropertyChanged(nameof(LyricsScan)); + OnPropertyChanged(nameof(LyricsCsvLabel)); + OnPropertyChanged(nameof(LyricsCsvSelect)); + OnPropertyChanged(nameof(LyricsCsvBrowse)); + OnPropertyChanged(nameof(LyricsSongListLabel)); + OnPropertyChanged(nameof(LyricsSongListWatermark)); + OnPropertyChanged(nameof(LyricsOutputLabel)); + OnPropertyChanged(nameof(LyricsOutputSelect)); + OnPropertyChanged(nameof(LyricsOutputBrowse)); + OnPropertyChanged(nameof(NetEaseSignOut)); + OnPropertyChanged(nameof(NetEaseSignOutHint)); + OnPropertyChanged(nameof(NetEaseSignIn)); + OnPropertyChanged(nameof(NetEaseSignInHint)); + OnPropertyChanged(nameof(NetEaseAccountStatus)); + OnPropertyChanged(nameof(NetEaseAccountLabel)); OnPropertyChanged(nameof(CommonTotal)); OnPropertyChanged(nameof(CommonFiles)); OnPropertyChanged(nameof(CommonSuccess)); @@ -142,26 +306,329 @@ public partial class LyricsDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(ColumnFilePath)); OnPropertyChanged(nameof(ColumnStatus)); OnPropertyChanged(nameof(EmptyStateText)); + OnPropertyChanged(nameof(ScannerNames)); + } + + partial void OnSelectedScannerIndexChanged(int value) => InvalidateScan(); + partial void OnSelectedCsvFilePathChanged(string? value) => InvalidateScan(); + partial void OnSongListIdsChanged(string? value) => InvalidateScan(); + partial void OnOutputDirectoryChanged(string? value) => InvalidateScan(); + + private void InvalidateScan() + { + if (CanEditInputs) + { + ResetCollections(); + } } [RelayCommand(CanExecute = nameof(CanSelectFolder))] - private async Task SelectFolderAsync() + private async Task SelectFolderAsync(CancellationToken cancellationToken = default) { var folder = await _dialogService.ShowFolderPickerAsync( _localization?["Lyrics_SelectFolder"] ?? "Select Music Folder"); + cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrEmpty(folder)) return; SelectedFolderPath = folder; - await ScanFilesAsync(); + await ScanFilesAsync(cancellationToken); } - private bool CanSelectFolder => !IsScanning && !IsDownloading; + /// + /// 是否可以修改任务来源与输出目录。 + /// + public bool CanEditInputs => !IsScanning && !IsDownloading && !IsAccountBusy; - private async Task ScanFilesAsync() + private bool CanSelectFolder => CanEditInputs; + + [RelayCommand(CanExecute = nameof(CanSelectFolder))] + private async Task SelectCsvFileAsync(CancellationToken cancellationToken = default) + { + var file = await _dialogService.ShowFilePickerAsync( + _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]); + cancellationToken.ThrowIfCancellationRequested(); + if (string.IsNullOrEmpty(file)) return; + + SelectedCsvFilePath = file; + } + + [RelayCommand(CanExecute = nameof(CanSelectFolder))] + private async Task SelectOutputFolderAsync(CancellationToken cancellationToken = default) + { + var folder = await _dialogService.ShowFolderPickerAsync( + _localization?["Lyrics_OutputSelect"] ?? "Select Output Folder"); + cancellationToken.ThrowIfCancellationRequested(); + if (string.IsNullOrEmpty(folder)) return; + + OutputDirectory = folder; + } + + + /// + /// 当前来源是否具备扫描所需的输入。 + /// + 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 + }); + + /// + /// 使用当前来源重新读取歌曲列表。 + /// + [RelayCommand(CanExecute = nameof(CanScan))] + private async Task StartScanAsync(CancellationToken cancellationToken = default) + { + switch ((LyricsScannerKind)SelectedScannerIndex) + { + case LyricsScannerKind.Csv: + await ScanCsvFileAsync(cancellationToken); + break; + case LyricsScannerKind.NetEase: + await ScanNetEasePlaylistAsync(cancellationToken); + break; + default: + await ScanFilesAsync(cancellationToken); + break; + } + } + + private async Task ScanFilesAsync(CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(SelectedFolderPath)) return; + ResetCollections(); IsScanning = true; + + try + { + var files = (await Task.Run( + () => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions), + cancellationToken)).ToList(); + + if (files.Count == 0) + { + await ShowNoMusicFilesAsync(cancellationToken); + return; + } + + ScanTotalCount = files.Count; + + using var warpTask = new WarpTask(ParallelCount); + var scanTasks = files.Select(file => + warpTask.RunAsync(async () => + { + var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken); + + await Dispatcher.UIThread.InvokeAsync(() => + { + if (musicInfo != null && + (!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist))) + { + AddRow(musicInfo); + } + + ScanProgressCount++; + ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount; + }); + }, cancellationToken)); + + await Task.WhenAll(scanTasks); + + TotalCount = MusicFiles.Count; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消扫描。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); + } + finally + { + IsScanning = false; + } + } + + private async Task ScanCsvFileAsync(CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty(SelectedCsvFilePath)) return; + + ResetCollections(); + IsScanning = true; + + try + { + var outputDirectory = RequireOutputDirectory(); + var musicInfos = await Task.Run(() => _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync( + SelectedCsvFilePath, outputDirectory, DefaultFileNamePattern, cancellationToken), cancellationToken); + + AppendScannedMusicInfos(musicInfos); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消扫描。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); + } + finally + { + IsScanning = false; + } + } + + private async Task ScanNetEasePlaylistAsync(CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(SongListIds)) return; + + ResetCollections(); + IsScanning = true; + + try + { + await RestoreNetEaseSessionAsync(cancellationToken); + + if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync(cancellationToken)) + { + return; + } + + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + + // 扫码等待与歌单请求都要能被打断,否则 Cookie 恰好失效时这里会一直挂着。 + var musicInfos = await _neteaseMusicScanner.GetMusicInfoFromNetEaseMusicSongListAsync( + SongListIds, + RequireOutputDirectory(), + DefaultFileNamePattern, + onQrCodeReady: null, + onStateChanged: null, + cancellationToken: cancellationToken); + + await PersistNetEaseSessionAsync(cancellationToken); + + AppendScannedMusicInfos(musicInfos); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消扫描。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); + } + finally + { + IsScanning = false; + + // 无论登录成功还是取消,都以扫描器中的状态为准。 + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + } + } + + /// + /// 恢复已保存的网易云登录状态。 + /// + private async Task RestoreNetEaseSessionAsync(CancellationToken cancellationToken = default) + { + if (_neteaseMusicScanner.IsLoggedIn) return; + + var session = await _sessionStore.LoadAsync(cancellationToken); + if (session == null) return; + + _neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken); + } + + private async Task PersistNetEaseSessionAsync(CancellationToken cancellationToken = default) + { + if (!_neteaseMusicScanner.IsLoggedIn) return; + + await _sessionStore.SaveAsync(new NetEaseSession + { + Cookie = _neteaseMusicScanner.Cookie, + CsrfToken = _neteaseMusicScanner.CsrfToken, + SavedAtUtc = DateTimeOffset.UtcNow + }, cancellationToken); + } + + /// + /// 显示二维码并等待登录或窗口关闭。 + /// + private async Task LoginToNetEaseAsync(CancellationToken cancellationToken = default) + { + var loginViewModel = new QrCodeLoginViewModel(_localization); + using var loginCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + void OnCancelled(object? sender, EventArgs args) => loginCts.Cancel(); + loginViewModel.Cancelled += OnCancelled; + + var loginTask = Task.Run(async () => + { + try + { + var expired = false; + var isSuccess = await _neteaseMusicScanner.LoginAsync( + payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)), + state => + { + expired = state == NetEaseLoginState.Expired; + Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)); + }, + loginCts.Token); + + await Dispatcher.UIThread.InvokeAsync(() => + { + if (isSuccess) + { + loginViewModel.Complete(); + } + else if (!expired) + { + loginViewModel.SetError(_localization?["NetEase_LoginFailed"] ?? + "Login did not complete. Close this dialog and try again."); + } + }); + + return isSuccess; + } + catch (OperationCanceledException) when (loginCts.IsCancellationRequested) + { + return false; + } + catch (Exception ex) + { + await Dispatcher.UIThread.InvokeAsync(() => loginViewModel.SetError(ex.Message)); + return false; + } + }); + + try + { + await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel, cancellationToken); + } + finally + { + loginViewModel.NotifyClosed(); + loginCts.Cancel(); + await loginTask; + loginViewModel.Cancelled -= OnCancelled; + } + + var isSuccess = await loginTask; + if (isSuccess) + { + await PersistNetEaseSessionAsync(cancellationToken); + } + + return isSuccess; + } + + + private void ResetCollections() + { MusicFiles.Clear(); _musicFileMap.Clear(); _scannedMusicInfos.Clear(); @@ -172,71 +639,73 @@ public partial class LyricsDownloadViewModel : ViewModelBase CompletedCount = 0; FailedCount = 0; ProgressPercentage = 0; - - try - { - var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions)) - .ToList(); - - if (files.Count == 0) - { - await _dialogService.ShowMessageAsync( - _localization?["Common_Info"] ?? "Info", - _localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder."); - IsScanning = false; - OnPropertyChanged(nameof(CanStartDownload)); - return; - } - - ScanTotalCount = files.Count; - - using var warpTask = new WarpTask(ParallelCount); - var scanTasks = files.Select(file => - warpTask.RunAsync(async () => - { - var musicInfo = await _tagLoader.LoadTagAsync(file); - - await Dispatcher.UIThread.InvokeAsync(() => - { - if (musicInfo != null && - (!string.IsNullOrEmpty(musicInfo.Name) || !string.IsNullOrEmpty(musicInfo.Artist))) - { - var vm = new MusicFileViewModel - { - FilePath = musicInfo.FilePath, - Name = musicInfo.Name, - Artist = musicInfo.Artist, - StatusMessage = _localization?["Status_Pending"] ?? "Pending" - }; - MusicFiles.Add(vm); - _musicFileMap[musicInfo.FilePath] = vm; - _scannedMusicInfos.Add(musicInfo); - } - - ScanProgressCount++; - ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount; - }); - })); - - await Task.WhenAll(scanTasks); - - TotalCount = MusicFiles.Count; - } - catch (Exception ex) - { - await _dialogService.ShowMessageAsync( - _localization?["Common_Error"] ?? "Error", - ex.Message); - } - finally - { - IsScanning = false; - OnPropertyChanged(nameof(CanStartDownload)); - } } + private void AddRow(MusicInfo musicInfo) + { + if (_musicFileMap.ContainsKey(musicInfo.FilePath)) return; + + var vm = new MusicFileViewModel + { + FilePath = musicInfo.FilePath, + Name = musicInfo.Name, + Artist = musicInfo.Artist, + StatusMessage = _localization?["Status_Pending"] ?? "Pending" + }; + + MusicFiles.Add(vm); + _musicFileMap[musicInfo.FilePath] = vm; + _scannedMusicInfos.Add(musicInfo); + } + + /// + /// 将 CSV 或网易云扫描结果加入列表。 + /// + private void AppendScannedMusicInfos(List musicInfos) + { + foreach (var musicInfo in musicInfos.Where(info => !string.IsNullOrEmpty(info.Name))) + { + AddRow(musicInfo); + } + + ScanTotalCount = MusicFiles.Count; + ScanProgressCount = ScanTotalCount; + ScanProgressPercentage = 100; + TotalCount = MusicFiles.Count; + } + + private string RequireOutputDirectory() + { + if (!string.IsNullOrWhiteSpace(OutputDirectory)) + { + return OutputDirectory; + } + + var fallback = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), + DefaultOutputDirectoryName); + OutputDirectory = fallback; + + return fallback; + } + + private Task ShowNoMusicFilesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return _dialogService.ShowMessageAsync( + _localization?["Common_Info"] ?? "Info", + _localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder."); + } + + private Task ShowErrorAsync(string message, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message); + } + + [RelayCommand(CanExecute = nameof(CanStartDownload))] - private async Task StartDownloadAsync() + private async Task StartDownloadAsync(CancellationToken cancellationToken = default) { if (_scannedMusicInfos.Count == 0) return; @@ -246,7 +715,6 @@ public partial class LyricsDownloadViewModel : ViewModelBase ProgressPercentage = 0; TotalCount = _scannedMusicInfos.Count; - // Reset all row statuses foreach (var vm in MusicFiles) { vm.IsProcessed = false; @@ -254,7 +722,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; } - _downloadCts = new CancellationTokenSource(); + _downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); try { @@ -294,9 +762,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase }, _downloadCts.Token); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested) { - // User cancelled + // 用户取消下载。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); } finally { @@ -311,6 +783,88 @@ public partial class LyricsDownloadViewModel : ViewModelBase { _downloadCts?.Cancel(); } + + /// + /// 清除已保存的网易云登录状态。 + /// + [RelayCommand(CanExecute = nameof(CanSignOutNetEase))] + private async Task SignOutNetEaseAsync(CancellationToken cancellationToken = default) + { + IsAccountBusy = true; + try + { + await _sessionStore.ClearAsync(cancellationToken); + _neteaseMusicScanner.ClearLoginState(); + await _dialogService.ShowMessageAsync( + _localization?["Common_Info"] ?? "Info", + _localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login."); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消操作。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); + } + finally + { + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + IsAccountBusy = false; + } + } + + private bool CanSignInNetEase => !IsNetEaseLoggedIn && CanEditInputs; + private bool CanSignOutNetEase => IsNetEaseLoggedIn && CanEditInputs; + + /// + /// 主动发起网易云扫码登录。 + /// + [RelayCommand(CanExecute = nameof(CanSignInNetEase))] + private async Task SignInNetEaseAsync(CancellationToken cancellationToken = default) + { + IsAccountBusy = true; + try + { + await LoginToNetEaseAsync(cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // 用户取消登录。 + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message, cancellationToken); + } + finally + { + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + IsAccountBusy = false; + } + } + + /// + /// 页面打开时恢复登录状态。 + /// + public override async Task OnActivatedAsync() + { + if (!CanEditInputs) return; + + IsAccountBusy = true; + try + { + await RestoreNetEaseSessionAsync(); + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message); + } + finally + { + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + IsAccountBusy = false; + } + } } public partial class MusicFileViewModel : ObservableObject diff --git a/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs index 479dec8..acf88ab 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs @@ -9,6 +9,7 @@ public partial class MainWindowViewModel : ViewModelBase { private readonly IThemeService _themeService; private readonly IUILocalizationService _localization; + private readonly INavigationService _navigation; [ObservableProperty] private ViewModelBase? _currentPage; @@ -27,6 +28,8 @@ public partial class MainWindowViewModel : ViewModelBase public string NavHome => _localization["Nav_Home"]; public string NavLyricsDownload => _localization["Nav_LyricsDownload"]; public string NavAlbumDownload => _localization["Nav_AlbumDownload"]; + /// 音乐解密导航文案。 + public string NavDecrypt => _localization["Nav_Decrypt"]; public string NavSettings => _localization["Nav_Settings"]; public string HomeDescription => _localization["Home_Description"]; @@ -37,25 +40,89 @@ public partial class MainWindowViewModel : ViewModelBase public MainWindowViewModel( IThemeService themeService, IUILocalizationService localization, - HomeViewModel homeViewModel) + INavigationService navigation) { _themeService = themeService; _localization = localization; + _navigation = navigation; + IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark; + _themeService.ThemeChanged += (_, _) => + IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark; // Subscribe to language changes _localization.LanguageChanged += OnLanguageChanged; - // Set initial page - CurrentPage = homeViewModel; - SelectedNavigationIndex = 0; + // 页面切换统一由导航服务管理。 + _navigation.NavigationChanged += OnNavigationChanged; + + NavigateToIndex(0); } + // 避免导航通知与侧栏选中状态互相触发。 + private bool _isSyncingNavigation; + + partial void OnSelectedNavigationIndexChanged(int value) + { + if (_isSyncingNavigation) + { + return; + } + + NavigateToIndex(value); + } + + private void NavigateToIndex(int index) + { + // 侧栏切换不累积返回记录。 + CurrentPage = index switch + { + 1 => _navigation.NavigateRoot(), + 2 => _navigation.NavigateRoot(), + 3 => _navigation.NavigateRoot(), + 4 => _navigation.NavigateRoot(), + _ => _navigation.NavigateRoot() + }; + } + + private void OnNavigationChanged(object? sender, ViewModelBase viewModel) + { + CurrentPage = viewModel; + + // 首页快捷入口跳转时同步侧栏选中项。 + var index = IndexOf(viewModel); + if (index < 0 || index == SelectedNavigationIndex) + { + return; + } + + _isSyncingNavigation = true; + try + { + SelectedNavigationIndex = index; + } + finally + { + _isSyncingNavigation = false; + } + } + + private static int IndexOf(ViewModelBase viewModel) => viewModel switch + { + LyricsDownloadViewModel => 1, + AlbumDownloadViewModel => 2, + DecryptViewModel => 3, + SettingsViewModel => 4, + HomeViewModel => 0, + _ => -1 + }; + private void OnLanguageChanged(object? sender, EventArgs e) { // Notify all localized properties have changed OnPropertyChanged(nameof(NavHome)); OnPropertyChanged(nameof(NavLyricsDownload)); OnPropertyChanged(nameof(NavAlbumDownload)); + OnPropertyChanged(nameof(NavDecrypt)); OnPropertyChanged(nameof(NavSettings)); OnPropertyChanged(nameof(HomeDescription)); OnPropertyChanged(nameof(ThemeButtonText)); @@ -64,9 +131,6 @@ public partial class MainWindowViewModel : ViewModelBase [RelayCommand] private void ToggleTheme() { - IsDarkTheme = !IsDarkTheme; - _themeService.SetTheme(IsDarkTheme - ? Avalonia.Styling.ThemeVariant.Dark - : Avalonia.Styling.ThemeVariant.Light); + _themeService.ToggleTheme(); } } diff --git a/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs new file mode 100644 index 0000000..b86b7ae --- /dev/null +++ b/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs @@ -0,0 +1,157 @@ +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.ComponentModel; +using QRCoder; +using ZonyLrcTools.Common.MusicScanner; +using ZonyLrcTools.Desktop.Infrastructure.Localization; + +namespace ZonyLrcTools.Desktop.ViewModels; + +/// +/// 网易云扫码登录对话框。 +/// +public partial class QrCodeLoginViewModel : ObservableObject +{ + private readonly IUILocalizationService? _localization; + private bool _isClosed; + + [ObservableProperty] + private Bitmap? _qrCodeImage; + + [ObservableProperty] + private string _statusText = string.Empty; + + [ObservableProperty] + private bool _hasImage; + + /// + /// 请求关闭登录对话框。 + /// + public event EventHandler? CloseRequested; + + /// + /// 登录完成前关闭对话框时触发。 + /// + public event EventHandler? Cancelled; + + /// + /// 是否已登录成功。 + /// + public bool IsCompleted { get; private set; } + + /// 登录窗口标题。 + public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music"; + /// 扫码登录提示。 + public string LoginTip => _localization?["NetEase_LoginTip"] ?? "Scan the QR code with the NetEase Cloud Music app on your phone."; + /// 取消按钮文案。 + public string CancelText => _localization?["Common_Cancel"] ?? "Cancel"; + + /// + /// 创建扫码登录对话框状态。 + /// + public QrCodeLoginViewModel(IUILocalizationService? localization = null) + { + _localization = localization; + _statusText = WaitText; + } + + private string WaitText => _localization?["NetEase_LoginWaiting"] ?? "Waiting for you to scan..."; + private string ScannedText => _localization?["NetEase_LoginScanned"] ?? "Scanned, please confirm on your phone."; + private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in."; + + /// + /// 显示扫描器提供的二维码。 + /// + public void SetPayload(NetEaseQrCodePayload payload) + { + if (_isClosed) return; + + var previousImage = QrCodeImage; + QrCodeImage = RenderQrCode(payload.Content); + HasImage = QrCodeImage != null; + previousImage?.Dispose(); + StatusText = HasImage + ? WaitText + : _localization?["NetEase_LoginFailed"] ?? "Login did not complete. Close this dialog and try again."; + } + + /// + /// 更新扫码登录状态。 + /// + 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 + }; + } + + /// + /// 显示登录错误。 + /// + public void SetError(string message) + { + if (_isClosed) return; + + StatusText = message; + } + + /// + /// 标记登录完成并关闭对话框。 + /// + public void Complete() + { + if (_isClosed) return; + + IsCompleted = true; + RequestClose(); + } + + /// + /// 请求关闭对话框。 + /// + public void RequestClose() + { + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + /// + /// 窗口关闭后停止登录并释放二维码。 + /// + public void NotifyClosed() + { + if (_isClosed) return; + + _isClosed = true; + var image = QrCodeImage; + QrCodeImage = null; + HasImage = false; + image?.Dispose(); + + if (!IsCompleted) + { + Cancelled?.Invoke(this, EventArgs.Empty); + } + } + + private static Bitmap? RenderQrCode(string content) + { + try + { + using var generator = new QRCodeGenerator(); + using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M); + using var qrCode = new PngByteQRCode(data); + using var stream = new MemoryStream(qrCode.GetGraphic(12)); + return new Bitmap(stream); + } + catch (Exception) + { + // 二维码无法生成时,由界面显示登录失败提示。 + return null; + } + } +} diff --git a/src/ZonyLrcTools.Desktop/ViewModels/SettingsViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/SettingsViewModel.cs index 9a4d70e..85f235c 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/SettingsViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/SettingsViewModel.cs @@ -2,19 +2,20 @@ using System.Collections.ObjectModel; using System.Globalization; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; -using Microsoft.Extensions.Options; -using YamlDotNet.Serialization; -using YamlDotNet.Serialization.NamingConventions; using ZonyLrcTools.Common.Configuration; +using ZonyLrcTools.Common.Lyrics; +using ZonyLrcTools.Desktop.Infrastructure.Configuration; using ZonyLrcTools.Desktop.Infrastructure.Localization; namespace ZonyLrcTools.Desktop.ViewModels; +/// 设置页面及自动保存状态。 public partial class SettingsViewModel : ViewModelBase { - private readonly GlobalOptions _globalOptions; + private readonly ISettingsStore _settingsStore; private readonly IUILocalizationService? _localizationService; - private bool _isLoading = true; // Prevent saving during initial load + private readonly GlobalOptions _globalOptions; + private bool _isLoading = true; [ObservableProperty] private bool _followSystemLanguage = true; @@ -32,7 +33,7 @@ public partial class SettingsViewModel : ViewModelBase private string _proxyIp = "127.0.0.1"; [ObservableProperty] - private int _proxyPort = 7890; + private int _proxyPort = 4780; [ObservableProperty] private bool _isTranslationEnabled; @@ -46,18 +47,40 @@ public partial class SettingsViewModel : ViewModelBase [ObservableProperty] private string _selectedEncoding = "utf-8"; - // Localized strings - public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings"; - public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language"; - public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System"; - public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese"; - public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English"; - public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy"; - public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy"; - public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address"; - public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider"; - public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset"; + [ObservableProperty] + private bool _isOnlyOutputTranslation; + [ObservableProperty] + private int _selectedLineBreakIndex; + + [ObservableProperty] + private bool _isBlockWordEnabled; + + [ObservableProperty] + private string _blockWordFilePath = "BlockWords.json"; + + [ObservableProperty] + private bool _isRomanOutputEnabled; + + /// 是否显示高级设置。 + [ObservableProperty] + private bool _isAdvancedVisible; + + // 显示配置位置及上次保存结果。 + [ObservableProperty] + private string _storageHint = string.Empty; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ShowSaveSuccess))] + [NotifyPropertyChangedFor(nameof(ShowSaveFailure))] + private string _saveStatusText = string.Empty; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ShowSaveSuccess))] + [NotifyPropertyChangedFor(nameof(ShowSaveFailure))] + private bool _hasSaveError; + + /// 可选择的歌词编码。 public ObservableCollection AvailableEncodings { get; } = new() { "utf-8", @@ -66,14 +89,119 @@ public partial class SettingsViewModel : ViewModelBase "gbk" }; + /// 预设换行符,与显示列表顺序一致。 + private static readonly string[] LineBreaks = + { + LineBreakType.Unix, + LineBreakType.Windows, + LineBreakType.MacOs + }; + + /// 换行符的显示名称。 + public ObservableCollection LineBreakDisplayNames { get; } = new() + { + "LF (Unix)", + "CRLF (Windows)", + "CR (macOS)" + }; + + private string CurrentLineBreak => SelectedLineBreakIndex >= 0 && SelectedLineBreakIndex < LineBreaks.Length + ? LineBreaks[SelectedLineBreakIndex] + : _globalOptions.Provider?.Lyric?.Config?.LineBreak ?? LineBreakType.Unix; + + /// 歌词提供者及搜索顺序。 public ObservableCollection LyricsProviders { get; } = new(); - public SettingsViewModel(IOptions options, IUILocalizationService? localizationService = null) - { - _globalOptions = options.Value; - _localizationService = localizationService; + /// 标签提供者及加载顺序。 + public ObservableCollection TagProviders { get; } = new(); - // Subscribe to language changes + // 本地化文本。 + /// 设置标题的本地化文本。 + public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings"; + /// 语言设置标题的本地化文本。 + public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language"; + /// 跟随系统语言的本地化文本。 + public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System"; + /// 中文选项的本地化文本。 + public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese"; + /// 英文选项的本地化文本。 + public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English"; + /// 代理设置标题的本地化文本。 + public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy"; + /// 启用代理的本地化文本。 + public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy"; + /// 代理地址的本地化文本。 + public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address"; + /// 代理端口的本地化文本。 + public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port"; + /// 歌词提供者标题的本地化文本。 + public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider"; + /// 恢复默认值的本地化文本。 + public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset"; + + /// 基本设置标题的本地化文本。 + public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics"; + /// 高级设置标题的本地化文本。 + public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced"; + /// 高级选项开关的本地化文本。 + public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options"; + /// 歌词设置标题的本地化文本。 + public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics"; + /// 翻译开关的本地化文本。 + public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics"; + /// 合并双语歌词开关的本地化文本。 + public string SettingsOneLineMode => _localizationService?["Settings_OneLineMode"] ?? "One-line mode (original + translation on same line)"; + /// 仅输出翻译开关的本地化文本。 + public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only"; + /// 跳过已有文件开关的本地化文本。 + public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files"; + /// 编码选项的本地化文本。 + public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:"; + /// 换行符选项的本地化文本。 + public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:"; + /// 罗马音开关的本地化文本。 + public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)"; + /// 屏蔽词设置标题的本地化文本。 + public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary"; + /// 屏蔽词开关的本地化文本。 + public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary"; + /// 屏蔽词路径的本地化文本。 + public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the working directory)"; + /// 标签提供者标题的本地化文本。 + public string SettingsTagProvider => _localizationService?["Settings_TagProvider"] ?? "Tag Provider"; + /// 优先级标题的本地化文本。 + public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: "; + /// 上移按钮的本地化文本。 + public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up"; + /// 下移按钮的本地化文本。 + public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down"; + /// 提供者顺序说明的本地化文本。 + public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"] + ?? "The list order is the search order. Use the arrows to change which source is tried first."; + /// 设置保存位置的本地化文本。 + public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file"; + /// 保存成功的本地化文本。 + public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved"; + /// 保存失败的本地化文本。 + public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings"; + /// 代理重启提示的本地化文本。 + public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"] + ?? "Proxy changes take effect the next time the app starts."; + + /// 是否显示保存成功提示。 + public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText); + + /// 是否显示保存失败提示。 + public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText); + + /// 创建设置页面。 + public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null) + { + _settingsStore = settingsStore; + _localizationService = localizationService; + _globalOptions = settingsStore.Options; + + // 跟随应用语言切换更新界面。 if (_localizationService != null) { _localizationService.LanguageChanged += OnLanguageChanged; @@ -81,7 +209,8 @@ public partial class SettingsViewModel : ViewModelBase LoadSettings(); LoadLanguageSettings(); - _isLoading = false; // Allow saving after initial load + StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}"; + _isLoading = false; } private void OnLanguageChanged(object? sender, EventArgs e) @@ -94,8 +223,33 @@ public partial class SettingsViewModel : ViewModelBase OnPropertyChanged(nameof(SettingsProxy)); OnPropertyChanged(nameof(SettingsProxyEnable)); OnPropertyChanged(nameof(SettingsProxyAddress)); + OnPropertyChanged(nameof(SettingsProxyPort)); OnPropertyChanged(nameof(SettingsLyricsProvider)); OnPropertyChanged(nameof(SettingsReset)); + OnPropertyChanged(nameof(SettingsBasicSection)); + OnPropertyChanged(nameof(SettingsAdvancedSection)); + OnPropertyChanged(nameof(SettingsShowAdvanced)); + OnPropertyChanged(nameof(SettingsLyricsSection)); + OnPropertyChanged(nameof(SettingsEnableTranslation)); + OnPropertyChanged(nameof(SettingsOneLineMode)); + OnPropertyChanged(nameof(SettingsOnlyTranslation)); + OnPropertyChanged(nameof(SettingsSkipExisting)); + OnPropertyChanged(nameof(SettingsFileEncoding)); + OnPropertyChanged(nameof(SettingsLineBreak)); + OnPropertyChanged(nameof(SettingsRomanOutput)); + OnPropertyChanged(nameof(SettingsBlockWordSection)); + OnPropertyChanged(nameof(SettingsBlockWordEnable)); + OnPropertyChanged(nameof(SettingsBlockWordPath)); + OnPropertyChanged(nameof(SettingsTagProvider)); + OnPropertyChanged(nameof(SettingsPriority)); + OnPropertyChanged(nameof(SettingsMoveUp)); + OnPropertyChanged(nameof(SettingsMoveDown)); + OnPropertyChanged(nameof(SettingsProviderOrderHint)); + OnPropertyChanged(nameof(SettingsStorage)); + OnPropertyChanged(nameof(SettingsSaved)); + OnPropertyChanged(nameof(SettingsSaveFailed)); + OnPropertyChanged(nameof(SettingsProxyRestartHint)); + StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}"; } private void LoadLanguageSettings() @@ -109,7 +263,7 @@ public partial class SettingsViewModel : ViewModelBase { if (value) { - // Auto-detect system language + // 使用操作系统语言。 var systemCulture = CultureInfo.InstalledUICulture.Name; ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US"); } @@ -141,6 +295,11 @@ public partial class SettingsViewModel : ViewModelBase partial void OnIsOneLineModeChanged(bool value) => SaveSettingsIfNotLoading(); partial void OnSkipExistingLyricsChanged(bool value) => SaveSettingsIfNotLoading(); partial void OnSelectedEncodingChanged(string value) => SaveSettingsIfNotLoading(); + partial void OnIsOnlyOutputTranslationChanged(bool value) => SaveSettingsIfNotLoading(); + partial void OnSelectedLineBreakIndexChanged(int value) => SaveSettingsIfNotLoading(); + partial void OnIsBlockWordEnabledChanged(bool value) => SaveSettingsIfNotLoading(); + partial void OnBlockWordFilePathChanged(string value) => SaveSettingsIfNotLoading(); + partial void OnIsRomanOutputEnabledChanged(bool value) => SaveSettingsIfNotLoading(); private void ApplyLanguage(string cultureName) { @@ -149,20 +308,23 @@ public partial class SettingsViewModel : ViewModelBase private void SaveSettingsIfNotLoading() { - if (!_isLoading) + if (_isLoading) { - SaveSettingsToFile(); + return; } + + WriteSettingsToOptions(); + _ = SaveSettingsAsync(); } private void LoadSettings() { - // Load network settings + // 加载代理设置。 IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false; ProxyIp = _globalOptions.NetworkOptions?.Ip ?? "127.0.0.1"; - ProxyPort = _globalOptions.NetworkOptions?.Port ?? 7890; + ProxyPort = _globalOptions.NetworkOptions?.Port ?? 4780; - // Load lyrics settings + // 加载歌词设置,保留未列入预设的有效编码。 var lyricsConfig = _globalOptions.Provider?.Lyric?.Config; if (lyricsConfig != null) { @@ -170,84 +332,469 @@ public partial class SettingsViewModel : ViewModelBase IsOneLineMode = lyricsConfig.IsOneLine; SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles; SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8"; + if (!AvailableEncodings.Contains(SelectedEncoding)) + { + AvailableEncodings.Add(SelectedEncoding); + } + IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation; + SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak); } - // Load lyrics providers + // 加载屏蔽词设置。 + var blockWord = _globalOptions.Provider?.Tag?.BlockWord; + if (blockWord != null) + { + IsBlockWordEnabled = blockWord.IsEnable; + BlockWordFilePath = string.IsNullOrWhiteSpace(blockWord.FilePath) + ? "BlockWords.json" + : blockWord.FilePath; + } + + // 罗马音开关保存在网易云提供者的扩展设置中。 + var netEase = _globalOptions.Provider?.Lyric?.Plugin? + .FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase)); + if (netEase?.Additional != null && + netEase.Additional.TryGetValue("isEnableRomanOutput", out var romanValue)) + { + IsRomanOutputEnabled = string.Equals(romanValue, "true", StringComparison.OrdinalIgnoreCase); + } + + // 启用的提供者按优先级排列,禁用项放到末尾。 + var tagProviders = _globalOptions.Provider?.Tag?.Plugin; + if (tagProviders != null) + { + foreach (var provider in tagProviders.Where(p => p.Priority != -1).OrderBy(p => p.Priority)) + { + AddTagProviderRow(provider.Name, true); + } + + // 禁用项不参与搜索。 + foreach (var provider in tagProviders.Where(p => p.Priority == -1)) + { + AddTagProviderRow(provider.Name, false); + } + + NormalizeProviderOrder(TagProviders); + } + + // 歌词提供者与标签提供者采用相同排序规则。 var providers = _globalOptions.Provider?.Lyric?.Plugin; if (providers != null) { - foreach (var provider in providers.OrderBy(p => p.Priority)) + foreach (var provider in providers.Where(p => p.Priority != -1).OrderBy(p => p.Priority)) { - LyricsProviders.Add(new LyricsProviderSettingViewModel - { - Name = provider.Name ?? "Unknown", - Priority = provider.Priority, - IsEnabled = provider.Priority != -1 - }); + AddLyricsProviderRow(provider.Name, true); } + + foreach (var provider in providers.Where(p => p.Priority == -1)) + { + AddLyricsProviderRow(provider.Name, false); + } + + NormalizeProviderOrder(LyricsProviders); } } - private void SaveSettingsToFile() + private void AddTagProviderRow(string? name, bool isEnabled) { + var row = new TagInfoProviderSettingViewModel + { + Name = name ?? "Unknown", + IsEnabled = isEnabled + }; + + // 创建行后绑定移动命令。 + row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, -1)); + row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, 1)); + + // 将行内编辑接入自动保存。 + row.PropertyChanged += OnProviderRowChanged; + TagProviders.Add(row); + } + + private void AddLyricsProviderRow(string? name, bool isEnabled) + { + var row = new LyricsProviderSettingViewModel + { + Name = name ?? "Unknown", + IsEnabled = isEnabled + }; + + row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, -1)); + row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, 1)); + + row.PropertyChanged += OnProviderRowChanged; + LyricsProviders.Add(row); + } + + /// 提供者启用状态改变后重新排序并保存。 + private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (_isLoading || _isNormalizing) + { + return; + } + + if (e.PropertyName is nameof(LyricsProviderSettingViewModel.IsEnabled) + or nameof(TagInfoProviderSettingViewModel.IsEnabled)) + { + _isNormalizing = true; + try + { + if (sender is LyricsProviderSettingViewModel) NormalizeProviderOrder(LyricsProviders); + else if (sender is TagInfoProviderSettingViewModel) NormalizeProviderOrder(TagProviders); + } + finally + { + _isNormalizing = false; + } + + SaveSettingsIfNotLoading(); + return; + } + + if (e.PropertyName is nameof(LyricsProviderSettingViewModel.Priority) + or nameof(TagInfoProviderSettingViewModel.Priority)) + { + SaveSettingsIfNotLoading(); + } + } + + private bool _isNormalizing; + + /// 启用项在前,优先级按可见顺序从一开始。 + private void NormalizeProviderOrder(ObservableCollection rows) where T : class, IProviderRowViewModel + { + var ordered = rows.Where(r => r.IsEnabled).Concat(rows.Where(r => !r.IsEnabled)).ToList(); + + for (var target = 0; target < ordered.Count; target++) + { + var current = rows.IndexOf(ordered[target]); + if (current != target) + { + rows.Move(current, target); + } + } + + var enabledCount = ordered.Count(r => r.IsEnabled); + for (var i = 0; i < ordered.Count; i++) + { + var row = ordered[i]; + + // 禁用项统一使用 -1。 + row.Priority = i < enabledCount ? i + 1 : -1; + row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—"; + row.CanMoveUp = i > 0 && i < enabledCount; + row.CanMoveDown = i + 1 < enabledCount; + } + } + + /// 在启用项范围内移动提供者。 + private void MoveProviderBy(ObservableCollection rows, T row, int offset) + where T : class, IProviderRowViewModel + { + var index = rows.IndexOf(row); + var target = index + offset; + if (index < 0 || target < 0 || target >= rows.Count || !row.IsEnabled || !rows[target].IsEnabled) + { + return; + } + + _isNormalizing = true; try { - // Update GlobalOptions with current values - if (_globalOptions.NetworkOptions != null) - { - _globalOptions.NetworkOptions.IsEnable = IsProxyEnabled; - _globalOptions.NetworkOptions.Ip = ProxyIp; - _globalOptions.NetworkOptions.Port = ProxyPort; - } - - if (_globalOptions.Provider?.Lyric?.Config != null) - { - _globalOptions.Provider.Lyric.Config.IsEnableTranslation = IsTranslationEnabled; - _globalOptions.Provider.Lyric.Config.IsOneLine = IsOneLineMode; - _globalOptions.Provider.Lyric.Config.IsSkipExistLyricFiles = SkipExistingLyrics; - _globalOptions.Provider.Lyric.Config.FileEncoding = SelectedEncoding; - } - - // Serialize and save to file - var serializer = new SerializerBuilder() - .WithNamingConvention(CamelCaseNamingConvention.Instance) - .Build(); - - var yaml = serializer.Serialize(_globalOptions); - var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.yaml"); - File.WriteAllText(configPath, yaml); + rows.Move(index, target); + NormalizeProviderOrder(rows); } - catch (Exception ex) + finally { - // Log error but don't crash - settings save is best effort - System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); + _isNormalizing = false; + } + + SaveSettingsIfNotLoading(); + } + + private static int ResolveLineBreakIndex(string? value) + { + for (var i = 0; i < LineBreaks.Length; i++) + { + if (string.Equals(LineBreaks[i], value, StringComparison.Ordinal)) + { + return i; + } + } + + return -1; + } + + private void WriteSettingsToOptions() + { + if (_globalOptions.NetworkOptions != null) + { + _globalOptions.NetworkOptions.IsEnable = IsProxyEnabled; + _globalOptions.NetworkOptions.Ip = ProxyIp; + _globalOptions.NetworkOptions.Port = ProxyPort; + } + + var lyricsConfig = _globalOptions.Provider?.Lyric?.Config; + if (lyricsConfig != null) + { + lyricsConfig.IsEnableTranslation = IsTranslationEnabled; + lyricsConfig.IsOneLine = IsOneLineMode; + lyricsConfig.IsSkipExistLyricFiles = SkipExistingLyrics; + lyricsConfig.FileEncoding = SelectedEncoding; + lyricsConfig.IsOnlyOutputTranslation = IsOnlyOutputTranslation; + lyricsConfig.LineBreak = CurrentLineBreak; + } + + var blockWord = _globalOptions.Provider?.Tag?.BlockWord; + if (blockWord != null) + { + blockWord.IsEnable = IsBlockWordEnabled; + blockWord.FilePath = BlockWordFilePath; + } + + var netEase = _globalOptions.Provider?.Lyric?.Plugin? + .FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase)); + if (netEase != null) + { + netEase.Additional ??= new Dictionary(); + netEase.Additional["isEnableRomanOutput"] = IsRomanOutputEnabled ? "true" : "false"; + } + + // 同步启用状态及搜索顺序。 + ApplyProviderSelection(_globalOptions.Provider?.Lyric?.Plugin, LyricsProviders); + ApplyProviderSelection(_globalOptions.Provider?.Tag?.Plugin, TagProviders); + } + + /// 将歌词提供者的界面顺序写入共享配置。 + private static void ApplyProviderSelection( + IEnumerable? options, + IEnumerable viewModels) + { + if (options == null) + { + return; + } + + var optionList = options.ToList(); + var order = 1; + + foreach (var row in viewModels) + { + var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase)); + if (option == null) + { + continue; + } + + option.Priority = row.IsEnabled ? order++ : -1; } } - [RelayCommand] - private void ResetToDefaults() + private static void ApplyProviderSelection( + IEnumerable? options, + IEnumerable viewModels) { - _isLoading = true; // Prevent multiple saves during reset + if (options == null) + { + return; + } + + var optionList = options.ToList(); + var order = 1; + + foreach (var row in viewModels) + { + var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase)); + if (option == null) + { + continue; + } + + option.Priority = row.IsEnabled ? order++ : -1; + } + } + + private async Task SaveSettingsAsync(CancellationToken cancellationToken = default) + { + // 合并连续输入,但配置在内存中立即生效。 + var pending = Interlocked.Increment(ref _saveRequestId); + await Task.Delay(SaveDebounceMilliseconds, cancellationToken).ConfigureAwait(true); + + if (pending != Volatile.Read(ref _saveRequestId)) + { + return; + } + + var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true); + if (pending != Volatile.Read(ref _saveRequestId)) + { + return; + } + + HasSaveError = !result.IsSuccess; + SaveStatusText = result.IsSuccess + ? $"{SettingsSaved}: {result.FilePath}" + : $"{SettingsSaveFailed}: {result.ErrorMessage}"; + StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}"; + } + + private int _saveRequestId; + private const int SaveDebounceMilliseconds = 400; + + [RelayCommand] + private async Task ResetToDefaultsAsync(CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _saveRequestId); + _isLoading = true; IsProxyEnabled = false; ProxyIp = "127.0.0.1"; - ProxyPort = 7890; - IsTranslationEnabled = false; - IsOneLineMode = false; - SkipExistingLyrics = true; + ProxyPort = 4780; + IsTranslationEnabled = true; + IsOneLineMode = true; + SkipExistingLyrics = false; + IsOnlyOutputTranslation = false; SelectedEncoding = "utf-8"; + SelectedLineBreakIndex = 0; + IsBlockWordEnabled = false; + BlockWordFilePath = "BlockWords.json"; + IsRomanOutputEnabled = false; + + // 恢复随程序附带的默认顺序,额外提供者保留在末尾。 + RestoreProviderOrder(LyricsProviders, ["NetEase", "QQ", "KuGou", "KuWo"], row => row.Name); + RestoreProviderOrder(TagProviders, ["Taglib", "FileName"], row => row.Name); + foreach (var row in LyricsProviders) + { + row.IsEnabled = true; + } + + foreach (var row in TagProviders) + { + row.IsEnabled = true; + } + + NormalizeProviderOrder(LyricsProviders); + NormalizeProviderOrder(TagProviders); + _isLoading = false; - SaveSettingsToFile(); // Save once after all resets + + // 所有默认值恢复后只保存一次。 + WriteSettingsToOptions(); + var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true); + HasSaveError = !result.IsSuccess; + SaveStatusText = result.IsSuccess + ? $"{SettingsSaved}: {result.FilePath}" + : $"{SettingsSaveFailed}: {result.ErrorMessage}"; + } + + private static void RestoreProviderOrder(ObservableCollection rows, string[] names, Func getName) + where T : class + { + var target = 0; + foreach (var name in names) + { + var row = rows.FirstOrDefault(row => string.Equals(getName(row), name, StringComparison.OrdinalIgnoreCase)); + if (row is not null) + { + rows.Move(rows.IndexOf(row), target++); + } + } } } -public partial class LyricsProviderSettingViewModel : ObservableObject +/// 可排序的提供者设置行。 +public interface IProviderRowViewModel +{ + /// 是否启用。 + bool IsEnabled { get; set; } + + /// 搜索优先级,禁用时为 -1。 + int Priority { get; set; } + + /// 界面显示的顺序。 + string PriorityLabel { get; set; } + + /// 是否可以向上移动。 + bool CanMoveUp { get; set; } + + /// 是否可以向下移动。 + bool CanMoveDown { get; set; } + + /// 禁用时降低行透明度。 + double RowOpacity { get; } + + /// 向上移动命令。 + IRelayCommand MoveUpCommand { get; } + + /// 向下移动命令。 + IRelayCommand MoveDownCommand { get; } +} + +/// 歌词提供者设置行。 +public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel { [ObservableProperty] private string _name = string.Empty; + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(RowOpacity))] + private bool _isEnabled; + + /// 搜索优先级,禁用时为 -1。 [ObservableProperty] private int _priority; + /// 显示的顺序,禁用时显示横线。 [ObservableProperty] + private string _priorityLabel = string.Empty; + + [ObservableProperty] + private bool _canMoveUp; + + [ObservableProperty] + private bool _canMoveDown; + + /// + public double RowOpacity => IsEnabled ? 1.0 : 0.45; + + /// + public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { }); + + /// + public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { }); +} + +/// 标签提供者设置行。 +public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel +{ + [ObservableProperty] + private string _name = string.Empty; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(RowOpacity))] private bool _isEnabled; + + /// + [ObservableProperty] + private int _priority; + + /// + [ObservableProperty] + private string _priorityLabel = string.Empty; + + [ObservableProperty] + private bool _canMoveUp; + + [ObservableProperty] + private bool _canMoveDown; + + /// + public double RowOpacity => IsEnabled ? 1.0 : 0.45; + + /// + public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { }); + + /// + public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { }); } diff --git a/src/ZonyLrcTools.Desktop/Views/Dialogs/ConfirmDialog.axaml b/src/ZonyLrcTools.Desktop/Views/Dialogs/ConfirmDialog.axaml index 5e042f6..7983a3a 100644 --- a/src/ZonyLrcTools.Desktop/Views/Dialogs/ConfirmDialog.axaml +++ b/src/ZonyLrcTools.Desktop/Views/Dialogs/ConfirmDialog.axaml @@ -28,10 +28,10 @@ HorizontalAlignment="Right" Spacing="8"> + + + @@ -61,36 +100,35 @@ BoxShadow="0 2 8 0 #0D000000" Padding="24"> - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - + + diff --git a/src/ZonyLrcTools.Desktop/Views/Pages/LyricsDownloadPage.axaml b/src/ZonyLrcTools.Desktop/Views/Pages/LyricsDownloadPage.axaml index e72b5cf..5bb1577 100644 --- a/src/ZonyLrcTools.Desktop/Views/Pages/LyricsDownloadPage.axaml +++ b/src/ZonyLrcTools.Desktop/Views/Pages/LyricsDownloadPage.axaml @@ -24,71 +24,182 @@ BoxShadow="0 2 8 0 #0D000000" Padding="24,20" Margin="0,0,0,16"> - - - - - - + + @@ -134,11 +179,124 @@ - - - + + + + + + + + + + + + + + + + + + + +