Refactored and cleaned up GetCoverImage code.

This commit is contained in:
Joseph Milazzo 2021-01-26 10:45:44 -06:00
parent ec64bf90c0
commit 1d61d1057e
2 changed files with 41 additions and 37 deletions

View File

@ -32,7 +32,7 @@ namespace API.Tests.Services
} }
[Theory] [Theory]
[InlineData("non existant file.zip", false)] [InlineData("non existent file.zip", false)]
[InlineData("wrong extension.rar", false)] [InlineData("wrong extension.rar", false)]
[InlineData("empty.zip", false)] [InlineData("empty.zip", false)]
[InlineData("flat file.zip", true)] [InlineData("flat file.zip", true)]
@ -45,6 +45,20 @@ namespace API.Tests.Services
Assert.Equal(expected, _archiveService.IsValidArchive(Path.Join(testDirectory, archivePath))); Assert.Equal(expected, _archiveService.IsValidArchive(Path.Join(testDirectory, archivePath)));
} }
[Theory]
[InlineData("non existent file.zip", 0)]
[InlineData("wrong extension.rar", 0)]
[InlineData("empty.zip", 0)]
[InlineData("flat file.zip", 1)]
[InlineData("file in folder in folder.zip", 1)]
[InlineData("file in folder.zip", 1)]
[InlineData("file in folder_alt.zip", 1)]
public void GetNumberOfPagesFromArchiveTest(string archivePath, int expected)
{
var testDirectory = Path.Join(Directory.GetCurrentDirectory(), "../../../Services/Test Data/ArchiveService/Archives");
Assert.Equal(expected, _archiveService.GetNumberOfPagesFromArchive(Path.Join(testDirectory, archivePath)));
}
[Theory] [Theory]
[InlineData("v10.cbz", "v10.expected.jpg")] [InlineData("v10.cbz", "v10.expected.jpg")]
[InlineData("v10 - with folder.cbz", "v10 - with folder.expected.jpg")] [InlineData("v10 - with folder.cbz", "v10 - with folder.expected.jpg")]

View File

@ -11,11 +11,12 @@ using NetVips;
namespace API.Services namespace API.Services
{ {
/// <summary> /// <summary>
/// Responsible for manipulating Archive files. Used by <see cref="CacheService"/> almost exclusively. /// Responsible for manipulating Archive files. Used by <see cref="CacheService"/> and <see cref="ScannerService"/>
/// </summary> /// </summary>
public class ArchiveService : IArchiveService public class ArchiveService : IArchiveService
{ {
private readonly ILogger<ArchiveService> _logger; private readonly ILogger<ArchiveService> _logger;
private const int ThumbnailWidth = 320;
public ArchiveService(ILogger<ArchiveService> logger) public ArchiveService(ILogger<ArchiveService> logger)
{ {
@ -25,7 +26,6 @@ namespace API.Services
public int GetNumberOfPagesFromArchive(string archivePath) public int GetNumberOfPagesFromArchive(string archivePath)
{ {
if (!IsValidArchive(archivePath)) return 0; if (!IsValidArchive(archivePath)) return 0;
_logger.LogDebug($"Getting Page numbers from {archivePath}"); _logger.LogDebug($"Getting Page numbers from {archivePath}");
try try
@ -53,53 +53,43 @@ namespace API.Services
try try
{ {
if (!IsValidArchive(filepath)) return Array.Empty<byte>(); if (!IsValidArchive(filepath)) return Array.Empty<byte>();
//if (string.IsNullOrEmpty(filepath) || !File.Exists(filepath) || !Parser.Parser.IsArchive(filepath)) return Array.Empty<byte>();
_logger.LogDebug($"Extracting Cover image from {filepath}"); _logger.LogDebug($"Extracting Cover image from {filepath}");
using ZipArchive archive = ZipFile.OpenRead(filepath); using ZipArchive archive = ZipFile.OpenRead(filepath);
if (!archive.HasFiles()) return Array.Empty<byte>(); if (!archive.HasFiles()) return Array.Empty<byte>();
var folder = archive.Entries.SingleOrDefault(x => Path.GetFileNameWithoutExtension(x.Name).ToLower() == "folder"); var folder = archive.Entries.SingleOrDefault(x => Path.GetFileNameWithoutExtension(x.Name).ToLower() == "folder");
var entries = archive.Entries.Where(x => Path.HasExtension(x.FullName) && Parser.Parser.IsImage(x.FullName)).OrderBy(x => x.FullName).ToList(); var entries = archive.Entries.Where(x => Path.HasExtension(x.FullName) && Parser.Parser.IsImage(x.FullName)).OrderBy(x => x.FullName).ToList();
ZipArchiveEntry entry; var entry = folder ?? entries[0];
if (folder != null) return createThumbnail ? CreateThumbnail(entry) : ConvertEntryToByteArray(entry);
{
entry = folder;
} else if (!entries.Any())
{
return Array.Empty<byte>();
}
else
{
entry = entries[0];
}
if (createThumbnail)
{
try
{
using var stream = entry.Open();
var thumbnail = Image.ThumbnailStream(stream, 320);
return thumbnail.WriteToBuffer(".jpg");
}
catch (Exception ex)
{
_logger.LogError(ex, "There was a critical error and prevented thumbnail generation.");
}
}
return ExtractEntryToImage(entry);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "There was an exception when reading archive stream."); _logger.LogError(ex, "There was an exception when reading archive stream.");
return Array.Empty<byte>();
} }
return Array.Empty<byte>();
} }
private static byte[] ExtractEntryToImage(ZipArchiveEntry entry) private byte[] CreateThumbnail(ZipArchiveEntry entry)
{
var coverImage = Array.Empty<byte>();
try
{
using var stream = entry.Open();
using var thumbnail = Image.ThumbnailStream(stream, ThumbnailWidth);
coverImage = thumbnail.WriteToBuffer(".jpg");
}
catch (Exception ex)
{
_logger.LogError(ex, "There was a critical error and prevented thumbnail generation. Defaulting to no cover image.");
}
return coverImage;
}
private static byte[] ConvertEntryToByteArray(ZipArchiveEntry entry)
{ {
using var stream = entry.Open(); using var stream = entry.Open();
using var ms = new MemoryStream(); using var ms = new MemoryStream();