fix: 一个坏文件不再中断整批任务

三个问题会让单个坏文件毁掉整次任务:

1. LoggerHelper.LogWarningInfo 在错误码小于 50000 时会把异常重新抛出。
   而这个方法的所有调用点都在 catch 块里,异常于是穿透调用方的 catch,
   整批任务就此中断。现在它只负责记录,要不要往上抛由调用方决定。

2. LyricsDownloader 把"这个源没返回歌词"当成了"这首歌是纯音乐":它把
   IsSuccessful 置为 true 并跳出 provider 循环,后面的源根本没被问到。
   现在只有真正拿到歌词才算成功;空结果会继续问下一个源,所有源都为空
   才判为跳过。

3. LyricsDownloader 在写文件之前就把这一首标成成功。当配置的
   fileEncoding 非法时,写入抛异常、异常被记进日志,而这一首仍然报告
   成功 —— 磁盘上留下 0 字节的 .lrc,界面上却是绿色。现在先做编码转换
   再建文件,失败时不留空壳,也如实报告失败。

顺带:
- IAlbumDownloader / AlbumDownloader 增加可选的逐首回调,调用方据此可以
  渲染进度;CLI 不传,行为不变。
- AlbumDownloader 不再在封面真正写盘之前记成功日志(原先它永远把所有
  曲目都算作成功)。
- 各下载循环补上 WarpTask 的释放;回调抛出的异常会被捕获并记录,不再
  掀翻整次运行。
This commit is contained in:
aL1CesT committed 2026-11-09 04:27:41 +08:00
1 parent 9cfcc02a4a
commit 1c0f8e8d3a
4 files changed
+157 -31

No files matched your search

