From 1c0f8e8d3a5aa04c984df68d183d3719f01c28b3 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:15:38 +0800 Subject: [PATCH 01/14] =?UTF-8?q?fix:=20=E4=B8=80=E4=B8=AA=E5=9D=8F?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=B8=8D=E5=86=8D=E4=B8=AD=E6=96=AD=E6=95=B4?= =?UTF-8?q?=E6=89=B9=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三个问题会让单个坏文件毁掉整次任务: 1. LoggerHelper.LogWarningInfo 在错误码小于 50000 时会把异常重新抛出。 而这个方法的所有调用点都在 catch 块里,异常于是穿透调用方的 catch, 整批任务就此中断。现在它只负责记录,要不要往上抛由调用方决定。 2. LyricsDownloader 把"这个源没返回歌词"当成了"这首歌是纯音乐":它把 IsSuccessful 置为 true 并跳出 provider 循环,后面的源根本没被问到。 现在只有真正拿到歌词才算成功;空结果会继续问下一个源,所有源都为空 才判为跳过。 3. LyricsDownloader 在写文件之前就把这一首标成成功。当配置的 fileEncoding 非法时,写入抛异常、异常被记进日志,而这一首仍然报告 成功 —— 磁盘上留下 0 字节的 .lrc,界面上却是绿色。现在先做编码转换 再建文件,失败时不留空壳,也如实报告失败。 顺带: - IAlbumDownloader / AlbumDownloader 增加可选的逐首回调,调用方据此可以 渲染进度;CLI 不传,行为不变。 - AlbumDownloader 不再在封面真正写盘之前记成功日志(原先它永远把所有 曲目都算作成功)。 - 各下载循环补上 WarpTask 的释放;回调抛出的异常会被捕获并记录,不再 掀翻整次运行。 --- .../Album/AlbumDownloader.cs | 77 ++++++++++++++-- .../Album/IAlbumDownloader.cs | 12 ++- .../Infrastructure/Extensions/LoggerHelper.cs | 11 ++- .../Lyrics/LyricsDownloader.cs | 92 +++++++++++++++---- 4 files changed, 159 insertions(+), 33 deletions(-) diff --git a/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs b/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs index 715c2b7..49b49bd 100644 --- a/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs +++ b/src/ZonyLrcTools.Common/Album/AlbumDownloader.cs @@ -1,4 +1,4 @@ -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; @@ -27,6 +27,7 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency public async Task DownloadAsync(List needDownloadMusicInfos, int parallelCount = 2, + Func? callback = null, CancellationToken cancellationToken = default) { await _logger.InfoAsync("开始下载专辑图像数据..."); @@ -34,35 +35,97 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase); if (provider == null) { + // 没有任何可用的专辑图像源,全部标记为失败并回调,避免调用方一直等待。 + foreach (var info in needDownloadMusicInfos) + { + info.IsSuccessful = false; + + if (callback == null) + { + continue; + } + + try + { + await callback(info); + } + catch (Exception ex) + { + await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。"); + } + } + return; } - var warpTask = new WarpTask(parallelCount); + 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 { + cancellationToken.ThrowIfCancellationRequested(); + var album = await provider.DownloadAsync(info.Name, info.Artist); - var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png"); - if (File.Exists(filePath) || album.Length <= 0) + var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, + $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png"); + + if (album.Length <= 0) { + info.IsSuccessful = false; + return; + } + + // 已存在同名图像视为成功,不重复覆盖用户已有的封面。 + if (File.Exists(filePath)) + { + info.IsSuccessful = true; return; } await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album); + info.IsSuccessful = true; + _logger.LogSuccessful(info); } catch (ErrorCodeException ex) { + info.IsSuccessful = false; _logger.LogWarningInfo(ex); } + catch (OperationCanceledException) + { + info.IsSuccessful = false; + } + catch (Exception ex) + { + info.IsSuccessful = false; + await _logger.ErrorAsync($"下载专辑图像时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。"); + } + finally + { + // 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。 + if (callback != null) + { + try + { + await callback(info); + } + catch (Exception ex) + { + await _logger.WarnAsync($"处理专辑下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。"); + } + } + } }, cancellationToken), cancellationToken)); await Task.WhenAll(warpTaskList); 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..3cafb3a 100644 --- a/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs +++ b/src/ZonyLrcTools.Common/Album/IAlbumDownloader.cs @@ -1,10 +1,18 @@ -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..fd852ed 100644 --- a/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs +++ b/src/ZonyLrcTools.Common/Infrastructure/Extensions/LoggerHelper.cs @@ -24,16 +24,17 @@ namespace ZonyLrcTools.Common.Infrastructure.Extensions /// /// 使用 级别打印错误日志,并记录异常堆栈。 + /// + /// 这个方法只负责记录,不会抛出异常。调用点全部位于 catch 块内, + /// 若在此处重新抛出,异常会穿透调用方的 catch 并终止整批任务 + /// (例如一首歌的编码配置有误会导致整批歌词下载中断)。 + /// 需要向上传播错误时,请由调用方显式决定,而不是让日志方法代劳。 + /// /// /// 日志记录器的实例。 /// 错误码异常实例。 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)}"); diff --git a/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs b/src/ZonyLrcTools.Common/Lyrics/LyricsDownloader.cs index 17edeba..b08637d 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; @@ -49,22 +49,53 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency 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. + // 依次尝试所有可用的歌词来源,直到某一家真正返回了歌词。 + // 某个来源返回空结果是「这家没搜到」,不是「这首歌没有歌词」,必须继续问下一家。 + var isFinished = false; + var hasProviderError = false; + foreach (var lyricsProvider in AvailableProviders) { - await DownloadAndWriteLyricsAsync(lyricsProvider, info); + var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info); - if (!info.IsSuccessful) continue; - _logger.LogSuccessful(info); - break; + if (result == LyricsDownloadResult.Success) + { + _logger.LogSuccessful(info); + isFinished = true; + break; + } + + if (result == LyricsDownloadResult.Failed) + { + hasProviderError = true; + } } - if (callback != null) await callback(info); + if (!isFinished) + { + // 所有来源都没有返回歌词。若期间有来源报错,就判为失败; + // 否则说明各家都查无此曲,按纯音乐/未收录处理(与旧版的统计口径保持一致)。 + info.IsSuccessful = !hasProviderError; + info.IsPruneMusic = !hasProviderError; + } + + // 回调是调用方(GUI)提供的 UI 代码,它抛异常不应该拖垮整批下载。 + if (callback != null) + { + try + { + await callback(info); + } + catch (Exception ex) + { + await _logger.WarnAsync($"处理歌曲下载回调时发生错误:{ex.Message},歌曲名: {info.Name}。"); + } + } }, cancellationToken), cancellationToken)); await Task.WhenAll(downloadTasks); @@ -76,19 +107,22 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency await LogFailedSongFilesInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.Now:yyyyMMddHHmmss}.txt"), needDownloadMusicInfos); } - private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info) + private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info) { try { var lyrics = await provider.DownloadAsync(info.Name, info.Artist); + // 该来源没有搜到歌词,交给调用方去问下一家,不能在这里判定整首歌完成。 if (lyrics.IsPruneMusic) { - info.IsSuccessful = true; - info.IsPruneMusic = true; - return; + return LyricsDownloadResult.Empty; } + // 先把歌词编码成字节,再动磁盘。编码配置有误时(例如 fileEncoding 写成了不存在的名字) + // 这一步就会抛错,此时文件还没被创建,不会留下 0 字节的空壳。 + var content = Utf8ToSelectedEncoding(lyrics); + var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc"); @@ -100,27 +134,47 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency // Write lyrics to file. await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write)) { - await using (var binaryWriter = new BinaryWriter(fileStream, Encoding.UTF8)) - { - binaryWriter.Write(Utf8ToSelectedEncoding(lyrics)); - binaryWriter.Flush(); - } + await fileStream.WriteAsync(content); + await fileStream.FlushAsync(); } info.IsSuccessful = true; + info.IsPruneMusic = false; + return LyricsDownloadResult.Success; } catch (ErrorCodeException ex) { - _logger.LogWarningInfo(ex); + // 失败标记必须放在记录日志之前:LoggerHelper 即便将来再改动行为, + // 也不能让「失败」的歌曲以默认的 IsSuccessful = true 冒出去。 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.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。"); + return LyricsDownloadResult.Failed; } } + /// + /// 单个歌词来源的处理结果。 + /// + private enum LyricsDownloadResult + { + /// 歌词已写入文件。 + Success, + + /// 该来源没有返回歌词(既可能是没有收录,也可能是纯音乐)。 + Empty, + + /// 该来源处理过程中出错。 + Failed + } + // Convert UTF-8 to selected encoding. private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics) { From 168a8e42f1d0c86d032f7efd0579f81ce51cad81 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:15:58 +0800 Subject: [PATCH 02/14] =?UTF-8?q?feat(decrypt):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E9=85=B7=E7=8B=97=20.kgg=20=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原先的解密依赖 MusicDecrypto.Library,它支持 ncm/qmc/kgm/kgma/kwm,但任何 版本都不支持 .kgg,这类文件会被直接拒绝。 .kgg 不是自包含的:音频用 QMC2 加密,而每个文件的 ekey 并不存放在文件里。 文件里只有偏移 0x48 处的 32 字节音频哈希;对应的 ekey 在酷狗客户端的 KGMusicV3.db(表 ShareFileItems)里,而这个数据库本身也是逐页加密的。 所以必须先读数据库: 1. 逐页解密 KGMusicV3.db(AES-128-CBC,key/IV 由主密钥和页号派生) 2. 用文件的音频哈希查出 ekey 3. 解码 ekey(TC-TEA CBC,含 V2 两段式变体) 4. 构造 QMC2 解密器(短密钥用映射表,长密钥用 RC4) 5. 按 1 MB 分块流式解密音频 6. 读解密后的头 4 个字节判断真实扩展名(fLaC / OggS / 否则 mp3) 实际后果:.kgg 只能在本机解密,因为那条 ekey 记录只有在酷狗客户端下载过 这首歌时才会写入。别人给的 .kgg 解不了。 新增内容: - Common/MusicDecryption/Kugou/ —— TcTea、EkeyDecoder、Qmc2Cipher、 KugouEkeyDatabase、KggMusicDecryptor - IKugouKeyProvider / KugouKeyProvider —— 探测数据库、缓存已解析的密钥表、 支持手动指定数据库路径 - IMusicDecryptor.ConvertMusicAsync 增加可选 CancellationToken,让大文件真的 能被中断(桌面端有"停止"按钮) - 输出先写 .part,校验字节数之后才改名,中途中断不会留下一个看起来完成 了的残缺文件 注意: - Microsoft.Data.Sqlite 会传递引入 SQLitePCLRaw.lib.e_sqlite3 2.1.11,该版本 被 NU1903 / GHSA-2m69-gcr7-jv3q 标记。显式引用 SQLitePCLRaw.bundle_e_sqlite3 3.0.5 覆盖掉它。 - e_sqlite3.dll 是原生依赖,单文件发布会把它留在 exe 外面,必须随包分发。 酷狗算法移植自 MIT 协议的 kgg-dec 参考实现,因此 THIRD-PARTY-NOTICES.md 带上原始版权与许可声明,每个移植文件头部也标了来源。 --- Directory.Packages.props | 3 + THIRD-PARTY-NOTICES.md | 45 +++ .../MusicDecryption/DefaultMusicDecryptor.cs | 28 +- .../MusicDecryption/IKugouKeyProvider.cs | 63 ++++ .../MusicDecryption/IMusicDecryptor.cs | 5 +- .../MusicDecryption/Kugou/EkeyDecoder.cs | 204 ++++++++++ .../Kugou/KggMusicDecryptor.cs | 239 ++++++++++++ .../Kugou/KugouEkeyDatabase.cs | 353 ++++++++++++++++++ .../MusicDecryption/Kugou/Qmc2Cipher.cs | 252 +++++++++++++ .../MusicDecryption/Kugou/TcTea.cs | 139 +++++++ .../MusicDecryption/KugouKeyProvider.cs | 190 ++++++++++ .../ZonyLrcTools.Common.csproj | 3 + 12 files changed, 1516 insertions(+), 8 deletions(-) create mode 100644 THIRD-PARTY-NOTICES.md create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/IKugouKeyProvider.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/Kugou/TcTea.cs create mode 100644 src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 27e3b3d..60bea96 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -41,6 +41,9 @@ + + + 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/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/DefaultMusicDecryptor.cs index eec0716..95c7f53 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,20 +9,30 @@ 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; @@ -30,15 +41,20 @@ namespace ZonyLrcTools.Common.MusicDecryption if (!File.Exists(outFilePath)) { await using var outFile = new FileStream(outFilePath, FileMode.Create, FileAccess.Write, FileShare.None); - await buffer.CopyToAsync(outFile); + await buffer.CopyToAsync(outFile, cancellationToken); } 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..bd9d9e5 --- /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..dd35fc6 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/EkeyDecoder.cs @@ -0,0 +1,204 @@ +// 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 static readonly byte[] V2Prefix = "UVFNdXNpYyBFbmNWMixLZXk6"u8.ToArray(); + + 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 段里被忽略的非法字符数量。Base64 解码本身是宽容的(会静默映射成 0), + /// 这里把它统计出来,让上层能把「密钥损坏」和「没有密钥」区分开。 + /// + /// + /// 原始密钥;解码失败时为空数组。 + public static byte[] Decode(string ekey, out int invalidCharCount) + { + invalidCharCount = 0; + if (string.IsNullOrEmpty(ekey)) + { + return []; + } + + var raw = Encoding.Latin1.GetBytes(ekey); + if (raw.Length >= V2Prefix.Length && raw.AsSpan(0, V2Prefix.Length).SequenceEqual(V2Prefix)) + { + var inner = TcTea.CbcDecrypt(raw[V2Prefix.Length..], 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(Encoding.Latin1.GetBytes(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 readonly byte[] Base64Table = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u8.ToArray(); + + /// + /// 宽容的 Base64 解码,兼容 URL-safe 变体与不规范的长度。 + /// 输入中不属于 Base64 的字符数量(空白字符会被跳过,不计入)。 + /// + private static byte[] Base64Decode(byte[] input, out int invalidCount) + { + var reverse = new byte[256]; + var isKnown = new bool[256]; + for (var i = 0; i < Base64Table.Length; i++) + { + reverse[Base64Table[i]] = (byte)i; + isKnown[Base64Table[i]] = true; + } + + // URL-safe 变体。 + reverse[(byte)'-'] = 62; + reverse[(byte)'_'] = 63; + isKnown[(byte)'-'] = true; + isKnown[(byte)'_'] = true; + isKnown[(byte)'='] = true; + + // 空白字符按「忽略」处理,其余未知字符计入 invalidCount,交给调用方判定为损坏。 + isKnown[(byte)' '] = true; + isKnown[(byte)'\r'] = true; + isKnown[(byte)'\n'] = true; + isKnown[(byte)'\t'] = true; + + invalidCount = 0; + var cleaned = new byte[input.Length]; + var cleanedLength = 0; + foreach (var value in input) + { + if (value is (byte)' ' or (byte)'\r' or (byte)'\n' or (byte)'\t') + { + continue; + } + + if (!isKnown[value]) + { + invalidCount++; + continue; + } + + cleaned[cleanedLength++] = value; + } + + input = cleaned.AsSpan(0, cleanedLength).ToArray(); + + var output = new byte[(input.Length + 3) / 4 * 3]; + var outOffset = 0; + + // 解一组 4 个字符;返回 true 表示遇到了填充,可以结束。 + bool DecodeBlock(ReadOnlySpan block) + { + var a = reverse[block[0]]; + var b = reverse[block[1]]; + var c = reverse[block[2]]; + var d = reverse[block[3]]; + + output[outOffset++] = (byte)((a << 2) | (b >> 4)); + + if (block[2] == '=') + { + return true; + } + + output[outOffset++] = (byte)((b << 4) | (c >> 2)); + + if (block[3] == '=') + { + return true; + } + + output[outOffset++] = (byte)((c << 6) | d); + return false; + } + + var fullLength = input.Length - input.Length % 4; + for (var i = 0; i < fullLength; i += 4) + { + if (DecodeBlock(input.AsSpan(i, 4))) + { + return output.AsSpan(0, outOffset).ToArray(); + } + } + + var remainder = input.Length % 4; + if (remainder != 0) + { + var tail = new byte[4]; + tail[0] = input[fullLength]; + tail[1] = remainder > 1 ? input[fullLength + 1] : (byte)'='; + tail[2] = (byte)'='; + tail[3] = (byte)'='; + DecodeBlock(tail); + } + + return output.AsSpan(0, outOffset).ToArray(); + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs new file mode 100644 index 0000000..08586be --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KggMusicDecryptor.cs @@ -0,0 +1,239 @@ +// 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 格式(按魔数而非扩展名)。 + /// + public static bool IsKggFile(string filePath) + { + try + { + using var stream = File.OpenRead(filePath); + Span buffer = stackalloc byte[16]; + return stream.ReadAtLeast(buffer, 16, throwOnEndOfStream: false) == 16 + && buffer.SequenceEqual(Magic); + } + catch + { + return false; + } + } + + /// + /// 解密 .kgg 文件。 + /// + /// 待解密的文件路径。 + /// 密钥来源;为 null 时使用自动探测到的酷狗数据库。 + /// 取消令牌。 + /// 解密结果;失败时带有可读的错误说明。 + public static async Task ConvertAsync(string filePath, + IKugouKeyProvider? keyProvider, + CancellationToken cancellationToken) + { + 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)); + 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(KugouEkeyDatabase.BuildMissingDatabaseMessage()); + } + + var ekey = ResolveEkey(keyProvider, audioHash); + 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); + 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) && new FileInfo(outputPath).Length == expectedLength) + { + return DecryptionResult.Success(outputPath); + } + + // 先写临时文件,成功后再改名。中途取消或被强杀都不会污染正式输出文件名。 + var tempPath = outputPath + ".part"; + try + { + await using (var output = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, + BufferSize, true)) + { + var buffer = new byte[BufferSize]; + long offset = 0; + int read; + while ((read = await input.ReadAsync(buffer, cancellationToken)) > 0) + { + 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})。"); + } + } + + File.Move(tempPath, outputPath, overwrite: true); + } + catch + { + TryDelete(tempPath); + throw; + } + + 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?.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 "mp3"; + } + } +} diff --git a/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs new file mode 100644 index 0000000..b2d48e6 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/KugouEkeyDatabase.cs @@ -0,0 +1,353 @@ +// 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.Security.Cryptography; +using System.Text; +using Microsoft.Data.Sqlite; + +namespace ZonyLrcTools.Common.MusicDecryption.Kugou +{ + /// + /// 酷狗客户端本地数据库(KGMusicV3.db)的读取器。 + /// + /// 数据库按 4KB 分页做了 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; + } + + // 解密后的内容写到临时文件,交给 SQLite 自己解析,避免手写记录格式。 + // 这里放的是明文密钥库,所以用一个专用目录并在每次进入时清理上次留下的残留: + // 进程被强杀时 finally 不会执行,但下一次读取会把上一轮的明文文件删掉。 + var tempDirectory = Path.Combine(Path.GetTempPath(), TemporaryDirectoryName); + var tempPath = Path.Combine(tempDirectory, $"{Guid.NewGuid():N}.db"); + try + { + Directory.CreateDirectory(tempDirectory); + SweepStaleTempFiles(tempDirectory); + + WriteFileWithFlush(tempPath, plain); + + using var connection = new SqliteConnection($"Data Source={tempPath};Mode=ReadOnly"); + connection.Open(); + + 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 + { + TryDeleteFile(tempPath); + } + + return result; + } + + private const string TemporaryDirectoryName = "zony-kgm-temp"; + + private static void WriteFileWithFlush(string path, byte[] content) + { + using var stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); + stream.Write(content, 0, content.Length); + stream.Flush(true); + } + + /// + /// 清掉上一次运行留下的明文临时库(正常退出时 finally 已经删过,这里只兜异常退出的底)。 + /// + private static void SweepStaleTempFiles(string directory) + { + try + { + foreach (var file in Directory.EnumerateFiles(directory, "*.db")) + { + TryDeleteFile(file); + } + } + catch + { + // 目录枚举失败不影响本次读取。 + } + } + + private static void TryDeleteFile(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch + { + // 删不掉不影响结果,下次进入时还会再清一次。 + } + } + + /// + /// 把整个加密数据库解密成明文的 SQLite 字节流。 + /// + private static byte[] DecryptDatabase(string databasePath) + { + using var source = new FileStream(databasePath, FileMode.Open, FileAccess.Read, FileShare.Read); + + var length = (int)source.Length; + if (length == 0 || length % PageSize != 0) + { + return []; + } + + 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..5308d79 --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/Kugou/Qmc2Cipher.cs @@ -0,0 +1,252 @@ +// 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 +{ + /// + /// 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 >> (8 - 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) + { + uint hash = 1; + 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..4535531 --- /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 []; + } + + ulong iv1 = 0; + ulong iv2 = 0; + 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..ff5a56f --- /dev/null +++ b/src/ZonyLrcTools.Common/MusicDecryption/KugouKeyProvider.cs @@ -0,0 +1,190 @@ +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? _loadedPath; + 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, StringComparison.OrdinalIgnoreCase)) + { + // 路径没变就不作废缓存,避免无意义地重新解密 16 MB 数据库。 + return; + } + + _manualPath = normalized; + Invalidate(); + } + } + + /// + /// 探测当前可用的酷狗数据库。 + /// + /// 结果会被缓存:整库解密需要几十毫秒,而真正查一次密钥只要 0.1 毫秒。 + /// 只有在 改变了路径、或显式调用 时才会重新读取。 + /// + /// + public KugouDatabaseInfo Probe() + { + lock (_syncRoot) + { + EnsureLoaded(); + + if (_databasePath == null) + { + var message = _manualPath != null + ? $"指定的酷狗数据库不可用:{_failureReason ?? _manualPath}" + : 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; + _loadedPath = null; + _failureReason = null; + } + } + + public bool IsKggFile(string filePath) => ReadAudioHash(filePath) != null; + + 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 hashLength = BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(0x44)); + if (hashLength == 0 || 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; + _loadedPath = 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 ?? "没有读到任何密钥"; + + // 手动指定的文件读不出密钥,就不要把它当成可用数据库。 + if (_manualPath != null) + { + return; + } + } + + _databasePath = path; + _loadedPath = path; + foreach (var pair in keys) + { + _keys[pair.Key] = pair.Value; + } + } + } +} diff --git a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj index 8cd7019..84a6d93 100644 --- a/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj +++ b/src/ZonyLrcTools.Common/ZonyLrcTools.Common.csproj @@ -7,6 +7,9 @@ + + + From 4ec67b9ee0be6104b7ef04b05653e4a6b4260ba9 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:16:15 +0800 Subject: [PATCH 03/14] =?UTF-8?q?feat(scanner):=20=E8=AE=A9=E7=BD=91?= =?UTF-8?q?=E6=98=93=E4=BA=91=E6=AD=8C=E5=8D=95=E6=89=AB=E6=8F=8F=E5=99=A8?= =?UTF-8?q?=E8=83=BD=E5=9C=A8=E7=BB=88=E7=AB=AF=E4=B9=8B=E5=A4=96=E4=BD=BF?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 网易云的扫描器是照着 CLI 的场景写的:把登录二维码画成 ASCII 艺术丢进日志, 然后在一个没有上限的循环里等待。这在终端里没问题,在别处都不行:GUI 无法 呈现那块 ASCII 图形,看不到登录进行到哪一步,也没法取消等待。 NetEaseMusicSongListMusicScanner 的改动: - LoginAsync 增加可选回调,收到结构化的 NetEaseQrCodePayload(二维码内容、 unikey、以及 ASCII 渲染结果)。传了回调就跳过 ASCII 那一步;不传(CLI 正是如此)时原有的日志输出完全不变,download -sc netease 的行为与改动前 一致。 - 增加可选的 Action,汇报中间状态(等待扫码 / 已扫码 未确认 / 成功 / 二维码过期),而不是只留一个会阻塞到底的 await。 - 每个循环、每次 HTTP 调用都接受 CancellationToken,关掉二维码窗口就能真的 中止扫描。 - Cookie 与 CsrfToken 从私有字段改成公开属性,调用方可以跨重启恢复会话, 不必每次启动都扫码。同时补上 RestoreLoginState / ClearLoginState / IsLoggedIn。 - 登录失败原先抛 ErrorCodes.NotSupportedFileEncoding,这个错误码与实际情况 毫无关系。改为 UnableGetSongListFromNetEaseCloudMusic。 CsvFileMusicScanner 另有一个解析缺陷:它按 Environment.NewLine 切行,而 Windows 上那是 "\r\n"。从网页导出、或从 git 里签出的 CSV 通常是纯 "\n", 于是整个文件被当成一行,跳过表头之后就是空的,界面上表现为"解析了却一首歌 都没有"。改成同时按两个字符切分即可;过短的行也不再抛异常。 --- .../MusicScanner/CsvFileMusicScanner.cs | 14 +- .../NetEaseMusicSongListMusicScanner.cs | 181 ++++++++++++++---- .../MusicScanner/NetEaseQrCodePayload.cs | 27 +++ 3 files changed, 179 insertions(+), 43 deletions(-) create mode 100644 src/ZonyLrcTools.Common/MusicScanner/NetEaseQrCodePayload.cs diff --git a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs index 825a4a5..5375a27 100644 --- a/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs +++ b/src/ZonyLrcTools.Common/MusicScanner/CsvFileMusicScanner.cs @@ -21,16 +21,22 @@ public class CsvFileMusicScanner : ITransientDependency 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)) + + // 不能只按 Environment.NewLine 切分:在 Windows 上读到的是 "\r\n",而用户从网盘、 + // 版本的表格导出、Git 里签出的 CSV 往往是 "\n",那样整个文件会被当成一行, + // 跳过表头之后就是空的,界面上表现为"解析了但一首歌都没有"。 + var csvFileLines = csvFileContent.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries); + return csvFileLines.Skip(1) + .Where(line => line.Contains(',')) // 跳过空行与 VCS 合并产生的杂行。 + .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..ca0ec4e 100644 --- a/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs +++ b/src/ZonyLrcTools.Common/MusicScanner/NetEaseMusicSongListMusicScanner.cs @@ -21,8 +21,20 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency private readonly ILogger _logger; private const string Host = "https://music.163.com"; - private string Cookie { get; set; } = string.Empty; - private string CsrfToken { get; set; } = string.Empty; + /// + /// 登录后的 Cookie。GUI 可以在登录成功之后把它持久化下来,下次直接赋值恢复登录态。 + /// + public string Cookie { get; set; } = string.Empty; + + /// + /// 登录后的 CSRF Token,通常与 一起持久化。 + /// + public string CsrfToken { get; set; } = string.Empty; + + /// + /// 当前是否已经持有登录态。 + /// + public bool IsLoggedIn => !string.IsNullOrEmpty(Cookie); /// /// 构建一个新的 对象。 @@ -34,24 +46,88 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency _logger = logger; } + /// + /// 清除当前登录态,下次调用歌单接口时会重新要求扫码。 + /// + public void ClearLoginState() + { + Cookie = string.Empty; + CsrfToken = string.Empty; + } + + /// + /// 恢复一个已有的登录态,供 GUI 从本地缓存中读回 Cookie 之后调用。 + /// + /// 之前登录成功时保存的 Cookie。 + /// 与 一起保存的 CSRF Token。 + public void RestoreLoginState(string cookie, string csrfToken) + { + Cookie = cookie ?? string.Empty; + CsrfToken = csrfToken ?? string.Empty; + } + + /// + /// 主动触发一次扫码登录(如果已经登录则直接返回 true)。 + /// + /// 二维码就绪回调。 + /// 登录状态变化回调,GUI 用它显示「已扫码,请在手机上确认」之类的中间态。 + /// 取消令牌。 + /// 登录成功时为 true。 + public async Task LoginAsync( + Action? onQrCodeReady = null, + Action? onStateChanged = null, + CancellationToken cancellationToken = default) + { + if (IsLoggedIn) + { + onStateChanged?.Invoke(NetEaseLoginState.Succeeded); + return true; + } + + var loginResponse = await LoginViqQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken); + Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty; + CsrfToken = loginResponse.csrfToken ?? string.Empty; + + return IsLoggedIn; + } + /// /// 从网易云歌单获取需要下载的歌曲列表,调用这个 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)) { - var loginResponse = await LoginViqQrCodeAsync(); + var loginResponse = await LoginViqQrCodeAsync(onQrCodeReady, onStateChanged, cancellationToken); Cookie = loginResponse.cookieContainer?.GetCookieHeader(new Uri(Host)) ?? string.Empty; CsrfToken = loginResponse.csrfToken ?? string.Empty; + + if (string.IsNullOrEmpty(Cookie)) + { + // 登录没成(用户取消、二维码过期),直接失败,不要再拿空 Cookie 去请求歌单。 + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); + } } async Task> GetMusicInfoBySongIdAsync(string songId) { + cancellationToken.ThrowIfCancellationRequested(); + var secretKey = NetEaseMusicEncryptionHelper.CreateSecretKey(16); var encSecKey = NetEaseMusicEncryptionHelper.RsaEncode(secretKey); var response = await _warpHttpClient.PostAsync( @@ -73,7 +149,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency if (response.Code != 200 || response.PlayList?.SongList == null) { - throw new ErrorCodeException(ErrorCodes.NotSupportedFileEncoding); + throw new ErrorCodeException(ErrorCodes.UnableGetSongListFromNetEaseCloudMusic); } return response.PlayList.SongList @@ -88,8 +164,10 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency } var musicInfoList = new List(); - foreach (var songListId in songListIds.Split(';')) + foreach (var songListId in songListIds.Split(';', StringSplitOptions.RemoveEmptyEntries)) { + cancellationToken.ThrowIfCancellationRequested(); + _logger.LogInformation("正在获取歌单 {SongListId} 的歌曲列表。", songListId); var musicInfos = await GetMusicInfoBySongIdAsync(songListId); musicInfoList.AddRange(musicInfos); @@ -121,55 +199,72 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency /// /// 通过二维码登录网易云音乐,登录成功后返回 Cookie 和 CSRF Token。 /// - private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync() + /// + /// 二维码就绪回调。为空时保持原有行为 —— 把 ASCII 二维码打到日志里,供 CLI 在终端展示。 + /// + /// 登录状态变化回调。 + /// 取消令牌。 + private async Task<(string? csrfToken, CookieContainer? cookieContainer)> LoginViqQrCodeAsync( + Action? onQrCodeReady, + Action? onStateChanged, + CancellationToken cancellationToken) { // Get unikey. var qrCodeKeyJson = await (await PostAsync($"{Host}/weapi/login/qrcode/unikey", new { type = 1 - })).Content.ReadAsStringAsync(); + })).Content.ReadAsStringAsync(cancellationToken); var uniKey = JObject.Parse(qrCodeKeyJson).SelectToken("$.unikey")!.Value(); if (string.IsNullOrEmpty(uniKey)) return (null, null); // Generate QR code. var qrGenerator = new QRCodeGenerator(); - var qrCodeData = qrGenerator.CreateQrCode($"{Host}/login?codekey={uniKey}", - QRCodeGenerator.ECCLevel.L); - var qrCode = new AsciiQRCode(qrCodeData); - var asciiQrCodeString = qrCode.GetGraphic(1, drawQuietZones: false); + var qrContent = $"{Host}/login?codekey={uniKey}"; + var qrCodeData = qrGenerator.CreateQrCode(qrContent, QRCodeGenerator.ECCLevel.L); + var asciiQrCodeString = new AsciiQRCode(qrCodeData).GetGraphic(1, drawQuietZones: false); - _logger.LogInformation("请使用网易云 APP 扫码登录:"); - _logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString); + if (onQrCodeReady != null) + { + onQrCodeReady(new NetEaseQrCodePayload(qrContent, uniKey, asciiQrCodeString)); + } + else + { + _logger.LogInformation("请使用网易云 APP 扫码登录:"); + _logger.LogInformation("\n{AsciiQrCodeString}", asciiQrCodeString); + } // Wait for login success. - var isLogin = false; - while (!isLogin) + var lastState = NetEaseLoginState.Waiting; + while (true) { - var (isSuccess, cookieContainer) = await CheckIsLoginAsync(uniKey); - isLogin = isSuccess; + cancellationToken.ThrowIfCancellationRequested(); - if (!isLogin) + var (state, cookieContainer) = await CheckIsLoginAsync(uniKey, cancellationToken); + + if (state != lastState) { - 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) { var responseMessage = await PostAsync($"{Host}/weapi/login/qrcode/client/login", new { @@ -177,17 +272,25 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency type = 1 }); - 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 802: + return (NetEaseLoginState.ScanConfirmed, null); + case 803: + break; + default: + return (NetEaseLoginState.Waiting, null); } if (!responseMessage.Headers.TryGetValues("Set-Cookie", out var cookies)) { - return (false, null); + return (NetEaseLoginState.Waiting, null); } var cookieContainer = new CookieContainer(); @@ -196,7 +299,7 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency cookieContainer.SetCookies(new Uri(Host), cookie); } - return (true, cookieContainer); + return (NetEaseLoginState.Succeeded, cookieContainer); } /// @@ -219,4 +322,4 @@ public class NetEaseMusicSongListMusicScanner : ISingletonDependency request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); }); } -} \ 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 +} From 9cda87dbfe5dd7e02b780d16ce4be2b95052236b Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:16:33 +0800 Subject: [PATCH 04/14] =?UTF-8?q?feat(desktop):=20=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=97=B6=E4=B8=8D=E5=86=8D=E9=87=8D=E5=86=99?= =?UTF-8?q?=E6=95=B4=E4=B8=AA=20config.yaml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 桌面端从共享的 DI 容器拿配置对象,再用 YamlDotNet 的序列化器整份写回。这样 一轮往返会把文件重写一遍:仓库里那 60 行、注释众多的 config.yaml 会变成 40 行机器生成的块,注释全没了,多行值的引号风格也变了。只要在设置页动一个开关, 注释就丢了。 SettingsStore 不再重新序列化整个文档,只补丁 UI 真正拥有的那几个键: - PatchText 按行扫描 YAML,用缩进栈跟踪每个受管键的路径 (networkOptions.isEnable、provider.lyric.plugin[NetEase].priority …), 只替换那个标量,其余每一个字节 —— 注释、空行、列对齐 —— 保持原样。带 引号的值保持原引号风格(QuotedScalarEventEmitter 沿用原文样式)。 - 补丁后的文本会被重新解析,并逐字段与预期值比对,通过才落盘。往返不一致 就拒绝写入,磁盘上的文件保持不动。另有重新生成整份文件的兜底路径,用于 原文件已被替换成补丁器无法跟随的内容时。 同一提交里还有: - AppPaths:可执行文件所在目录可写时配置就放那里(便携安装),否则回退到 %AppData%/ZonyLrcTools。写入走临时文件 + File.Move,崩溃不会留下半份配置。 - NetEaseSessionStore / KugouDatabaseStore:两个小 JSON,分别存网易云登录 cookie 和用户手动指定的 KGMusicV3.db 路径。刻意与 config.yaml 分开 —— 它们是机器状态而不是用户偏好,也不该出现在设置的 diff 里。 - ConfigurationServiceCollectionExtensions:构造与 CLI 相同的 GlobalOptions, 但基于上面解析出的路径,而不是固定的 AppContext.BaseDirectory。 Common 为此一行未改:CLI 照旧从自己所在目录读 config.yaml。 --- .../Infrastructure/Configuration/AppPaths.cs | 117 ++++ ...onfigurationServiceCollectionExtensions.cs | 29 + .../Configuration/ISettingsStore.cs | 39 ++ .../Configuration/KugouDatabaseStore.cs | 113 ++++ .../Configuration/NetEaseSessionStore.cs | 122 +++++ .../Configuration/QuotedScalarEventEmitter.cs | 51 ++ .../Configuration/SettingsStore.cs | 501 ++++++++++++++++++ 7 files changed, 972 insertions(+) create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs new file mode 100644 index 0000000..8dab003 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs @@ -0,0 +1,117 @@ +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// Resolves the directories the desktop application reads and writes at runtime. +/// +/// +/// The application prefers a portable layout: settings live next to the executable so the +/// whole folder can be copied to a USB stick and moved between machines. If that directory +/// is read-only (installed under Program Files, or launched from a read-only mount), it falls +/// back to %AppData%\ZonyLrcTools instead of silently losing every setting the user changes. +/// +public static class AppPaths +{ + private const string ApplicationFolderName = "ZonyLrcTools"; + private const string ConfigFileName = "config.yaml"; + + private static readonly Lazy LazyConfigDirectory = new(ResolveConfigDirectory); + + /// + /// Directory that holds config.yaml. + /// + public static string ConfigDirectory => LazyConfigDirectory.Value; + + /// + /// Full path of the writable config.yaml. + /// + public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName); + + /// + /// Copy the template shipped next to the executable into the config directory when the + /// user does not have a settings file yet. Safe to call on every startup. + /// + 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), + StringComparison.OrdinalIgnoreCase)) + { + return; + } + + try + { + File.Copy(template, ConfigFilePath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A missing config file is not fatal: the options binder falls back to defaults. + } + } + + 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) + { + // Fall through to the portable path; reading still works even when writing does not. + } + + 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..f8f5d50 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs @@ -0,0 +1,29 @@ +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 +{ + /// + /// Bind from the writable settings file resolved by + /// , instead of the read-only folder next to the executable that + /// uses. + /// + 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..4a35c7f --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs @@ -0,0 +1,39 @@ +using ZonyLrcTools.Common.Configuration; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// Result of a settings persist operation. +/// +/// Whether the settings were written to disk. +/// The file that was written, when the write succeeded. +/// Human readable reason when the write failed. +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); +} + +/// +/// Single owner of the settings file: reads the bound and writes it back +/// to . +/// +public interface ISettingsStore +{ + /// + /// The live options instance shared by the whole application. Mutating it takes effect + /// immediately for components that read it per operation. + /// + GlobalOptions Options { get; } + + /// + /// Absolute path of the settings file currently in use. + /// + string ConfigFilePath { get; } + + /// + /// Serialize to YAML and replace the settings file atomically. + /// + 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..b1c68d9 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs @@ -0,0 +1,113 @@ +using System.Text.Json; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// Remembers a manually chosen Kugou database (KGMusicV3.db) path. +/// +/// +/// This is machine state, not a user preference — it points at a file that happens to exist on +/// this computer. Keeping it out of config.yaml means the shipped configuration template +/// stays clean and CLI users never see a stray GUI-only key. +/// +public sealed class KugouDatabaseStore +{ + private const string FileName = "kugou.database.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true + }; + + private readonly SemaphoreSlim _lock = new(1, 1); + + /// + /// Full path of the settings file. + /// + public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); + + /// + /// Load the stored database path, or null when there is none / it cannot be read. + /// + 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); + + return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + // A corrupt cache must never block the application; fall back to auto detection. + return null; + } + finally + { + _lock.Release(); + } + } + + /// + /// Persist the chosen database path. + /// + public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + Directory.CreateDirectory(AppPaths.ConfigDirectory); + + var setting = new KugouDatabaseSetting { DatabasePath = databasePath }; + var temporaryPath = FilePath + ".tmp"; + await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(setting, JsonOptions), cancellationToken); + File.Move(temporaryPath, FilePath, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Losing this only costs the user one extra pick next launch. + } + finally + { + _lock.Release(); + } + } + + /// + /// Forget the stored path so auto detection takes over again. + /// + public async Task ClearAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + if (File.Exists(FilePath)) + { + File.Delete(FilePath); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Nothing actionable. + } + finally + { + _lock.Release(); + } + } +} + +/// +/// The persisted shape of . +/// +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..35f66ec --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs @@ -0,0 +1,122 @@ +using System.Text.Json; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// Persists the NetEase Cloud Music login state (cookie + csrf token) so the QR login dialog +/// does not reappear on every launch. +/// +/// +/// The cookie is a bearer credential: whoever holds it is logged in as the user. It is written +/// next to the settings file with owner-only permissions where the platform supports it, and +/// the file is small and plain JSON so a user can delete it by hand to force a re-login. +/// +public sealed class NetEaseSessionStore +{ + private const string FileName = "netease.session.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true + }; + + private readonly SemaphoreSlim _lock = new(1, 1); + + /// + /// Full path of the session file. + /// + public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName); + + /// + /// Whether a stored session exists on disk. + /// + public bool HasStoredSession => File.Exists(FilePath); + + /// + /// Load the stored session, or null when there is none / it cannot be read. + /// + 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 session = JsonSerializer.Deserialize(json); + + return string.IsNullOrEmpty(session?.Cookie) ? null : session; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + // A corrupt session cache must never block the application; treat it as "not logged in". + return null; + } + finally + { + _lock.Release(); + } + } + + /// + /// Write the session to disk. + /// + public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + Directory.CreateDirectory(AppPaths.ConfigDirectory); + + var temporaryPath = FilePath + ".tmp"; + await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(session, JsonOptions), cancellationToken); + File.Move(temporaryPath, FilePath, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Losing the cache only costs the user one extra scan next launch. + } + finally + { + _lock.Release(); + } + } + + /// + /// Delete the stored session. + /// + public async Task ClearAsync(CancellationToken cancellationToken = default) + { + await _lock.WaitAsync(cancellationToken); + try + { + if (File.Exists(FilePath)) + { + File.Delete(FilePath); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Nothing actionable; the in-memory state is cleared regardless. + } + finally + { + _lock.Release(); + } + } +} + +/// +/// The bits of a NetEase login that are worth keeping between runs. +/// +public sealed class NetEaseSession +{ + public string Cookie { get; set; } = string.Empty; + + public string CsrfToken { get; set; } = string.Empty; + + public DateTimeOffset SavedAt { get; set; } = DateTimeOffset.Now; +} diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs new file mode 100644 index 0000000..09fa835 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs @@ -0,0 +1,51 @@ +using YamlDotNet.Core; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.EventEmitters; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// Forces every control-character scalar onto a single double-quoted line. +/// +/// +/// +/// YamlDotNet renders a value such as "\n" as the folded block scalar >2, which is +/// technically legal YAML but reads as garbage to anyone opening config.yaml by hand and +/// contradicts the documentation that describes lineBreak as an escape sequence. +/// +/// +/// This emitter only changes presentation: the value that survives a round trip is identical, +/// it just comes back as lineBreak: "\n" instead of a folded block. +/// +/// +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; + } + } + + // Leading or trailing whitespace is silently trimmed by the plain-scalar reader. + 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..b7bb4d2 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs @@ -0,0 +1,501 @@ +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Options; +using YamlDotNet.Serialization; +using YamlDotNet.Serialization.NamingConventions; +using ZonyLrcTools.Common.Configuration; + +namespace ZonyLrcTools.Desktop.Infrastructure.Configuration; + +/// +/// +/// +/// Saving must not destroy the hand-written comments in config.yaml: that file is the +/// documented configuration surface of this project, and a full re-serialize flattens it into an +/// unreadable machine blob on the very first checkbox click. +/// +/// +/// So the store patches the values it owns in place, line by line, and only falls back to a full +/// re-serialize when the on-disk text no longer round-trips to the intended values. The patched +/// text is parsed back and compared before it is committed, so a bad patch can never overwrite a +/// working configuration. +/// +/// +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) + // Keep "\n" readable instead of letting YamlDotNet emit the folded block scalar ">2". + .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); + } + + // Write to a sibling temp file first so a crash mid-write cannot truncate the + // settings the user already had. + var tempPath = targetPath + ".tmp"; + await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken) + .ConfigureAwait(false); + File.Move(tempPath, targetPath, overwrite: true); + + return SettingsSaveResult.Success(targetPath); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + return SettingsSaveResult.Failure(ex.Message); + } + finally + { + _writeLock.Release(); + } + } + + /// + /// Rewrites only the managed scalar values in place, keeping every comment and blank line. + /// Returns null when the file is missing or the patched text does not read back as the + /// intended configuration. + /// + /// + /// A managed key does not need its own line to be "correct": config.yaml ships with + /// # depth: 10 commented out for QQ, and the default it falls back to is exactly the + /// value the GUI wants. The round-trip check below is therefore the only gate that matters. + /// + private async Task TryPatchInPlaceAsync( + string path, + IReadOnlyDictionary managed, + CancellationToken cancellationToken) + { + if (!File.Exists(path)) + { + return null; + } + + var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(original)) + { + return null; + } + + var patched = PatchText(original, managed); + return VerifyRoundTrip(patched, managed) ? patched : null; + } + + private string BuildFromScratch() + { + // Materialize the same managed values the patch path would have written, so the two + // paths cannot disagree about what "saved" means. + // YamlDotNet 输出统一是 "\n",这里显式拼同一套行尾,避免首行注释与正文混用 CRLF/LF。 + 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; + } + } + + /// Reads the value of a managed path back out of a deserialized options instance. + 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), + // Line breaks must not be trimmed: "\n" and "" are different configurations. + "provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak, + "provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation), + "provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation), + "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 + }; + } + + /// Canonical text for a boolean, so "True" and "true" compare equal. + 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 + }; + + /// + /// Walks the YAML text, tracking the current key path by indentation, and replaces only the + /// value part of lines whose full path is managed. Trailing comments are preserved verbatim. + /// + private static string PatchText(string original, IReadOnlyDictionary managed) + { + var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n"; + var lines = original.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); + var stack = new List<(int Indent, string Path)>(); + var replaced = new HashSet(StringComparer.Ordinal); + + for (var i = 0; i < lines.Length; i++) + { + var raw = lines[i]; + var trimmed = raw.TrimStart(); + if (trimmed.Length == 0 || trimmed.StartsWith('#')) + { + continue; + } + + var indent = raw.Length - trimmed.Length; + + // Leave the previous sibling scope as soon as the indentation goes back out. + while (stack.Count > 0 && stack[^1].Indent >= indent) + { + stack.RemoveAt(stack.Count - 1); + } + + var parent = stack.Count > 0 ? stack[^1].Path : string.Empty; + + // List element header, e.g. " - name: NetEase # 基于网易云的歌词下载器。" + if (trimmed.StartsWith("- name:", StringComparison.Ordinal)) + { + var name = ReadToken(trimmed["- name:".Length..]); + if (name.Length > 0) + { + stack.Add((indent, $"{parent}[{name}]")); + } + + continue; + } + + var colon = trimmed.IndexOf(':'); + if (colon <= 0) + { + continue; + } + + var key = trimmed[..colon].Trim(); + if (key.Length == 0 || key.Contains(' ') || key.StartsWith('-')) + { + continue; + } + + var rest = trimmed[(colon + 1)..]; + var valuePart = ReadToken(rest); + var fullPath = parent.Length == 0 ? key : $"{parent}.{key}"; + + if (valuePart.Length == 0) + { + // Section header: children follow at a deeper indentation. + stack.Add((indent, fullPath)); + continue; + } + + if (!managed.TryGetValue(fullPath, out var newValue)) + { + continue; + } + + if (!replaced.Add(fullPath)) + { + // 同一个键出现多次时只改第一处:改全部会让 YAML 里前一处生效、后一处变成 + // 死键的语义更难理解,也让回读校验失去意义。留个注释说明这是有意为之。 + continue; + } + + // Preserve the exact column layout: the value span, then its trailing comment. + // config.yaml aligns its comments into columns, so a value that grew or shrank must + // absorb the difference in the padding rather than push the comment sideways. + var leadingSpaces = rest.Length - rest.TrimStart().Length; + var valueStart = indent + colon + 1 + leadingSpaces; + var comment = rest[(leadingSpaces + valuePart.Length)..]; + var replacement = FormatScalar(newValue, valuePart); + + if (comment.Length > 1 && comment[0] == ' ') + { + var commentColumn = valueStart + valuePart.Length + (comment.Length - comment.TrimStart().Length); + var padding = commentColumn - (valueStart + replacement.Length); + if (padding >= 1) + { + comment = new string(' ', padding) + comment.TrimStart(); + } + } + + lines[i] = raw[..valueStart] + replacement + comment; + } + + return string.Join(newline, lines); + } + + /// Reads the first YAML token, stopping at whitespace outside quotes. + private static string ReadToken(string text) + { + var s = text.TrimStart(); + if (s.Length == 0) + { + return string.Empty; + } + + if (s[0] is '"' or '\'') + { + var quote = s[0]; + for (var i = 1; i < s.Length; i++) + { + if (s[i] == '\\' && quote == '"') + { + i++; + continue; + } + + if (s[i] == quote) + { + return s[..(i + 1)]; + } + } + + return s; + } + + var end = 0; + while (end < s.Length && !char.IsWhiteSpace(s[end])) + { + end++; + } + + return s[..end]; + } + + /// + /// Emits the new scalar in the shape the old one had: same quote character when the previous + /// value was quoted, double quotes when the value contains characters a plain scalar cannot + /// carry (the line-break value), plain otherwise. + /// + /// + /// A value that merely looks like a boolean is left unquoted: "true" and "false" reach this + /// method both from boolean fields (where quoting would turn them into strings) and from + /// string fields (whose original spelling in the file was already quoted). Mirroring the + /// previous token's quoting therefore keeps both cases correct. + /// + private static string FormatScalar(string value, string previous) + { + var mustQuote = value.Length == 0 + || value.Any(c => c is '\n' or '\r' or '\t' or '"' or '\\') + || value != value.Trim(); + + if (!mustQuote) + { + if (previous.StartsWith('\'') && !value.Contains('\'')) + { + return $"'{value}'"; + } + + if (previous.StartsWith('"')) + { + return $"\"{value}\""; + } + + return value; + } + + var escaped = value + .Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("\"", "\\\"", StringComparison.Ordinal) + .Replace("\r", "\\r", StringComparison.Ordinal) + .Replace("\n", "\\n", StringComparison.Ordinal) + .Replace("\t", "\\t", StringComparison.Ordinal); + + return $"\"{escaped}\""; + } + + /// Flattens the editable subset of into path → scalar text. + 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; + } + + /// + /// Releases the write lock. is a singleton, so this only runs at + /// shutdown, but the lock is a disposable handle and leaving it to finalization is sloppy. + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _writeLock.Dispose(); + } +} From 216ea4e0c47524ced606db1cbc73af585b6f2a9c Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:16:50 +0800 Subject: [PATCH 05/14] =?UTF-8?q?refactor(desktop):=20=E9=A1=B5=E9=9D=A2?= =?UTF-8?q?=E5=88=87=E6=8D=A2=E7=BB=9F=E4=B8=80=E8=B5=B0=20INavigationServ?= =?UTF-8?q?ice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 侧栏原先是在 MainWindow.axaml.cs 里用一个针对 ListBox.SelectedIndex 的 switch 接起来的,直接调 App.Services.GetRequiredService<...> 从 code-behind 赋页面。 NavigationService 存在、已注册,却从没被用过。 后果:首页的深层链接无法改变侧栏选中项;新增一个页面要同时改 view model 和 code-behind;每个页面即使该是单例也会被重新构造。 现在: - INavigationService 增加 NavigateRoot(),用于"跳到顶层页面"(清空回退栈), 与已有的 NavigateTo()、GoBack() 并存。 - MainWindowViewModel 订阅 NavigationChanged,把当前 view model 反映射成侧栏 索引,因此从首页卡片跳转时侧栏高亮会跟着走。 - MainWindow.axaml.cs 基本清空;ListBox 绑索引,导航由 view model 发起。 这个提交里两处对话框服务的新增是给后面页面用的: - ShowFilesPickerAsync —— 多选,解密页需要 - ShowQrCodeLoginDialogAsync —— 把网易云二维码对话框作为模态窗口承载 - ShowMessageAsync 补进接口。它早已实现、也早已被调用,只是没写进契约。 --- .../Services/DialogService.cs | 63 ++++++++++++++-- .../Services/IDialogService.cs | 14 ++++ .../Services/INavigationService.cs | 10 +++ .../Services/NavigationService.cs | 68 ++++++++++++++++-- .../Services/ServiceCollectionExtensions.cs | 13 +++- .../ViewModels/MainWindowViewModel.cs | 72 +++++++++++++++++-- .../Views/MainWindow.axaml | 18 ++++- .../Views/MainWindow.axaml.cs | 27 ------- 8 files changed, 239 insertions(+), 46 deletions(-) diff --git a/src/ZonyLrcTools.Desktop/Services/DialogService.cs b/src/ZonyLrcTools.Desktop/Services/DialogService.cs index 9e3706e..320d736 100644 --- a/src/ZonyLrcTools.Desktop/Services/DialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/DialogService.cs @@ -2,6 +2,7 @@ using Avalonia; using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform.Storage; +using ZonyLrcTools.Desktop.ViewModels; using ZonyLrcTools.Desktop.Views.Dialogs; namespace ZonyLrcTools.Desktop.Services; @@ -28,22 +29,58 @@ public class DialogService : IDialogService public async Task ShowFilePickerAsync(string title, string[]? filters = null) { - if (MainWindow == null) return null; + var files = await ShowFilesPickerAsync(title, filters); + return files.FirstOrDefault(); + } - var fileTypes = filters?.Select(f => new FilePickerFileType(f) - { - Patterns = new[] { f } - }).ToList(); + public async Task> ShowFilesPickerAsync(string title, string[]? filters = null) + { + if (MainWindow == null) return Array.Empty(); + + var fileTypes = BuildFileTypes(filters); var files = await MainWindow.StorageProvider.OpenFilePickerAsync( new FilePickerOpenOptions { Title = title, - AllowMultiple = false, + AllowMultiple = true, FileTypeFilter = fileTypes }); - return files.FirstOrDefault()?.Path.LocalPath; + return files + .Select(f => f.Path.LocalPath) + .Where(p => !string.IsNullOrEmpty(p)) + .ToList(); + } + + /// + /// Turn a list of bare extensions (".mp3", "mp3", "*.mp3") into Avalonia file type filters. + /// + 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 +99,16 @@ public class DialogService : IDialogService var dialog = new MessageDialog(title, message); await dialog.ShowDialog(MainWindow); } + + public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel) + { + if (MainWindow == null) + { + viewModel.RequestClose(); + return; + } + + var dialog = new QrCodeLoginDialog(viewModel); + await dialog.ShowDialog(MainWindow); + } } diff --git a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs index 0428216..3e1e3ad 100644 --- a/src/ZonyLrcTools.Desktop/Services/IDialogService.cs +++ b/src/ZonyLrcTools.Desktop/Services/IDialogService.cs @@ -1,9 +1,23 @@ +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); + Task ShowConfirmDialogAsync(string title, string message); + Task ShowMessageAsync(string title, string message); + + /// + /// Open the NetEase QR-code login dialog as a modal child of the main window. + /// The returned task completes when the user or the login flow closes it; callers that + /// only want the dialog on screen can ignore it. + /// + Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel); } diff --git a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs index f3697f0..76acbc3 100644 --- a/src/ZonyLrcTools.Desktop/Services/INavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/INavigationService.cs @@ -7,7 +7,17 @@ public interface INavigationService ViewModelBase? CurrentViewModel { get; } event EventHandler? NavigationChanged; + /// + /// Push a page onto the navigation stack. Use for drill-down (detail pages, wizards). + /// TViewModel NavigateTo() where TViewModel : ViewModelBase; + + /// + /// Replace the whole stack with a single page. This is what the sidebar uses: switching + /// sections is not a back-navigable action, so the stack must not grow on every click. + /// + 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..18a7c2b 100644 --- a/src/ZonyLrcTools.Desktop/Services/NavigationService.cs +++ b/src/ZonyLrcTools.Desktop/Services/NavigationService.cs @@ -22,13 +22,43 @@ 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(); + // Already showing this page; do not restart it. + 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 +69,40 @@ 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); } } + + /// + /// Page lifecycle hooks are fire-and-forget from the caller's perspective; an exception thrown + /// inside one must not tear down the navigation call that triggered it. + /// + private static async Task SafeActivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnActivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // A failing OnActivated must not crash navigation. + } + } + + private static async Task SafeDeactivateAsync(ViewModelBase viewModel) + { + try + { + await viewModel.OnDeactivatedAsync().ConfigureAwait(false); + } + catch (Exception) + { + // A failing OnDeactivated must not crash navigation. + } + } } diff --git a/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs b/src/ZonyLrcTools.Desktop/Services/ServiceCollectionExtensions.cs index 7f42578..77fadb0 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,10 @@ public static class ServiceCollectionExtensions services.BeginAutoDependencyInject(); // Configure Common services - services.ConfigureConfiguration(); + // ConfigureConfiguration() from Common always reads config.yaml from the executable + // folder, which breaks portable installs and read-only install locations. The desktop + // app resolves a writable location first and binds from there instead. + services.ConfigureDesktopConfiguration(); services.ConfigureLocalization(); services.ConfigureToolService(); @@ -39,11 +43,18 @@ public static class ServiceCollectionExtensions services.AddSingleton(); services.AddSingleton(); + // Stores the NetEase login cookie between launches so the QR dialog is a first-run event. + services.AddSingleton(); + + // Remembers a manually chosen KuGou database path (machine state, not a user preference). + 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/MainWindowViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/MainWindowViewModel.cs index 479dec8..53c6f52 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,7 @@ 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 +39,87 @@ public partial class MainWindowViewModel : ViewModelBase public MainWindowViewModel( IThemeService themeService, IUILocalizationService localization, - HomeViewModel homeViewModel) + INavigationService navigation) { _themeService = themeService; _localization = localization; + _navigation = navigation; // Subscribe to language changes _localization.LanguageChanged += OnLanguageChanged; - // Set initial page - CurrentPage = homeViewModel; - SelectedNavigationIndex = 0; + // The navigation service is the single owner of "which page is showing". + _navigation.NavigationChanged += OnNavigationChanged; + + NavigateToIndex(0); } + // Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed". + private bool _isSyncingNavigation; + + partial void OnSelectedNavigationIndexChanged(int value) + { + if (_isSyncingNavigation) + { + return; + } + + NavigateToIndex(value); + } + + private void NavigateToIndex(int index) + { + // NavigateRoot keeps the stack depth at one: sidebar switching is not a back-navigable + // action, so clicking around must not grow history. + CurrentPage = index switch + { + 1 => _navigation.NavigateRoot(), + 2 => _navigation.NavigateRoot(), + 3 => _navigation.NavigateRoot(), + 4 => _navigation.NavigateRoot(), + _ => _navigation.NavigateRoot() + }; + } + + private void OnNavigationChanged(object? sender, ViewModelBase viewModel) + { + CurrentPage = viewModel; + + // The home page quick actions navigate directly, so the sidebar has to follow them. + var index = IndexOf(viewModel); + if (index < 0 || index == SelectedNavigationIndex) + { + 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)); diff --git a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml index ee46002..f9db75d 100644 --- a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml +++ b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml @@ -92,8 +92,7 @@ + Margin="0,8,0,0"> + + + + + + + + + + diff --git a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs index 942028f..b7fc324 100644 --- a/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs +++ b/src/ZonyLrcTools.Desktop/Views/MainWindow.axaml.cs @@ -1,6 +1,4 @@ using Avalonia.Controls; -using Microsoft.Extensions.DependencyInjection; -using ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.Views; @@ -10,29 +8,4 @@ public partial class MainWindow : Window { InitializeComponent(); } - - private void OnNavigationSelectionChanged(object? sender, SelectionChangedEventArgs e) - { - if (DataContext is not MainWindowViewModel viewModel) return; - if (sender is not ListBox listBox) return; - - var services = App.Services; - if (services == null) return; - - switch (listBox.SelectedIndex) - { - case 0: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 1: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 2: - viewModel.CurrentPage = services.GetRequiredService(); - break; - case 3: - viewModel.CurrentPage = services.GetRequiredService(); - break; - } - } } From 695c696e7f894159cb1ff8bb89fec861db2ce1f8 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:17:33 +0800 Subject: [PATCH 06/14] =?UTF-8?q?feat(desktop):=20=E8=A1=A5=E5=85=A8?= =?UTF-8?q?=E4=B8=AD=E8=8B=B1=E5=8F=8C=E8=AF=AD=EF=BC=8C=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E6=8C=89=E9=92=AE=E6=8E=92=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 资源文件里本来就有 70 个 key,中英各一套,但只有 7 个真正被引用:DataGrid 的 列头。视图里其余全是硬编码英文(光 HomePage 就有 15 处、SettingsPage 7 处), 所以选中文之后大部分界面仍是英文。 现在两个 resx 各有 154 个 key,键集合完全一致,视图里每个字符串都走 {loc:Localize} 或本地化服务。在设置页切换语言会更新整个窗口,包括写在 view model 里的那些字符串。 按钮渲染也整理了一遍,因为 Fluent 的默认度量放在中文旁边显得参差: - 全局 Button 样式统一 FontSize 13、Padding 16,6、MinHeight 34、CornerRadius 6 并居中,不同页面的按钮高度一致。Button.accent 给主操作加字重。 - 省略号改用中文的 U+2026,而不是三个 ASCII 点 —— 后者落在基线上,跟在汉字 后面会留下明显的空隙。 - MinWidth 原先散落五个值(70/80/100/120/150),收敛成三个(88/108/132), 一排按钮能对齐。 - Button.icon 覆盖透明的箭头/详情按钮,含 hover 与置灰禁用态。 App.axaml 新增图标:ChevronUp、ChevronDown、ChevronRight、Alert、Account。 --- src/ZonyLrcTools.Desktop/App.axaml | 51 ++++ .../Resources/UIStrings.en-US.resx | 265 +++++++++++++++++- .../Resources/UIStrings.resx | 265 +++++++++++++++++- 3 files changed, 569 insertions(+), 12 deletions(-) diff --git a/src/ZonyLrcTools.Desktop/App.axaml b/src/ZonyLrcTools.Desktop/App.axaml index afe9cbc..115fcdb 100644 --- a/src/ZonyLrcTools.Desktop/App.axaml +++ b/src/ZonyLrcTools.Desktop/App.axaml @@ -6,6 +6,50 @@ + + + + + + + + + + + + + @@ -19,6 +63,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/Resources/UIStrings.en-US.resx b/src/ZonyLrcTools.Desktop/Resources/UIStrings.en-US.resx index 7af86e1..4f99cc1 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,257 @@ 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 word file path: + + + 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. + + + 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..1431be1 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,257 @@ 在所选文件夹中没有找到任何音乐文件。 + + + 音乐解密 + + + 音乐解密 + + + 将加密的音乐文件(ncm / qmc / kgm / kgg / kwm)转换为可播放格式 + + + 请选择要解密的加密音乐文件… + + + 添加文件… + + + 并行数: + + + 开始解密 + + + 停止 + + + 暂无文件,请添加文件后开始解密 + + + 清空 + + + 文件 + + + 文件名 + + + 输出路径 + + + 基础设置 + + + 高级设置 + + + 显示高级设置 + + + 歌词设置 + + + 启用翻译歌词 + + + 单行模式(原文与翻译在同一行) + + + 只输出翻译歌词 + + + 跳过已存在的歌词文件 + + + 文件编码: + + + 换行符: + + + 输出罗马音歌词 + + + 屏蔽词 + + + 启用屏蔽词过滤 + + + 屏蔽词文件路径: + + + 标签源 + + + 优先级 + + + 配置文件位置 + + + 设置已保存 + + + 设置保存失败 + + + 修改代理设置后需要重启程序才能生效。 + + + 确定要将所有设置恢复为默认值吗? + + + 快速操作 + + + 解密音乐 + + + 支持网易云、QQ音乐、酷狗、酷我四大歌词源 + + + 多线程并行下载,自动规避覆盖 + + + 支持多种文件编码与翻译歌词输出 + + + 跨平台运行,支持 Windows、Linux 与 macOS + + + 开始使用 + + + 来源 + + + 本地文件夹 + + + CSV 文件 + + + 网易云歌单 + + + 解析 + + + CSV 文件 + + + 请选择 CSV 文件… + + + 选择… + + + 歌单 ID + + + 例如 7224428149(多个歌单用分号分隔) + + + 保存到 + + + 歌词文件的输出目录 + + + 选择… + + + 登录网易云音乐 + + + 请使用手机上的网易云音乐 App 扫描二维码。 + + + 等待扫码… + + + 已扫码,请在手机上确认。 + + + 登录成功。 + + + 功能特性 + + + 版本 + + + 批量下载音乐文件的歌词 + + + 为音乐库获取专辑封面 + + + 解密受保护的音乐文件 + + + 上移 + + + 下移 + + + kgg 解密需要酷狗数据库 KGMusicV3.db(酷狗下载过该歌曲才会写入密钥) + + + 选择数据库文件… + + + 已读取 {0} 个解密密钥 + + + 未找到酷狗数据库,kgg 文件将无法解密 + + + 指定数据库… + + + 缺少酷狗数据库 + + + 查看详情 + + + 解密失败原因 + + + 列表顺序即搜索顺序,用右侧箭头调整优先尝试哪一家。 + + + 退出登录 + + + 清除已保存的登录状态,下次解析歌单需要重新扫码。 + + + 已退出登录,下次解析歌单需要重新扫码。 + + + 登录… + + + 立即扫码登录,不必等到下次解析歌单。 + + + 已登录,解析歌单会直接使用这个会话。 + + + 未登录,解析歌单时会弹出二维码。 + + + 账号状态 + + + 复制 + From c6143156015be9614eb66c4937eccedd4e8255b2 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:17:50 +0800 Subject: [PATCH 07/14] =?UTF-8?q?feat(desktop):=20=E4=B8=93=E8=BE=91?= =?UTF-8?q?=E9=A1=B5=E6=8E=A5=E4=B8=8A=E7=9C=9F=E5=AE=9E=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=EF=BC=8C=E9=A6=96=E9=A1=B5=E5=8D=A1=E7=89=87=E6=8E=A5=E4=B8=8A?= =?UTF-8?q?=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 两个页面看着完成,实际什么都不做。 专辑页:StartDownloadAsync 只有一句注释和 Task.Delay(1000) —— 按钮会亮,进度条 会动,一个文件也不会写。现在它会扫描所选目录(与歌词页相同的 IFileScanner + ITagLoader 路径)、把找到的曲目填进表格,并调用 IAlbumDownloader,用第一个提交 加的回调逐行更新封面落盘状态。"停止"真的会取消。列显示歌曲、艺术家和逐行状态, 头部沿用歌词页那套扫描/下载计数。 首页:两张"快速操作"卡片是没有 Command 的 Button —— 从来没接过任何逻辑。现在 它们分别跳到歌词页、专辑页、解密页;功能列表也做了本地化,不再是四句硬编码 英文。卡片外观不变,只换了命令和文案。 --- .../ViewModels/AlbumDownloadViewModel.cs | 195 +++++++++++++++++- .../ViewModels/HomeViewModel.cs | 84 +++++++- .../Views/Pages/AlbumDownloadPage.axaml | 30 ++- .../Views/Pages/HomePage.axaml | 106 +++++++--- 4 files changed, 359 insertions(+), 56 deletions(-) diff --git a/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/AlbumDownloadViewModel.cs index 6e2b6a7..7ff6e88 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 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,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:"; public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download"; public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download"; + 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 +84,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 +115,8 @@ public partial class AlbumDownloadViewModel : ViewModelBase MusicFiles.CollectionChanged += (_, _) => { OnPropertyChanged(nameof(HasNoFiles)); + OnPropertyChanged(nameof(CanStartDownload)); + StartDownloadCommand.NotifyCanExecuteChanged(); }; } @@ -92,6 +130,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 +141,151 @@ public partial class AlbumDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(EmptyStateText)); } - [RelayCommand] + [RelayCommand(CanExecute = nameof(CanSelectFolder))] private async Task SelectFolderAsync() { - var folder = await _dialogService.ShowFolderPickerAsync("Select Music Folder"); + var folder = await _dialogService.ShowFolderPickerAsync( + _localization?["Album_SelectFolder"] ?? "Select Music Folder"); if (string.IsNullOrEmpty(folder)) return; SelectedFolderPath = folder; - OnPropertyChanged(nameof(CanStartDownload)); + await ScanFilesAsync(); } - [RelayCommand] - private async Task StartDownloadAsync() + private bool CanSelectFolder => !IsScanning && !IsDownloading; + + /// + /// Tag-read the folder the same way the lyrics page does: identical row set, so the user sees + /// the same songs whichever feature they open first. + /// + private async Task ScanFilesAsync() { 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 _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."); + 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 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; + }); + })); + + 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)); + } + } + + [RelayCommand(CanExecute = nameof(CanStartDownload))] + private async Task StartDownloadAsync() + { + if (_scannedMusicInfos.Count == 0) return; + IsDownloading = true; CompletedCount = 0; FailedCount = 0; ProgressPercentage = 0; + TotalCount = _scannedMusicInfos.Count; + + foreach (var vm in MusicFiles) + { + vm.IsProcessed = false; + vm.IsSuccessful = false; + vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending"; + } _downloadCts = new CancellationTokenSource(); 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) { - // User cancelled + // User cancelled. } finally { @@ -147,3 +301,24 @@ 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/HomeViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs index 197da45..23026da 100644 --- a/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs +++ b/src/ZonyLrcTools.Desktop/ViewModels/HomeViewModel.cs @@ -1,15 +1,89 @@ +using System.Reflection; using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using ZonyLrcTools.Desktop.Infrastructure.Localization; +using ZonyLrcTools.Desktop.Services; namespace ZonyLrcTools.Desktop.ViewModels; +/// +/// The landing page. Its only job is to point people at the three things this app actually does, +/// so every quick-action button navigates for real instead of sitting there looking clickable. +/// 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"]; + + // Card copy: title + one-line explanation, both localized. + 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)) + { + // Strip the "+" suffix that SourceLink appends. + 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/Views/Pages/AlbumDownloadPage.axaml b/src/ZonyLrcTools.Desktop/Views/Pages/AlbumDownloadPage.axaml index 0cbb072..9f1571b 100644 --- a/src/ZonyLrcTools.Desktop/Views/Pages/AlbumDownloadPage.axaml +++ b/src/ZonyLrcTools.Desktop/Views/Pages/AlbumDownloadPage.axaml @@ -40,7 +40,7 @@ + + @@ -61,36 +100,35 @@ BoxShadow="0 2 8 0 #0D000000" Padding="24"> - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - + + From c303705ab66d5ae38e323b87f06fbebd1844c876 Mon Sep 17 00:00:00 2001 From: aL1CesT <63580499+aL1CesT@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:18:08 +0800 Subject: [PATCH 08/14] =?UTF-8?q?feat(desktop):=20=E6=AD=8C=E8=AF=8D?= =?UTF-8?q?=E9=A1=B5=E6=94=AF=E6=8C=81=E4=B8=89=E7=A7=8D=E6=9D=A5=E6=BA=90?= =?UTF-8?q?=EF=BC=8C=E5=8A=A0=E7=BD=91=E6=98=93=E4=BA=91=E6=89=AB=E7=A0=81?= =?UTF-8?q?=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 歌词页原先只能扫本地目录。CLI 有三种来源 —— 本地、CSV、网易云歌单 —— 而 网易云那条路在界面上完全走不通。 现在页面有一个来源下拉,以及三行互斥的输入: 本地文件夹 —— 沿用目录选择器 CSV 文件 —— 选一个"歌名,歌手"两列的 .csv 网易云 —— 粘贴一个或多个歌单 ID,用分号分隔 因为网易云那条路需要已登录的会话,这个提交同时加上二维码登录对话框: - QrCodeLoginViewModel 用 QRCoder 把二维码内容渲染成真正的 PNG(CLI 是往日志里 画 ASCII 艺术,在窗口里没法用),下方显示登录状态:等待扫码、已扫码待确认、 成功。 - 关闭对话框即取消登录,而这次能真的停下来,因为扫描器已经接受 CancellationToken(上一个提交)。 - cookie 持久化到 netease.session.json,重启不必重新扫码。页面显示当前是否 已登录:未登录给"登录…"按钮,已登录给"退出登录",退出会同时清掉内存里的 cookie 和文件,下次解析歌单重新扫码。 - 非本地来源还需要指定 .lrc 的落盘目录,因此多一行输出目录,默认 <音乐>/DownloadedLrc。 扫描与下载拆成两步:"解析"把来源返回的歌曲填进表格,"开始下载"才写文件。 进度、逐行状态与取消按钮对三种来源一视同仁。 --- .../ViewModels/LyricsDownloadViewModel.cs | 502 ++++++++++++++++-- .../ViewModels/QrCodeLoginViewModel.cs | 134 +++++ .../Views/Dialogs/QrCodeLoginDialog.axaml | 55 ++ .../Views/Dialogs/QrCodeLoginDialog.axaml.cs | 47 ++ .../Views/Pages/LyricsDownloadPage.axaml | 231 +++++--- .../ZonyLrcTools.Desktop.csproj | 2 + 6 files changed, 880 insertions(+), 91 deletions(-) create mode 100644 src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs create mode 100644 src/ZonyLrcTools.Desktop/Views/Dialogs/QrCodeLoginDialog.axaml create mode 100644 src/ZonyLrcTools.Desktop/Views/Dialogs/QrCodeLoginDialog.axaml.cs diff --git a/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/LyricsDownloadViewModel.cs index c028dfb..7a1d920 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; +/// +/// Which source the lyrics page reads its song list from. +/// +public enum LyricsScannerKind +{ + /// Scan a local folder for audio files. + Local = 0, + + /// Read a CSV file containing "song,artist" rows. + Csv = 1, + + /// Pull a NetEase Cloud Music playlist by id. + 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 CancellationTokenSource? _scanCts; + private readonly Dictionary _musicFileMap = new(); private 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))] + [NotifyPropertyChangedFor(nameof(CanScan))] + private int _selectedScannerIndex; + [ObservableProperty] private int _parallelCount = 2; @@ -53,7 +99,11 @@ public partial class LyricsDownloadViewModel : ViewModelBase [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))] [NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))] + [NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))] + [NotifyCanExecuteChangedFor(nameof(StartScanCommand))] [NotifyPropertyChangedFor(nameof(CanStartDownload))] + [NotifyPropertyChangedFor(nameof(CanScan))] private bool _isScanning; [ObservableProperty] @@ -65,6 +115,12 @@ public partial class LyricsDownloadViewModel : ViewModelBase [ObservableProperty] private double _scanProgressPercentage; + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(NetEaseAccountStatus))] + [NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))] + [NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))] + private bool _isNetEaseLoggedIn; + [ObservableProperty] private string? _currentProcessingFile; @@ -78,6 +134,33 @@ 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"; + public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File"; + public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file..."; + 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."; + + /// + /// Human readable login state. The sign in / sign out buttons alone were not enough: a user + /// who had never signed in could not tell whether a session was stored, and a user who had + /// signed in had no way to notice the cookie was restored from disk. + /// + 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,6 +170,20 @@ public partial class LyricsDownloadViewModel : ViewModelBase public string ColumnFilePath => _localization?["Column_FilePath"] ?? "File Path"; public string ColumnStatus => _localization?["Column_Status"] ?? "Status"; + /// + /// Scanner display names, indexed the same way as . + /// + 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 => !IsDownloading && !IsScanning && MusicFiles.Count > 0; public bool HasNoFiles => MusicFiles.Count == 0; @@ -100,6 +197,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 +207,30 @@ 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; } + // The scanner is a singleton, so a session restored by an earlier page visit is already + // in memory; reflect it right away instead of waiting for the first activation. + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + MusicFiles.CollectionChanged += (_, _) => { OnPropertyChanged(nameof(HasNoFiles)); OnPropertyChanged(nameof(CanStartDownload)); + StartDownloadCommand.NotifyCanExecuteChanged(); }; } @@ -133,6 +245,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,8 +270,11 @@ public partial class LyricsDownloadViewModel : ViewModelBase OnPropertyChanged(nameof(ColumnFilePath)); OnPropertyChanged(nameof(ColumnStatus)); OnPropertyChanged(nameof(EmptyStateText)); + OnPropertyChanged(nameof(ScannerNames)); } + // ---------------------------------------------------------------- selection commands + [RelayCommand(CanExecute = nameof(CanSelectFolder))] private async Task SelectFolderAsync() { @@ -157,21 +288,65 @@ public partial class LyricsDownloadViewModel : ViewModelBase private bool CanSelectFolder => !IsScanning && !IsDownloading; + [RelayCommand(CanExecute = nameof(CanSelectFolder))] + private async Task SelectCsvFileAsync() + { + var file = await _dialogService.ShowFilePickerAsync( + _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]); + if (string.IsNullOrEmpty(file)) return; + + SelectedCsvFilePath = file; + } + + [RelayCommand(CanExecute = nameof(CanSelectFolder))] + private async Task SelectOutputFolderAsync() + { + var folder = await _dialogService.ShowFolderPickerAsync( + _localization?["Lyrics_OutputSelect"] ?? "Select Output Folder"); + if (string.IsNullOrEmpty(folder)) return; + + OutputDirectory = folder; + } + + // ---------------------------------------------------------------- scanning + + /// + /// Whether the current source has enough input to start reading a song list. + /// + public bool CanScan => !IsScanning && !IsDownloading && SelectedScannerIndex switch + { + (int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath), + (int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath), + (int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds), + _ => false + }; + + /// + /// Re-read the song list using the currently selected source. + /// + [RelayCommand(CanExecute = nameof(CanScan))] + private async Task StartScanAsync() + { + switch ((LyricsScannerKind)SelectedScannerIndex) + { + case LyricsScannerKind.Csv: + await ScanCsvFileAsync(); + break; + case LyricsScannerKind.NetEase: + await ScanNetEasePlaylistAsync(); + break; + default: + await ScanFilesAsync(); + break; + } + } + private async Task ScanFilesAsync() { if (string.IsNullOrEmpty(SelectedFolderPath)) return; + ResetCollections(); IsScanning = true; - MusicFiles.Clear(); - _musicFileMap.Clear(); - _scannedMusicInfos.Clear(); - ScanProgressCount = 0; - ScanTotalCount = 0; - ScanProgressPercentage = 0; - TotalCount = 0; - CompletedCount = 0; - FailedCount = 0; - ProgressPercentage = 0; try { @@ -180,11 +355,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase 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)); + await ShowNoMusicFilesAsync(); return; } @@ -201,16 +372,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase 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); + AddRow(musicInfo); } ScanProgressCount++; @@ -224,17 +386,245 @@ public partial class LyricsDownloadViewModel : ViewModelBase } catch (Exception ex) { - await _dialogService.ShowMessageAsync( - _localization?["Common_Error"] ?? "Error", - ex.Message); + await ShowErrorAsync(ex.Message); } finally { IsScanning = false; - OnPropertyChanged(nameof(CanStartDownload)); } } + private async Task ScanCsvFileAsync() + { + if (string.IsNullOrEmpty(SelectedCsvFilePath)) return; + + ResetCollections(); + IsScanning = true; + + try + { + var musicInfos = await _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync( + SelectedCsvFilePath, + RequireOutputDirectory(), + DefaultFileNamePattern); + + AppendScannedMusicInfos(musicInfos); + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message); + } + finally + { + IsScanning = false; + } + } + + private async Task ScanNetEasePlaylistAsync() + { + if (string.IsNullOrWhiteSpace(SongListIds)) return; + + ResetCollections(); + IsScanning = true; + + using var scanCts = new CancellationTokenSource(); + _scanCts = scanCts; + + try + { + await RestoreNetEaseSessionAsync(); + + if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync()) + { + return; + } + + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + + // 扫码等待与歌单请求都要能被打断,否则 Cookie 恰好失效时这里会一直挂着。 + var musicInfos = await _neteaseMusicScanner.GetMusicInfoFromNetEaseMusicSongListAsync( + SongListIds, + RequireOutputDirectory(), + DefaultFileNamePattern, + onQrCodeReady: null, + onStateChanged: null, + cancellationToken: scanCts.Token); + + await PersistNetEaseSessionAsync(); + + AppendScannedMusicInfos(musicInfos); + } + catch (OperationCanceledException) + { + // User closed the login dialog. + } + catch (Exception ex) + { + await ShowErrorAsync(ex.Message); + } + finally + { + _scanCts = null; + IsScanning = false; + + // Whatever happened above - scan ok, user cancelled the QR dialog, request failed - + // the account row must reflect the scanner's real state. Without this the sign-in + // button kept saying "Sign out" after a successful login from the scan flow. + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + } + } + + /// + /// Load a previously saved NetEase session so the QR dialog only appears on first use. + /// + private async Task RestoreNetEaseSessionAsync() + { + if (_neteaseMusicScanner.IsLoggedIn) return; + + var session = await _sessionStore.LoadAsync(); + if (session == null) return; + + _neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken); + } + + private async Task PersistNetEaseSessionAsync() + { + if (!_neteaseMusicScanner.IsLoggedIn) return; + + await _sessionStore.SaveAsync(new NetEaseSession + { + Cookie = _neteaseMusicScanner.Cookie, + CsrfToken = _neteaseMusicScanner.CsrfToken, + SavedAt = DateTimeOffset.Now + }); + } + + /// + /// Show the QR dialog and wait for the scan-and-confirm flow to finish. + /// + private async Task LoginToNetEaseAsync() + { + var loginViewModel = new QrCodeLoginViewModel(_localization); + using var loginCts = new CancellationTokenSource(); + + loginViewModel.Cancelled += (_, _) => loginCts.Cancel(); + + var loginTask = Task.Run(async () => + { + try + { + var isSuccess = await _neteaseMusicScanner.LoginAsync( + payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)), + state => Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)), + loginCts.Token); + + if (isSuccess) + { + Dispatcher.UIThread.Post(() => loginViewModel.Complete()); + } + + return isSuccess; + } + catch (OperationCanceledException) + { + return false; + } + catch (Exception ex) + { + Dispatcher.UIThread.Post(() => loginViewModel.SetError(ex.Message)); + return false; + } + }); + + // The dialog closes itself once the flow calls Complete(), so this await returns as soon + // as the user either confirms on the phone or gives up. + await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel); + + var isSuccess = await loginTask; + if (isSuccess) + { + await PersistNetEaseSessionAsync(); + } + + return isSuccess; + } + + // ---------------------------------------------------------------- shared helpers + + private void ResetCollections() + { + MusicFiles.Clear(); + _musicFileMap.Clear(); + _scannedMusicInfos.Clear(); + ScanProgressCount = 0; + ScanTotalCount = 0; + ScanProgressPercentage = 0; + TotalCount = 0; + CompletedCount = 0; + FailedCount = 0; + ProgressPercentage = 0; + } + + private void AddRow(MusicInfo musicInfo) + { + 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); + } + + /// + /// Fill the grid from a scanner that returns its list in one shot (CSV, NetEase). + /// + 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() + { + return _dialogService.ShowMessageAsync( + _localization?["Common_Info"] ?? "Info", + _localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder."); + } + + private Task ShowErrorAsync(string message) + { + return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message); + } + + // ---------------------------------------------------------------- download + [RelayCommand(CanExecute = nameof(CanStartDownload))] private async Task StartDownloadAsync() { @@ -246,7 +636,6 @@ public partial class LyricsDownloadViewModel : ViewModelBase ProgressPercentage = 0; TotalCount = _scannedMusicInfos.Count; - // Reset all row statuses foreach (var vm in MusicFiles) { vm.IsProcessed = false; @@ -311,6 +700,57 @@ public partial class LyricsDownloadViewModel : ViewModelBase { _downloadCts?.Cancel(); } + + /// + /// Clears the saved NetEase session so the next playlist scan asks for a fresh QR login. + /// + /// Without this the only way to recover from an expired Cookie was to delete + /// netease.session.json by hand. + /// + /// + [RelayCommand(CanExecute = nameof(IsNetEaseLoggedIn))] + private async Task SignOutNetEaseAsync() + { + _neteaseMusicScanner.ClearLoginState(); + await _sessionStore.ClearAsync(); + IsNetEaseLoggedIn = false; + await _dialogService.ShowMessageAsync( + _localization?["Common_Info"] ?? "Info", + _localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login."); + } + + private bool CanSignInNetEase => !IsNetEaseLoggedIn && !IsScanning && !IsDownloading; + + /// + /// Let the user sign in from the page itself instead of discovering the QR dialog only after + /// pressing "Scan" - the button used to be hidden behind one specific scanner choice. + /// + [RelayCommand(CanExecute = nameof(CanSignInNetEase))] + private async Task SignInNetEaseAsync() + { + if (await LoginToNetEaseAsync()) + { + IsNetEaseLoggedIn = true; + } + } + + /// + /// Refresh the visible login state. Called on construction and every time the page is shown, + /// because the session may have been written by an earlier run of the app. + /// + private async Task RefreshNetEaseLoginStateAsync() + { + await RestoreNetEaseSessionAsync(); + IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn; + SignOutNetEaseCommand.NotifyCanExecuteChanged(); + SignInNetEaseCommand.NotifyCanExecuteChanged(); + } + + public override async Task OnActivatedAsync() + { + await base.OnActivatedAsync(); + await RefreshNetEaseLoginStateAsync(); + } } public partial class MusicFileViewModel : ObservableObject diff --git a/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs b/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs new file mode 100644 index 0000000..2a65a58 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/ViewModels/QrCodeLoginViewModel.cs @@ -0,0 +1,134 @@ +using Avalonia.Media.Imaging; +using CommunityToolkit.Mvvm.ComponentModel; +using QRCoder; +using ZonyLrcTools.Common.MusicScanner; +using ZonyLrcTools.Desktop.Infrastructure.Localization; + +namespace ZonyLrcTools.Desktop.ViewModels; + +/// +/// Drives the NetEase QR-code login dialog. +/// +/// +/// Two events cross the dialog boundary in opposite directions: +/// lets the login flow close the window once it is done, and fires when +/// the user closed the window first, so the caller can stop polling instead of waiting forever. +/// +public partial class QrCodeLoginViewModel : ObservableObject +{ + private readonly IUILocalizationService? _localization; + + [ObservableProperty] + private Bitmap? _qrCodeImage; + + [ObservableProperty] + private string _statusText = string.Empty; + + [ObservableProperty] + private bool _hasImage; + + /// + /// Raised when the login flow wants the dialog closed. + /// + public event EventHandler? CloseRequested; + + /// + /// Raised when the user closed the dialog before logging in. + /// + public event EventHandler? Cancelled; + + /// + /// True once the login succeeded; the dialog stays closable but no longer counts as a cancel. + /// + 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."; + + /// + /// Render the QR payload the scanner produced. + /// + public void SetPayload(NetEaseQrCodePayload payload) + { + QrCodeImage = RenderQrCode(payload.Content); + HasImage = QrCodeImage != null; + StatusText = WaitText; + } + + /// + /// Reflect a login-state change reported by the scanner. + /// + public void SetState(NetEaseLoginState state) + { + StatusText = state switch + { + NetEaseLoginState.ScanConfirmed => ScannedText, + NetEaseLoginState.Succeeded => SuccessText, + _ => WaitText + }; + } + + /// + /// Push an error message into the dialog. + /// + public void SetError(string message) + { + StatusText = message; + } + + /// + /// Mark the flow as finished and close the dialog. + /// + public void Complete() + { + IsCompleted = true; + RequestClose(); + } + + /// + /// Ask the dialog to close. + /// + public void RequestClose() + { + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + /// + /// Called by the dialog when its window closed, for whatever reason. + /// + public void NotifyClosed() + { + 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); + var pngBytes = new PngByteQRCode(data).GetGraphic(12); + + return new Bitmap(new MemoryStream(pngBytes)); + } + catch (Exception) + { + // A render failure shows up as the placeholder, not as a crash. + return null; + } + } +} diff --git a/src/ZonyLrcTools.Desktop/Views/Dialogs/QrCodeLoginDialog.axaml b/src/ZonyLrcTools.Desktop/Views/Dialogs/QrCodeLoginDialog.axaml new file mode 100644 index 0000000..e0769a4 --- /dev/null +++ b/src/ZonyLrcTools.Desktop/Views/Dialogs/QrCodeLoginDialog.axaml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + - + + + @@ -134,11 +179,124 @@ - - - + + + + + + + + + + + + + + + + + + + +