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) {