@@ -1,4 +1,4 @@
using ZonyLrcTools.Common.Infrastructure.DependencyInject; using ZonyLrcTools.Common.Infrastructure.DependencyInject;
using ZonyLrcTools.Common.Infrastructure.Exceptions; using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Extensions; using ZonyLrcTools.Common.Infrastructure.Extensions;
using ZonyLrcTools.Common.Infrastructure.IO; using ZonyLrcTools.Common.Infrastructure.IO;
@@ -27,6 +27,7 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos, public async Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
int parallelCount = 2, int parallelCount = 2,
Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
await _logger.InfoAsync("开始下载专辑图像数据..."); await _logger.InfoAsync("开始下载专辑图像数据...");
@@ -34,31 +35,93 @@ public class AlbumDownloader : IAlbumDownloader, ISingletonDependency
var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase); var provider = AvailableProviders.FirstOrDefault(d => d.DownloaderName == InternalAlbumProviderNames.NetEase);
if (provider == null) 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; return;
} }
var warpTask = new WarpTask(parallelCount); if (parallelCount <= 0)
{
parallelCount = 1;
}
using var warpTask = new WarpTask(parallelCount);
var warpTaskList = needDownloadMusicInfos.Select(info => var warpTaskList = needDownloadMusicInfos.Select(info =>
warpTask.RunAsync(() => warpTask.RunAsync(() =>
Task.Run(async () => Task.Run(async () =>
{ {
_logger.LogSuccessful(info);
try try
{ {
cancellationToken.ThrowIfCancellationRequested();
var album = await provider.DownloadAsync(info.Name, info.Artist); var album = await provider.DownloadAsync(info.Name, info.Artist);
var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png"); var filePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
if (File.Exists(filePath) || album.Length <= 0) $"{Path.GetFileNameWithoutExtension(info.FilePath)}.png");
if (album.Length <= 0)
{ {
info.IsSuccessful = false;
return;
}
// 已存在同名图像视为成功,不重复覆盖用户已有的封面。
if (File.Exists(filePath))
{
info.IsSuccessful = true;
return; return;
} }
await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album); await new FileStream(filePath, FileMode.Create).WriteBytesToFileAsync(album);
info.IsSuccessful = true;
_logger.LogSuccessful(info);
} }
catch (ErrorCodeException ex) catch (ErrorCodeException ex)
{ {
info.IsSuccessful = false;
_logger.LogWarningInfo(ex); _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)); }, cancellationToken), cancellationToken));
await Task.WhenAll(warpTaskList); await Task.WhenAll(warpTaskList);
@@ -1,9 +1,17 @@
namespace ZonyLrcTools.Common.Album; namespace ZonyLrcTools.Common.Album;
public interface IAlbumDownloader public interface IAlbumDownloader
{ {
/// <summary>
/// 使用给定的歌曲信息下载专辑图像,并输出到音乐文件同目录。
/// </summary>
/// <param name="needDownloadMusicInfos">需要下载专辑图像的歌曲信息。</param>
/// <param name="parallelCount">下载线程/并发量。</param>
/// <param name="callback">单首歌曲处理完成之后的回调方法。</param>
/// <param name="cancellationToken">任务取消标记。</param>
Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos, Task DownloadAsync(List<MusicInfo> needDownloadMusicInfos,
int parallelCount = 2, int parallelCount = 2,
Func<MusicInfo, Task>? callback = null,
CancellationToken cancellationToken = default); CancellationToken cancellationToken = default);
IEnumerable<IAlbumProvider> AvailableProviders { get; } IEnumerable<IAlbumProvider> AvailableProviders { get; }
@@ -24,16 +24,17 @@ namespace ZonyLrcTools.Common.Infrastructure.Extensions
/// <summary> /// <summary>
/// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。 /// 使用 <see cref="LogLevel.Warning"/> 级别打印错误日志,并记录异常堆栈。
/// <remarks>
/// 这个方法只负责记录,<b>不会抛出异常</b>。调用点全部位于 catch 块内,
/// 若在此处重新抛出,异常会穿透调用方的 catch 并终止整批任务
/// (例如一首歌的编码配置有误会导致整批歌词下载中断)。
/// 需要向上传播错误时,请由调用方显式决定,而不是让日志方法代劳。
/// </remarks>
/// </summary> /// </summary>
/// <param name="logger">日志记录器的实例。</param> /// <param name="logger">日志记录器的实例。</param>
/// <param name="exception">错误码异常实例。</param> /// <param name="exception">错误码异常实例。</param>
public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception) public static void LogWarningInfo(this IWarpLogger logger, ErrorCodeException exception)
{ {
if (exception.ErrorCode < 50000)
{
throw exception;
}
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}"); sb.Append($"错误代码: {exception.ErrorCode},信息: {ErrorCodeHelperStatic.GetMessage(exception.ErrorCode)}");
sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}"); sb.Append($"\n附加信息:\n {JsonConvert.SerializeObject(exception.AttachObject)}");
@@ -1,4 +1,4 @@
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Text; using System.Text;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using ZonyLrcTools.Common.Configuration; using ZonyLrcTools.Common.Configuration;
@@ -49,22 +49,53 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
parallelCount = 1; parallelCount = 1;
} }
var warpTask = new WarpTask(parallelCount); using var warpTask = new WarpTask(parallelCount);
var downloadTasks = needDownloadMusicInfos.Select(info => var downloadTasks = needDownloadMusicInfos.Select(info =>
warpTask.RunAsync(() => warpTask.RunAsync(() =>
Task.Run(async () => Task.Run(async () =>
{ {
// Try to download lyrics from all available providers. // 依次尝试所有可用的歌词来源,直到某一家真正返回了歌词。
// 某个来源返回空结果是「这家没搜到」,不是「这首歌没有歌词」,必须继续问下一家。
var isFinished = false;
var hasProviderError = false;
foreach (var lyricsProvider in AvailableProviders) foreach (var lyricsProvider in AvailableProviders)
{ {
await DownloadAndWriteLyricsAsync(lyricsProvider, info); var result = await DownloadAndWriteLyricsAsync(lyricsProvider, info);
if (!info.IsSuccessful) continue; if (result == LyricsDownloadResult.Success)
_logger.LogSuccessful(info); {
break; _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)); }, cancellationToken), cancellationToken));
await Task.WhenAll(downloadTasks); 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); await LogFailedSongFilesInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"歌词下载失败列表_{DateTime.Now:yyyyMMddHHmmss}.txt"), needDownloadMusicInfos);
} }
private async Task DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info) private async Task<LyricsDownloadResult> DownloadAndWriteLyricsAsync(ILyricsProvider provider, MusicInfo info)
{ {
try try
{ {
var lyrics = await provider.DownloadAsync(info.Name, info.Artist); var lyrics = await provider.DownloadAsync(info.Name, info.Artist);
// 该来源没有搜到歌词,交给调用方去问下一家,不能在这里判定整首歌完成。
if (lyrics.IsPruneMusic) if (lyrics.IsPruneMusic)
{ {
info.IsSuccessful = true; return LyricsDownloadResult.Empty;
info.IsPruneMusic = true;
return;
} }
// 先把歌词编码成字节,再动磁盘。编码配置有误时(例如 fileEncoding 写成了不存在的名字)
// 这一步就会抛错,此时文件还没被创建,不会留下 0 字节的空壳。
var content = Utf8ToSelectedEncoding(lyrics);
var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!, var newLyricsFilePath = Path.Combine(Path.GetDirectoryName(info.FilePath)!,
$"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc"); $"{Path.GetFileNameWithoutExtension(info.FilePath)}.lrc");
@@ -100,27 +134,47 @@ public class LyricsDownloader : ILyricsDownloader, ISingletonDependency
// Write lyrics to file. // Write lyrics to file.
await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write)) await using (var fileStream = new FileStream(newLyricsFilePath, FileMode.CreateNew, FileAccess.Write))
{ {
await using (var binaryWriter = new BinaryWriter(fileStream, Encoding.UTF8)) await fileStream.WriteAsync(content);
{ await fileStream.FlushAsync();
binaryWriter.Write(Utf8ToSelectedEncoding(lyrics));
binaryWriter.Flush();
}
} }
info.IsSuccessful = true; info.IsSuccessful = true;
info.IsPruneMusic = false;
return LyricsDownloadResult.Success;
} }
catch (ErrorCodeException ex) catch (ErrorCodeException ex)
{ {
_logger.LogWarningInfo(ex); // 失败标记必须放在记录日志之前:LoggerHelper 即便将来再改动行为,
// 也不能让「失败」的歌曲以默认的 IsSuccessful = true 冒出去。
info.IsSuccessful = false; info.IsSuccessful = false;
info.IsPruneMusic = false;
_logger.LogWarningInfo(ex);
return LyricsDownloadResult.Failed;
} }
catch (Exception ex) catch (Exception ex)
{ {
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
info.IsSuccessful = false; info.IsSuccessful = false;
info.IsPruneMusic = false;
await _logger.ErrorAsync($"下载歌词文件时发生错误:{ex.Message},歌曲名: {info.Name},歌手: {info.Artist}。");
return LyricsDownloadResult.Failed;
} }
} }
/// <summary>
/// 单个歌词来源的处理结果。
/// </summary>
private enum LyricsDownloadResult
{
/// <summary>歌词已写入文件。</summary>
Success,
/// <summary>该来源没有返回歌词(既可能是没有收录,也可能是纯音乐)。</summary>
Empty,
/// <summary>该来源处理过程中出错。</summary>
Failed
}
// Convert UTF-8 to selected encoding. // Convert UTF-8 to selected encoding.
private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics) private byte[] Utf8ToSelectedEncoding(LyricsItemCollection lyrics)
{ {