Fixed Delete Series + Issue Covers from Kavita+ (#3784)

This commit is contained in:
Joe Milazzo 2025-05-03 13:46:40 -06:00 committed by GitHub
parent 3a0d33ca13
commit bc41b0256e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 2189 additions and 1596 deletions

View File

@ -28,6 +28,7 @@
<ItemGroup>
<Folder Include="Services\Test Data\ArchiveService\ComicInfos" />
<Folder Include="Services\Test Data\CoverDbService\" />
<Folder Include="Services\Test Data\ImageService\Covers\" />
</ItemGroup>

View File

@ -20,10 +20,11 @@ namespace API.Tests;
public abstract class AbstractDbTest : AbstractFsTest , IDisposable
{
protected readonly DbConnection _connection;
protected readonly DataContext _context;
protected readonly IUnitOfWork _unitOfWork;
protected readonly IMapper _mapper;
protected readonly DataContext Context;
protected readonly IUnitOfWork UnitOfWork;
protected readonly IMapper Mapper;
private readonly DbConnection _connection;
private bool _disposed;
protected AbstractDbTest()
{
@ -34,17 +35,17 @@ public abstract class AbstractDbTest : AbstractFsTest , IDisposable
_connection = RelationalOptionsExtension.Extract(contextOptions).Connection;
_context = new DataContext(contextOptions);
Context = new DataContext(contextOptions);
_context.Database.EnsureCreated(); // Ensure DB schema is created
Context.Database.EnsureCreated(); // Ensure DB schema is created
Task.Run(SeedDb).GetAwaiter().GetResult();
var config = new MapperConfiguration(cfg => cfg.AddProfile<AutoMapperProfiles>());
_mapper = config.CreateMapper();
Mapper = config.CreateMapper();
GlobalConfiguration.Configuration.UseInMemoryStorage();
_unitOfWork = new UnitOfWork(_context, _mapper, null);
UnitOfWork = new UnitOfWork(Context, Mapper, null);
}
private static DbConnection CreateInMemoryDatabase()
@ -59,34 +60,34 @@ public abstract class AbstractDbTest : AbstractFsTest , IDisposable
{
try
{
await _context.Database.EnsureCreatedAsync();
await Context.Database.EnsureCreatedAsync();
var filesystem = CreateFileSystem();
await Seed.SeedSettings(_context, new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem));
await Seed.SeedSettings(Context, new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem));
var setting = await _context.ServerSetting.Where(s => s.Key == ServerSettingKey.CacheDirectory).SingleAsync();
var setting = await Context.ServerSetting.Where(s => s.Key == ServerSettingKey.CacheDirectory).SingleAsync();
setting.Value = CacheDirectory;
setting = await _context.ServerSetting.Where(s => s.Key == ServerSettingKey.BackupDirectory).SingleAsync();
setting = await Context.ServerSetting.Where(s => s.Key == ServerSettingKey.BackupDirectory).SingleAsync();
setting.Value = BackupDirectory;
setting = await _context.ServerSetting.Where(s => s.Key == ServerSettingKey.BookmarkDirectory).SingleAsync();
setting = await Context.ServerSetting.Where(s => s.Key == ServerSettingKey.BookmarkDirectory).SingleAsync();
setting.Value = BookmarkDirectory;
setting = await _context.ServerSetting.Where(s => s.Key == ServerSettingKey.TotalLogs).SingleAsync();
setting = await Context.ServerSetting.Where(s => s.Key == ServerSettingKey.TotalLogs).SingleAsync();
setting.Value = "10";
_context.ServerSetting.Update(setting);
Context.ServerSetting.Update(setting);
_context.Library.Add(new LibraryBuilder("Manga")
Context.Library.Add(new LibraryBuilder("Manga")
.WithAllowMetadataMatching(true)
.WithFolderPath(new FolderPathBuilder(DataDirectory).Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
await Seed.SeedMetadataSettings(_context);
await Seed.SeedMetadataSettings(Context);
return true;
}
@ -101,8 +102,21 @@ public abstract class AbstractDbTest : AbstractFsTest , IDisposable
public void Dispose()
{
_context.Dispose();
_connection.Dispose();
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
Context?.Dispose();
_connection?.Dispose();
}
_disposed = true;
}
/// <summary>
@ -114,9 +128,9 @@ public abstract class AbstractDbTest : AbstractFsTest , IDisposable
{
var role = new AppRole { Id = userId, Name = roleName, NormalizedName = roleName.ToUpper() };
await _context.Roles.AddAsync(role);
await _context.UserRoles.AddAsync(new AppUserRole { UserId = userId, RoleId = userId });
await Context.Roles.AddAsync(role);
await Context.UserRoles.AddAsync(new AppUserRole { UserId = userId, RoleId = userId });
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
}

View File

@ -1,6 +1,7 @@
using System.IO;
using System.IO.Abstractions;
using System.IO.Abstractions.TestingHelpers;
using API.Services.Tasks.Scanner.Parser;

View File

@ -142,7 +142,7 @@ public class ChapterListExtensionsTests
CreateChapter("darker than black", "1", CreateFile("/manga/darker than black.cbz", MangaFormat.Archive), false),
};
Assert.Equal(chapterList.First(), chapterList.GetFirstChapterWithFiles());
Assert.Equal(chapterList[0], chapterList.GetFirstChapterWithFiles());
}
[Fact]
@ -150,13 +150,13 @@ public class ChapterListExtensionsTests
{
var chapterList = new List<Chapter>()
{
CreateChapter("darker than black", API.Services.Tasks.Scanner.Parser.Parser.DefaultChapter, CreateFile("/manga/darker than black.cbz", MangaFormat.Archive), true),
CreateChapter("darker than black", Parser.DefaultChapter, CreateFile("/manga/darker than black.cbz", MangaFormat.Archive), true),
CreateChapter("darker than black", "1", CreateFile("/manga/darker than black.cbz", MangaFormat.Archive), false),
};
chapterList.First().Files = new List<MangaFile>();
chapterList[0].Files = new List<MangaFile>();
Assert.Equal(chapterList.Last(), chapterList.GetFirstChapterWithFiles());
Assert.Equal(chapterList[^1], chapterList.GetFirstChapterWithFiles());
}
@ -181,7 +181,7 @@ public class ChapterListExtensionsTests
CreateChapter("detective comics", API.Services.Tasks.Scanner.Parser.Parser.DefaultChapter, CreateFile("/manga/detective comics #001.cbz", MangaFormat.Archive), true)
};
chapterList[0].ReleaseDate = new DateTime(10, 1, 1);
chapterList[0].ReleaseDate = new DateTime(10, 1, 1, 0, 0, 0, DateTimeKind.Utc);
chapterList[1].ReleaseDate = DateTime.MinValue;
Assert.Equal(0, chapterList.MinimumReleaseYear());
@ -196,8 +196,8 @@ public class ChapterListExtensionsTests
CreateChapter("detective comics", API.Services.Tasks.Scanner.Parser.Parser.DefaultChapter, CreateFile("/manga/detective comics #001.cbz", MangaFormat.Archive), true)
};
chapterList[0].ReleaseDate = new DateTime(2002, 1, 1);
chapterList[1].ReleaseDate = new DateTime(2012, 2, 1);
chapterList[0].ReleaseDate = new DateTime(2002, 1, 1, 0, 0, 0, DateTimeKind.Utc);
chapterList[1].ReleaseDate = new DateTime(2012, 2, 1, 0, 0, 0, DateTimeKind.Utc);
Assert.Equal(2002, chapterList.MinimumReleaseYear());
}

View File

@ -24,9 +24,9 @@ public class SeriesFilterTests : AbstractDbTest
{
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series);
_context.AppUser.RemoveRange(_context.AppUser);
await _context.SaveChangesAsync();
Context.Series.RemoveRange(Context.Series);
Context.AppUser.RemoveRange(Context.AppUser);
await Context.SaveChangesAsync();
}
#region HasProgress
@ -54,18 +54,18 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
// Create read progress on Partial and Full
var readerService = new ReaderService(_unitOfWork, Substitute.For<ILogger<ReaderService>>(),
var readerService = new ReaderService(UnitOfWork, Substitute.For<ILogger<ReaderService>>(),
Substitute.For<IEventHub>(), Substitute.For<IImageService>(),
Substitute.For<IDirectoryService>(), Substitute.For<IScrobblingService>());
// Select Partial and set pages read to 5 on first chapter
var partialSeries = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2);
var partialSeries = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2);
var partialChapter = partialSeries.Volumes.First().Chapters.First();
Assert.True(await readerService.SaveReadingProgress(new ProgressDto()
@ -78,7 +78,7 @@ public class SeriesFilterTests : AbstractDbTest
}, user.Id));
// Select Full and set pages read to 10 on first chapter
var fullSeries = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(3);
var fullSeries = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(3);
var fullChapter = fullSeries.Volumes.First().Chapters.First();
Assert.True(await readerService.SaveReadingProgress(new ProgressDto()
@ -98,7 +98,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasProgress();
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.LessThan, 50, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.LessThan, 50, user.Id)
.ToListAsync();
Assert.Single(queryResult);
@ -111,7 +111,7 @@ public class SeriesFilterTests : AbstractDbTest
var user = await SetupHasProgress();
// Query series with progress <= 50%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.LessThanEqual, 50, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.LessThanEqual, 50, user.Id)
.ToListAsync();
Assert.Equal(2, queryResult.Count);
@ -125,7 +125,7 @@ public class SeriesFilterTests : AbstractDbTest
var user = await SetupHasProgress();
// Query series with progress > 50%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.GreaterThan, 50, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.GreaterThan, 50, user.Id)
.ToListAsync();
Assert.Single(queryResult);
@ -138,7 +138,7 @@ public class SeriesFilterTests : AbstractDbTest
var user = await SetupHasProgress();
// Query series with progress == 100%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.Equal, 100, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.Equal, 100, user.Id)
.ToListAsync();
Assert.Single(queryResult);
@ -151,7 +151,7 @@ public class SeriesFilterTests : AbstractDbTest
var user = await SetupHasProgress();
// Query series with progress < 100%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.LessThan, 100, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.LessThan, 100, user.Id)
.ToListAsync();
Assert.Equal(2, queryResult.Count);
@ -165,7 +165,7 @@ public class SeriesFilterTests : AbstractDbTest
var user = await SetupHasProgress();
// Query series with progress <= 100%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.LessThanEqual, 100, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.LessThanEqual, 100, user.Id)
.ToListAsync();
Assert.Equal(3, queryResult.Count);
@ -188,16 +188,16 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
var readerService = new ReaderService(_unitOfWork, Substitute.For<ILogger<ReaderService>>(),
var readerService = new ReaderService(UnitOfWork, Substitute.For<ILogger<ReaderService>>(),
Substitute.For<IEventHub>(), Substitute.For<IImageService>(),
Substitute.For<IDirectoryService>(), Substitute.For<IScrobblingService>());
// Set progress to 99.99% (99/100 pages read)
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var chapter = series.Volumes.First().Chapters.First();
Assert.True(await readerService.SaveReadingProgress(new ProgressDto()
@ -210,7 +210,7 @@ public class SeriesFilterTests : AbstractDbTest
}, user.Id));
// Query series with progress < 100%
var queryResult = await _context.Series.HasReadingProgress(true, FilterComparison.LessThan, 100, user.Id)
var queryResult = await Context.Series.HasReadingProgress(true, FilterComparison.LessThan, 100, user.Id)
.ToListAsync();
Assert.Single(queryResult);
@ -246,9 +246,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -258,7 +258,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.Equal, ["en"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.Equal, ["en"]).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("en", foundSeries[0].Metadata.Language);
}
@ -268,7 +268,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.NotEqual, ["en"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.NotEqual, ["en"]).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.DoesNotContain(foundSeries, s => s.Metadata.Language == "en");
}
@ -278,7 +278,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.Contains, ["en", "fr"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.Contains, ["en", "fr"]).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Metadata.Language == "en");
Assert.Contains(foundSeries, s => s.Metadata.Language == "fr");
@ -289,7 +289,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.NotContains, ["en", "fr"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.NotContains, ["en", "fr"]).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("es", foundSeries[0].Metadata.Language);
}
@ -300,11 +300,11 @@ public class SeriesFilterTests : AbstractDbTest
await SetupHasLanguage();
// Since "MustContains" matches all the provided languages, no series should match in this case.
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.MustContains, ["en", "fr"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.MustContains, ["en", "fr"]).ToListAsync();
Assert.Empty(foundSeries);
// Single language should work.
foundSeries = await _context.Series.HasLanguage(true, FilterComparison.MustContains, ["en"]).ToListAsync();
foundSeries = await Context.Series.HasLanguage(true, FilterComparison.MustContains, ["en"]).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("en", foundSeries[0].Metadata.Language);
}
@ -314,7 +314,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.Matches, ["e"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.Matches, ["e"]).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains("en", foundSeries.Select(s => s.Metadata.Language));
Assert.Contains("es", foundSeries.Select(s => s.Metadata.Language));
@ -325,7 +325,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(false, FilterComparison.Equal, ["en"]).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(false, FilterComparison.Equal, ["en"]).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -334,7 +334,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasLanguage();
var foundSeries = await _context.Series.HasLanguage(true, FilterComparison.Equal, new List<string>()).ToListAsync();
var foundSeries = await Context.Series.HasLanguage(true, FilterComparison.Equal, new List<string>()).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -345,7 +345,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await _context.Series.HasLanguage(true, FilterComparison.GreaterThan, ["en"]).ToListAsync();
await Context.Series.HasLanguage(true, FilterComparison.GreaterThan, ["en"]).ToListAsync();
});
}
@ -379,9 +379,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -391,7 +391,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.Equal, 100).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.Equal, 100).ToListAsync();
Assert.Single(series);
Assert.Equal("Full", series[0].Name);
}
@ -401,7 +401,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.GreaterThan, 50).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.GreaterThan, 50).ToListAsync();
Assert.Single(series);
Assert.Equal("Full", series[0].Name);
}
@ -411,7 +411,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.GreaterThanEqual, 50).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.GreaterThanEqual, 50).ToListAsync();
Assert.Equal(2, series.Count);
Assert.Contains(series, s => s.Name == "Partial");
Assert.Contains(series, s => s.Name == "Full");
@ -422,7 +422,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.LessThan, 50).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.LessThan, 50).ToListAsync();
Assert.Single(series);
Assert.Equal("None", series[0].Name);
}
@ -432,7 +432,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.LessThanEqual, 50).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.LessThanEqual, 50).ToListAsync();
Assert.Equal(2, series.Count);
Assert.Contains(series, s => s.Name == "None");
Assert.Contains(series, s => s.Name == "Partial");
@ -443,7 +443,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.NotEqual, 100).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.NotEqual, 100).ToListAsync();
Assert.Equal(2, series.Count);
Assert.DoesNotContain(series, s => s.Name == "Full");
}
@ -453,7 +453,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(false, FilterComparison.Equal, 100).ToListAsync();
var series = await Context.Series.HasAverageRating(false, FilterComparison.Equal, 100).ToListAsync();
Assert.Equal(3, series.Count);
}
@ -462,7 +462,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAverageRating();
var series = await _context.Series.HasAverageRating(true, FilterComparison.Equal, -1).ToListAsync();
var series = await Context.Series.HasAverageRating(true, FilterComparison.Equal, -1).ToListAsync();
Assert.Single(series);
Assert.Equal("None", series[0].Name);
}
@ -474,7 +474,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<KavitaException>(async () =>
{
await _context.Series.HasAverageRating(true, FilterComparison.Contains, 50).ToListAsync();
await Context.Series.HasAverageRating(true, FilterComparison.Contains, 50).ToListAsync();
});
}
@ -485,7 +485,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await _context.Series.HasAverageRating(true, (FilterComparison)999, 50).ToListAsync();
await Context.Series.HasAverageRating(true, (FilterComparison)999, 50).ToListAsync();
});
}
@ -519,9 +519,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -531,7 +531,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(true, FilterComparison.Equal, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(true, FilterComparison.Equal, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("Cancelled", foundSeries[0].Name);
}
@ -541,7 +541,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(true, FilterComparison.Contains, new List<PublicationStatus> { PublicationStatus.Cancelled, PublicationStatus.Completed }).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(true, FilterComparison.Contains, new List<PublicationStatus> { PublicationStatus.Cancelled, PublicationStatus.Completed }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "Cancelled");
Assert.Contains(foundSeries, s => s.Name == "Completed");
@ -552,7 +552,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(true, FilterComparison.NotContains, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(true, FilterComparison.NotContains, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "OnGoing");
Assert.Contains(foundSeries, s => s.Name == "Completed");
@ -563,7 +563,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(true, FilterComparison.NotEqual, new List<PublicationStatus> { PublicationStatus.OnGoing }).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(true, FilterComparison.NotEqual, new List<PublicationStatus> { PublicationStatus.OnGoing }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "Cancelled");
Assert.Contains(foundSeries, s => s.Name == "Completed");
@ -574,7 +574,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(false, FilterComparison.Equal, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(false, FilterComparison.Equal, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -583,7 +583,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasPublicationStatus();
var foundSeries = await _context.Series.HasPublicationStatus(true, FilterComparison.Equal, new List<PublicationStatus>()).ToListAsync();
var foundSeries = await Context.Series.HasPublicationStatus(true, FilterComparison.Equal, new List<PublicationStatus>()).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -594,7 +594,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<KavitaException>(async () =>
{
await _context.Series.HasPublicationStatus(true, FilterComparison.BeginsWith, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
await Context.Series.HasPublicationStatus(true, FilterComparison.BeginsWith, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
});
}
@ -605,7 +605,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await _context.Series.HasPublicationStatus(true, (FilterComparison)999, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
await Context.Series.HasPublicationStatus(true, (FilterComparison)999, new List<PublicationStatus> { PublicationStatus.Cancelled }).ToListAsync();
});
}
#endregion
@ -637,9 +637,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -649,7 +649,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.Equal, [AgeRating.G]).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.Equal, [AgeRating.G]).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("G", foundSeries[0].Name);
}
@ -659,7 +659,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.Contains, new List<AgeRating> { AgeRating.G, AgeRating.Mature }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.Contains, new List<AgeRating> { AgeRating.G, AgeRating.Mature }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "G");
Assert.Contains(foundSeries, s => s.Name == "Mature");
@ -670,7 +670,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.NotContains, new List<AgeRating> { AgeRating.Unknown }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.NotContains, new List<AgeRating> { AgeRating.Unknown }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "G");
Assert.Contains(foundSeries, s => s.Name == "Mature");
@ -681,7 +681,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.NotEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.NotEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "Unknown");
Assert.Contains(foundSeries, s => s.Name == "Mature");
@ -692,7 +692,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.GreaterThan, new List<AgeRating> { AgeRating.Unknown }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.GreaterThan, new List<AgeRating> { AgeRating.Unknown }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "G");
Assert.Contains(foundSeries, s => s.Name == "Mature");
@ -703,7 +703,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.GreaterThanEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.GreaterThanEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "G");
Assert.Contains(foundSeries, s => s.Name == "Mature");
@ -714,7 +714,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.LessThan, new List<AgeRating> { AgeRating.Mature }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.LessThan, new List<AgeRating> { AgeRating.Mature }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "Unknown");
Assert.Contains(foundSeries, s => s.Name == "G");
@ -725,7 +725,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.LessThanEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.LessThanEqual, new List<AgeRating> { AgeRating.G }).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "Unknown");
Assert.Contains(foundSeries, s => s.Name == "G");
@ -736,7 +736,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(false, FilterComparison.Equal, new List<AgeRating> { AgeRating.G }).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(false, FilterComparison.Equal, new List<AgeRating> { AgeRating.G }).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -745,7 +745,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasAgeRating();
var foundSeries = await _context.Series.HasAgeRating(true, FilterComparison.Equal, new List<AgeRating>()).ToListAsync();
var foundSeries = await Context.Series.HasAgeRating(true, FilterComparison.Equal, new List<AgeRating>()).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -756,7 +756,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<KavitaException>(async () =>
{
await _context.Series.HasAgeRating(true, FilterComparison.BeginsWith, new List<AgeRating> { AgeRating.G }).ToListAsync();
await Context.Series.HasAgeRating(true, FilterComparison.BeginsWith, new List<AgeRating> { AgeRating.G }).ToListAsync();
});
}
@ -767,7 +767,7 @@ public class SeriesFilterTests : AbstractDbTest
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () =>
{
await _context.Series.HasAgeRating(true, (FilterComparison)999, new List<AgeRating> { AgeRating.G }).ToListAsync();
await Context.Series.HasAgeRating(true, (FilterComparison)999, new List<AgeRating> { AgeRating.G }).ToListAsync();
});
}
@ -801,9 +801,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -813,7 +813,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.Equal, 2020).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.Equal, 2020).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("2020", foundSeries[0].Name);
}
@ -823,7 +823,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.GreaterThan, 2000).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.GreaterThan, 2000).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "2020");
Assert.Contains(foundSeries, s => s.Name == "2025");
@ -834,7 +834,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.LessThan, 2025).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.LessThan, 2025).ToListAsync();
Assert.Equal(2, foundSeries.Count);
Assert.Contains(foundSeries, s => s.Name == "2000");
Assert.Contains(foundSeries, s => s.Name == "2020");
@ -845,7 +845,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.IsInLast, 5).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.IsInLast, 5).ToListAsync();
Assert.Equal(2, foundSeries.Count);
}
@ -854,7 +854,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.IsNotInLast, 5).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.IsNotInLast, 5).ToListAsync();
Assert.Single(foundSeries);
Assert.Contains(foundSeries, s => s.Name == "2000");
}
@ -864,7 +864,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(false, FilterComparison.Equal, 2020).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(false, FilterComparison.Equal, 2020).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -873,7 +873,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasReleaseYear();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.Equal, null).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.Equal, null).ToListAsync();
Assert.Equal(3, foundSeries.Count);
}
@ -889,10 +889,10 @@ public class SeriesFilterTests : AbstractDbTest
.Build())
.Build();
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Library.Add(library);
await Context.SaveChangesAsync();
var foundSeries = await _context.Series.HasReleaseYear(true, FilterComparison.IsEmpty, 0).ToListAsync();
var foundSeries = await Context.Series.HasReleaseYear(true, FilterComparison.IsEmpty, 0).ToListAsync();
Assert.Single(foundSeries);
Assert.Equal("EmptyYear", foundSeries[0].Name);
}
@ -925,14 +925,14 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
var ratingService = new RatingService(_unitOfWork, Substitute.For<IScrobblingService>(), Substitute.For<ILogger<RatingService>>());
var ratingService = new RatingService(UnitOfWork, Substitute.For<IScrobblingService>(), Substitute.For<ILogger<RatingService>>());
// Select 0 Rating
var zeroRating = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2);
var zeroRating = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2);
Assert.NotNull(zeroRating);
Assert.True(await ratingService.UpdateSeriesRating(user, new UpdateRatingDto()
@ -942,7 +942,7 @@ public class SeriesFilterTests : AbstractDbTest
}));
// Select 4.5 Rating
var partialRating = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(3);
var partialRating = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(3);
Assert.True(await ratingService.UpdateSeriesRating(user, new UpdateRatingDto()
{
@ -958,7 +958,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.Equal, 4.5f, user.Id)
.ToListAsync();
@ -971,7 +971,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.GreaterThan, 0, user.Id)
.ToListAsync();
@ -984,7 +984,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.LessThan, 4.5f, user.Id)
.ToListAsync();
@ -997,7 +997,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.IsEmpty, 0, user.Id)
.ToListAsync();
@ -1010,7 +1010,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.GreaterThanEqual, 4.5f, user.Id)
.ToListAsync();
@ -1023,7 +1023,7 @@ public class SeriesFilterTests : AbstractDbTest
{
var user = await SetupHasRating();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasRating(true, FilterComparison.LessThanEqual, 0, user.Id)
.ToListAsync();
@ -1101,9 +1101,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -1113,7 +1113,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.Equal, "My Dress-Up Darling")
.ToListAsync();
@ -1126,7 +1126,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.Equal, "Ijiranaide, Nagatoro-san")
.ToListAsync();
@ -1139,7 +1139,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.BeginsWith, "My Dress")
.ToListAsync();
@ -1152,7 +1152,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.BeginsWith, "Sono Bisque")
.ToListAsync();
@ -1165,7 +1165,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.EndsWith, "Nagatoro")
.ToListAsync();
@ -1178,7 +1178,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.Matches, "Toy With Me")
.ToListAsync();
@ -1191,7 +1191,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasName();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasName(true, FilterComparison.NotEqual, "My Dress-Up Darling")
.ToListAsync();
@ -1235,9 +1235,9 @@ public class SeriesFilterTests : AbstractDbTest
.WithLibrary(library)
.Build();
_context.Users.Add(user);
_context.Library.Add(library);
await _context.SaveChangesAsync();
Context.Users.Add(user);
Context.Library.Add(library);
await Context.SaveChangesAsync();
return user;
}
@ -1247,7 +1247,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.Equal, "I like hippos")
.ToListAsync();
@ -1260,7 +1260,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.BeginsWith, "I like h")
.ToListAsync();
@ -1273,7 +1273,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.EndsWith, "apples")
.ToListAsync();
@ -1286,7 +1286,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.Matches, "like ducks")
.ToListAsync();
@ -1299,7 +1299,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.NotEqual, "I like ducks")
.ToListAsync();
@ -1312,7 +1312,7 @@ public class SeriesFilterTests : AbstractDbTest
{
await SetupHasSummary();
var foundSeries = await _context.Series
var foundSeries = await Context.Series
.HasSummary(true, FilterComparison.IsEmpty, string.Empty)
.ToListAsync();

View File

@ -7,8 +7,8 @@ public class PersonHelperTests : AbstractDbTest
{
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
await _context.SaveChangesAsync();
Context.Series.RemoveRange(Context.Series.ToList());
await Context.SaveChangesAsync();
}
//
// // 1. Test adding new people and keeping existing ones

View File

@ -29,11 +29,11 @@ public class CleanupServiceTests : AbstractDbTest
public CleanupServiceTests() : base()
{
_context.Library.Add(new LibraryBuilder("Manga")
Context.Library.Add(new LibraryBuilder("Manga")
.WithFolderPath(new FolderPathBuilder(Root + "data/").Build())
.Build());
_readerService = new ReaderService(_unitOfWork, Substitute.For<ILogger<ReaderService>>(), Substitute.For<IEventHub>(),
_readerService = new ReaderService(UnitOfWork, Substitute.For<ILogger<ReaderService>>(), Substitute.For<IEventHub>(),
Substitute.For<IImageService>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()), Substitute.For<IScrobblingService>());
}
@ -43,11 +43,11 @@ public class CleanupServiceTests : AbstractDbTest
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
_context.Users.RemoveRange(_context.Users.ToList());
_context.AppUserBookmark.RemoveRange(_context.AppUserBookmark.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
Context.Users.RemoveRange(Context.Users.ToList());
Context.AppUserBookmark.RemoveRange(Context.AppUserBookmark.ToList());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
#endregion
@ -68,18 +68,18 @@ public class CleanupServiceTests : AbstractDbTest
var s = new SeriesBuilder("Test 1").Build();
s.CoverImage = $"{ImageService.GetSeriesFormat(1)}.jpg";
s.LibraryId = 1;
_context.Series.Add(s);
Context.Series.Add(s);
s = new SeriesBuilder("Test 2").Build();
s.CoverImage = $"{ImageService.GetSeriesFormat(3)}.jpg";
s.LibraryId = 1;
_context.Series.Add(s);
Context.Series.Add(s);
s = new SeriesBuilder("Test 3").Build();
s.CoverImage = $"{ImageService.GetSeriesFormat(1000)}.jpg";
s.LibraryId = 1;
_context.Series.Add(s);
Context.Series.Add(s);
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.DeleteSeriesCoverImages();
@ -102,16 +102,16 @@ public class CleanupServiceTests : AbstractDbTest
var s = new SeriesBuilder("Test 1").Build();
s.CoverImage = $"{ImageService.GetSeriesFormat(1)}.jpg";
s.LibraryId = 1;
_context.Series.Add(s);
Context.Series.Add(s);
s = new SeriesBuilder("Test 2").Build();
s.CoverImage = $"{ImageService.GetSeriesFormat(3)}.jpg";
s.LibraryId = 1;
_context.Series.Add(s);
Context.Series.Add(s);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.DeleteSeriesCoverImages();
@ -133,7 +133,7 @@ public class CleanupServiceTests : AbstractDbTest
await ResetDb();
// Add 2 series with cover images
_context.Series.Add(new SeriesBuilder("Test 1")
Context.Series.Add(new SeriesBuilder("Test 1")
.WithVolume(new VolumeBuilder("1")
.WithChapter(new ChapterBuilder(API.Services.Tasks.Scanner.Parser.Parser.DefaultChapter).WithCoverImage("v01_c01.jpg").Build())
.WithCoverImage("v01_c01.jpg")
@ -142,7 +142,7 @@ public class CleanupServiceTests : AbstractDbTest
.WithLibraryId(1)
.Build());
_context.Series.Add(new SeriesBuilder("Test 2")
Context.Series.Add(new SeriesBuilder("Test 2")
.WithVolume(new VolumeBuilder("1")
.WithChapter(new ChapterBuilder(API.Services.Tasks.Scanner.Parser.Parser.DefaultChapter).WithCoverImage("v01_c03.jpg").Build())
.WithCoverImage("v01_c03.jpg")
@ -152,9 +152,9 @@ public class CleanupServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.DeleteChapterCoverImages();
@ -223,7 +223,7 @@ public class CleanupServiceTests : AbstractDbTest
// Delete all Series to reset state
await ResetDb();
_context.Users.Add(new AppUser()
Context.Users.Add(new AppUser()
{
UserName = "Joe",
ReadingLists = new List<ReadingList>()
@ -239,9 +239,9 @@ public class CleanupServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.DeleteReadingListCoverImages();
@ -260,7 +260,7 @@ public class CleanupServiceTests : AbstractDbTest
filesystem.AddFile($"{CacheDirectory}02.jpg", new MockFileData(""));
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
cleanupService.CleanupCacheAndTempDirectories();
Assert.Empty(ds.GetFiles(CacheDirectory, searchOption: SearchOption.AllDirectories));
@ -274,7 +274,7 @@ public class CleanupServiceTests : AbstractDbTest
filesystem.AddFile($"{CacheDirectory}subdir/02.jpg", new MockFileData(""));
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
cleanupService.CleanupCacheAndTempDirectories();
Assert.Empty(ds.GetFiles(CacheDirectory, searchOption: SearchOption.AllDirectories));
@ -297,7 +297,7 @@ public class CleanupServiceTests : AbstractDbTest
filesystem.AddFile($"{BackupDirectory}randomfile.zip", filesystemFile);
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.CleanupBackups();
Assert.Single(ds.GetFiles(BackupDirectory, searchOption: SearchOption.AllDirectories));
@ -319,7 +319,7 @@ public class CleanupServiceTests : AbstractDbTest
});
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.CleanupBackups();
Assert.True(filesystem.File.Exists($"{BackupDirectory}randomfile.zip"));
@ -343,7 +343,7 @@ public class CleanupServiceTests : AbstractDbTest
}
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.CleanupLogs();
Assert.Single(ds.GetFiles(LogDirectory, searchOption: SearchOption.AllDirectories));
@ -372,7 +372,7 @@ public class CleanupServiceTests : AbstractDbTest
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var cleanupService = new CleanupService(_logger, _unitOfWork, _messageHub,
var cleanupService = new CleanupService(_logger, UnitOfWork, _messageHub,
ds);
await cleanupService.CleanupLogs();
Assert.True(filesystem.File.Exists($"{LogDirectory}kavita20200911.log"));
@ -396,36 +396,36 @@ public class CleanupServiceTests : AbstractDbTest
.Build();
series.Library = new LibraryBuilder("Test LIb").Build();
_context.Series.Add(series);
Context.Series.Add(series);
_context.AppUser.Add(new AppUser()
Context.AppUser.Add(new AppUser()
{
UserName = "majora2007"
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Progress);
var user = await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Progress);
await _readerService.MarkChaptersUntilAsRead(user, 1, 5);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
// Validate correct chapters have read status
Assert.Equal(1, (await _unitOfWork.AppUserProgressRepository.GetUserProgressAsync(1, 1)).PagesRead);
Assert.Equal(1, (await UnitOfWork.AppUserProgressRepository.GetUserProgressAsync(1, 1)).PagesRead);
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), _unitOfWork,
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), UnitOfWork,
Substitute.For<IEventHub>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()));
// Delete the Chapter
_context.Chapter.Remove(c);
await _unitOfWork.CommitAsync();
Assert.Empty(await _unitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
Context.Chapter.Remove(c);
await UnitOfWork.CommitAsync();
Assert.Empty(await UnitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
// NOTE: This may not be needed, the underlying DB structure seems fixed as of v0.7
await cleanupService.CleanupDbEntries();
Assert.Empty(await _unitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
Assert.Empty(await UnitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
}
[Fact]
@ -436,7 +436,7 @@ public class CleanupServiceTests : AbstractDbTest
.WithMetadata(new SeriesMetadataBuilder().Build())
.Build();
s.Library = new LibraryBuilder("Test LIb").Build();
_context.Series.Add(s);
Context.Series.Add(s);
var c = new AppUserCollection()
{
@ -446,24 +446,24 @@ public class CleanupServiceTests : AbstractDbTest
Items = new List<Series>() {s}
};
_context.AppUser.Add(new AppUser()
Context.AppUser.Add(new AppUser()
{
UserName = "majora2007",
Collections = new List<AppUserCollection>() {c}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), _unitOfWork,
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), UnitOfWork,
Substitute.For<IEventHub>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()));
// Delete the Chapter
_context.Series.Remove(s);
await _unitOfWork.CommitAsync();
Context.Series.Remove(s);
await UnitOfWork.CommitAsync();
await cleanupService.CleanupDbEntries();
Assert.Empty(await _unitOfWork.CollectionTagRepository.GetAllCollectionsAsync());
Assert.Empty(await UnitOfWork.CollectionTagRepository.GetAllCollectionsAsync());
}
#endregion
@ -480,15 +480,15 @@ public class CleanupServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test LIb").Build();
_context.Series.Add(s);
Context.Series.Add(s);
var user = new AppUser()
{
UserName = "CleanupWantToRead_ShouldRemoveFullyReadSeries",
};
_context.AppUser.Add(user);
Context.AppUser.Add(user);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
// Add want to read
user.WantToRead = new List<AppUserWantToRead>()
@ -498,12 +498,12 @@ public class CleanupServiceTests : AbstractDbTest
SeriesId = s.Id
}
};
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
await _readerService.MarkSeriesAsRead(user, s.Id);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), _unitOfWork,
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), UnitOfWork,
Substitute.For<IEventHub>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()));
@ -511,7 +511,7 @@ public class CleanupServiceTests : AbstractDbTest
await cleanupService.CleanupWantToRead();
var wantToRead =
await _unitOfWork.SeriesRepository.GetWantToReadForUserAsync(user.Id, new UserParams(), new FilterDto());
await UnitOfWork.SeriesRepository.GetWantToReadForUserAsync(user.Id, new UserParams(), new FilterDto());
Assert.Equal(0, wantToRead.TotalCount);
}
@ -533,15 +533,15 @@ public class CleanupServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test Lib").Build();
_context.Series.Add(s);
Context.Series.Add(s);
var user = new AppUser()
{
UserName = "ConsolidateProgress_ShouldRemoveDuplicates",
};
_context.AppUser.Add(user);
Context.AppUser.Add(user);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
// Add 2 progress events
user.Progresses ??= [];
@ -553,7 +553,7 @@ public class CleanupServiceTests : AbstractDbTest
LibraryId = s.LibraryId,
PagesRead = 1,
});
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
// Add a duplicate with higher page number
user.Progresses.Add(new AppUserProgress()
@ -564,18 +564,18 @@ public class CleanupServiceTests : AbstractDbTest
LibraryId = s.LibraryId,
PagesRead = 3,
});
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
Assert.Equal(2, (await _unitOfWork.AppUserProgressRepository.GetAllProgress()).Count());
Assert.Equal(2, (await UnitOfWork.AppUserProgressRepository.GetAllProgress()).Count());
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), _unitOfWork,
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), UnitOfWork,
Substitute.For<IEventHub>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()));
await cleanupService.ConsolidateProgress();
var progress = await _unitOfWork.AppUserProgressRepository.GetAllProgress();
var progress = await UnitOfWork.AppUserProgressRepository.GetAllProgress();
Assert.Single(progress);
Assert.True(progress.First().PagesRead == 3);
@ -601,50 +601,50 @@ public class CleanupServiceTests : AbstractDbTest
{
new VolumeBuilder(API.Services.Tasks.Scanner.Parser.Parser.LooseLeafVolume).WithChapter(c).Build()
};
_context.Series.Add(s);
Context.Series.Add(s);
var user = new AppUser()
{
UserName = "EnsureChapterProgressIsCapped",
Progresses = new List<AppUserProgress>()
};
_context.AppUser.Add(user);
Context.AppUser.Add(user);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
await _readerService.MarkChaptersAsRead(user, s.Id, new List<Chapter>() {c});
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
var chapter = await _unitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await _unitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
var chapter = await UnitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await UnitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
Assert.NotNull(chapter);
Assert.Equal(2, chapter.PagesRead);
// Update chapter to have 1 page
c.Pages = 1;
_unitOfWork.ChapterRepository.Update(c);
await _unitOfWork.CommitAsync();
UnitOfWork.ChapterRepository.Update(c);
await UnitOfWork.CommitAsync();
chapter = await _unitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await _unitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
chapter = await UnitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await UnitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
Assert.NotNull(chapter);
Assert.Equal(2, chapter.PagesRead);
Assert.Equal(1, chapter.Pages);
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), _unitOfWork,
var cleanupService = new CleanupService(Substitute.For<ILogger<CleanupService>>(), UnitOfWork,
Substitute.For<IEventHub>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()));
await cleanupService.EnsureChapterProgressIsCapped();
chapter = await _unitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await _unitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
chapter = await UnitOfWork.ChapterRepository.GetChapterDtoAsync(c.Id);
await UnitOfWork.ChapterRepository.AddChapterModifiers(user.Id, chapter);
Assert.NotNull(chapter);
Assert.Equal(1, chapter.PagesRead);
_context.AppUser.Remove(user);
await _unitOfWork.CommitAsync();
Context.AppUser.Remove(user);
await UnitOfWork.CommitAsync();
}
#endregion

View File

@ -23,24 +23,24 @@ public class CollectionTagServiceTests : AbstractDbTest
private readonly ICollectionTagService _service;
public CollectionTagServiceTests()
{
_service = new CollectionTagService(_unitOfWork, Substitute.For<IEventHub>());
_service = new CollectionTagService(UnitOfWork, Substitute.For<IEventHub>());
}
protected override async Task ResetDb()
{
_context.AppUserCollection.RemoveRange(_context.AppUserCollection.ToList());
_context.Library.RemoveRange(_context.Library.ToList());
Context.AppUserCollection.RemoveRange(Context.AppUserCollection.ToList());
Context.Library.RemoveRange(Context.Library.ToList());
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
private async Task SeedSeries()
{
if (_context.AppUserCollection.Any()) return;
if (Context.AppUserCollection.Any()) return;
var s1 = new SeriesBuilder("Series 1").WithMetadata(new SeriesMetadataBuilder().WithAgeRating(AgeRating.Mature).Build()).Build();
var s2 = new SeriesBuilder("Series 2").WithMetadata(new SeriesMetadataBuilder().WithAgeRating(AgeRating.G).Build()).Build();
_context.Library.Add(new LibraryBuilder("Library 2", LibraryType.Manga)
Context.Library.Add(new LibraryBuilder("Library 2", LibraryType.Manga)
.WithSeries(s1)
.WithSeries(s2)
.Build());
@ -51,9 +51,9 @@ public class CollectionTagServiceTests : AbstractDbTest
new AppUserCollectionBuilder("Tag 1").WithItems(new []{s1}).Build(),
new AppUserCollectionBuilder("Tag 2").WithItems(new []{s1, s2}).WithIsPromoted(true).Build()
};
_unitOfWork.UserRepository.Add(user);
UnitOfWork.UserRepository.Add(user);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
#region DeleteTag
@ -64,7 +64,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Arrange
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Act
@ -72,7 +72,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Assert
Assert.True(result);
var deletedTag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var deletedTag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.Null(deletedTag);
Assert.Single(user.Collections); // Only one collection should remain
}
@ -82,7 +82,7 @@ public class CollectionTagServiceTests : AbstractDbTest
{
// Arrange
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Act - Try to delete a non-existent tag
@ -98,7 +98,7 @@ public class CollectionTagServiceTests : AbstractDbTest
{
// Arrange
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Act
@ -106,7 +106,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Assert
Assert.True(result);
var remainingTag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(2);
var remainingTag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(2);
Assert.NotNull(remainingTag);
Assert.Equal("Tag 2", remainingTag.Title);
Assert.True(remainingTag.Promoted);
@ -121,12 +121,12 @@ public class CollectionTagServiceTests : AbstractDbTest
{
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
user.Collections.Add(new AppUserCollectionBuilder("UpdateTag_ShouldUpdateFields").WithIsPromoted(true).Build());
_unitOfWork.UserRepository.Update(user);
await _unitOfWork.CommitAsync();
UnitOfWork.UserRepository.Update(user);
await UnitOfWork.CommitAsync();
await _service.UpdateTag(new AppUserCollectionDto()
{
@ -137,7 +137,7 @@ public class CollectionTagServiceTests : AbstractDbTest
AgeRating = AgeRating.Unknown
}, 1);
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(3);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(3);
Assert.NotNull(tag);
Assert.True(tag.Promoted);
Assert.False(string.IsNullOrEmpty(tag.Summary));
@ -151,12 +151,12 @@ public class CollectionTagServiceTests : AbstractDbTest
{
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
user.Collections.Add(new AppUserCollectionBuilder("UpdateTag_ShouldNotChangeTitle_WhenNotKavitaSource").WithSource(ScrobbleProvider.Mal).Build());
_unitOfWork.UserRepository.Update(user);
await _unitOfWork.CommitAsync();
UnitOfWork.UserRepository.Update(user);
await UnitOfWork.CommitAsync();
await _service.UpdateTag(new AppUserCollectionDto()
{
@ -167,7 +167,7 @@ public class CollectionTagServiceTests : AbstractDbTest
AgeRating = AgeRating.Unknown
}, 1);
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(3);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(3);
Assert.NotNull(tag);
Assert.Equal("UpdateTag_ShouldNotChangeTitle_WhenNotKavitaSource", tag.Title);
Assert.False(string.IsNullOrEmpty(tag.Summary));
@ -198,8 +198,8 @@ public class CollectionTagServiceTests : AbstractDbTest
// Create a second user
var user2 = new AppUserBuilder("user2", "user2", Seed.DefaultThemes.First()).Build();
_unitOfWork.UserRepository.Add(user2);
await _unitOfWork.CommitAsync();
UnitOfWork.UserRepository.Add(user2);
await UnitOfWork.CommitAsync();
// Act & Assert
var exception = await Assert.ThrowsAsync<KavitaException>(() => _service.UpdateTag(new AppUserCollectionDto()
@ -261,7 +261,7 @@ public class CollectionTagServiceTests : AbstractDbTest
}, 1);
// Assert
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.True(tag.CoverImageLocked);
@ -273,7 +273,7 @@ public class CollectionTagServiceTests : AbstractDbTest
CoverImageLocked = false
}, 1);
tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.False(tag.CoverImageLocked);
Assert.Equal(string.Empty, tag.CoverImage);
@ -286,7 +286,7 @@ public class CollectionTagServiceTests : AbstractDbTest
await SeedSeries();
// Setup a user with admin role
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
await AddUserWithRole(user.Id, PolicyConstants.AdminRole);
@ -300,7 +300,7 @@ public class CollectionTagServiceTests : AbstractDbTest
}, 1);
// Assert
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.True(tag.Promoted);
}
@ -312,7 +312,7 @@ public class CollectionTagServiceTests : AbstractDbTest
await SeedSeries();
// Setup a user with promote role
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Mock to return promote role for the user
@ -327,7 +327,7 @@ public class CollectionTagServiceTests : AbstractDbTest
}, 1);
// Assert
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.True(tag.Promoted);
}
@ -339,7 +339,7 @@ public class CollectionTagServiceTests : AbstractDbTest
await SeedSeries();
// Setup a user with no special roles
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Act - Try to promote a tag without proper role
@ -351,7 +351,7 @@ public class CollectionTagServiceTests : AbstractDbTest
}, 1);
// Assert
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.False(tag.Promoted); // Should remain unpromoted
}
@ -365,15 +365,15 @@ public class CollectionTagServiceTests : AbstractDbTest
{
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Tag 2 has 2 series
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(2);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(2);
Assert.NotNull(tag);
await _service.RemoveTagFromSeries(tag, new[] {1});
var userCollections = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var userCollections = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.Equal(2, userCollections!.Collections.Count);
Assert.Single(tag.Items);
Assert.Equal(2, tag.Items.First().Id);
@ -387,11 +387,11 @@ public class CollectionTagServiceTests : AbstractDbTest
{
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Tag 2 has 2 series
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(2);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(2);
Assert.NotNull(tag);
await _service.RemoveTagFromSeries(tag, new[] {1});
@ -407,15 +407,15 @@ public class CollectionTagServiceTests : AbstractDbTest
{
await SeedSeries();
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
var user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.Collections);
Assert.NotNull(user);
// Tag 1 has 1 series
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
await _service.RemoveTagFromSeries(tag, new[] {1});
var tag2 = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag2 = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.Null(tag2);
}
@ -435,7 +435,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Arrange
await SeedSeries();
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
var initialItemCount = tag.Items.Count;
@ -444,7 +444,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Assert
Assert.True(result);
tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.Equal(initialItemCount, tag.Items.Count); // No items should be removed
}
@ -455,7 +455,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Arrange
await SeedSeries();
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
var initialItemCount = tag.Items.Count;
@ -464,7 +464,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Assert
Assert.True(result);
tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
Assert.Equal(initialItemCount, tag.Items.Count); // No items should be removed
}
@ -475,13 +475,13 @@ public class CollectionTagServiceTests : AbstractDbTest
// Arrange
await SeedSeries();
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.NotNull(tag);
// Force null items list
tag.Items = null;
_unitOfWork.CollectionTagRepository.Update(tag);
await _unitOfWork.CommitAsync();
UnitOfWork.CollectionTagRepository.Update(tag);
await UnitOfWork.CommitAsync();
// Act
var result = await _service.RemoveTagFromSeries(tag, [1]);
@ -489,7 +489,7 @@ public class CollectionTagServiceTests : AbstractDbTest
// Assert
Assert.True(result);
// The tag should not be removed since the items list was null, not empty
var tagAfter = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(1);
var tagAfter = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(1);
Assert.Null(tagAfter);
}
@ -501,21 +501,21 @@ public class CollectionTagServiceTests : AbstractDbTest
// Add a third series with a different age rating
var s3 = new SeriesBuilder("Series 3").WithMetadata(new SeriesMetadataBuilder().WithAgeRating(AgeRating.PG).Build()).Build();
_context.Library.First().Series.Add(s3);
await _unitOfWork.CommitAsync();
Context.Library.First().Series.Add(s3);
await UnitOfWork.CommitAsync();
// Add series 3 to tag 2
var tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(2);
var tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(2);
Assert.NotNull(tag);
tag.Items.Add(s3);
_unitOfWork.CollectionTagRepository.Update(tag);
await _unitOfWork.CommitAsync();
UnitOfWork.CollectionTagRepository.Update(tag);
await UnitOfWork.CommitAsync();
// Act - Remove the series with Mature rating
await _service.RemoveTagFromSeries(tag, new[] {1});
// Assert
tag = await _unitOfWork.CollectionTagRepository.GetCollectionAsync(2);
tag = await UnitOfWork.CollectionTagRepository.GetCollectionAsync(2);
Assert.NotNull(tag);
Assert.Equal(2, tag.Items.Count);

View File

@ -0,0 +1,117 @@
using System.IO;
using System.IO.Abstractions;
using System.Reflection;
using System.Threading.Tasks;
using API.Constants;
using API.Entities.Enums;
using API.Extensions;
using API.Services;
using API.Services.Tasks.Metadata;
using API.SignalR;
using EasyCaching.Core;
using Kavita.Common;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Xunit;
namespace API.Tests.Services;
public class CoverDbServiceTests : AbstractDbTest
{
private readonly DirectoryService _directoryService;
private readonly IEasyCachingProviderFactory _cacheFactory = Substitute.For<IEasyCachingProviderFactory>();
private readonly ICoverDbService _coverDbService;
private static readonly string FaviconPath = Path.Join(Directory.GetCurrentDirectory(),
"../../../Services/Test Data/CoverDbService/Favicons");
/// <summary>
/// Path to download files temp to. Should be empty after each test.
/// </summary>
private static readonly string TempPath = Path.Join(Directory.GetCurrentDirectory(),
"../../../Services/Test Data/CoverDbService/Temp");
public CoverDbServiceTests()
{
_directoryService = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), CreateFileSystem());
var imageService = new ImageService(Substitute.For<ILogger<ImageService>>(), _directoryService);
_coverDbService = new CoverDbService(Substitute.For<ILogger<CoverDbService>>(), _directoryService, _cacheFactory,
Substitute.For<IHostEnvironment>(), imageService, UnitOfWork, Substitute.For<IEventHub>());
}
protected override Task ResetDb()
{
throw new System.NotImplementedException();
}
#region Download Favicon
/// <summary>
/// I cannot figure out how to test this code due to the reliance on the _directoryService.FaviconDirectory and not being
/// able to redirect it to the real filesystem.
/// </summary>
public async Task DownloadFaviconAsync_ShouldDownloadAndMatchExpectedFavicon()
{
// Arrange
var testUrl = "https://anilist.co/anime/6205/Kmpfer/";
var encodeFormat = EncodeFormat.WEBP;
var expectedFaviconPath = Path.Combine(FaviconPath, "anilist.co.webp");
// Ensure TempPath exists
_directoryService.ExistOrCreate(TempPath);
var baseUrl = "https://anilist.co";
// Ensure there is no cache result for this URL
var provider = Substitute.For<IEasyCachingProvider>();
provider.GetAsync<string>(baseUrl).Returns(new CacheValue<string>(null, false));
_cacheFactory.GetCachingProvider(EasyCacheProfiles.Favicon).Returns(provider);
// // Replace favicon directory with TempPath
// var directoryService = (DirectoryService)_directoryService;
// directoryService.FaviconDirectory = TempPath;
// Hack: Swap FaviconDirectory with TempPath for ability to download real files
typeof(DirectoryService)
.GetField("FaviconDirectory", BindingFlags.NonPublic | BindingFlags.Instance)
?.SetValue(_directoryService, TempPath);
// Act
var resultFilename = await _coverDbService.DownloadFaviconAsync(testUrl, encodeFormat);
var actualFaviconPath = Path.Combine(TempPath, resultFilename);
// Assert file exists
Assert.True(File.Exists(actualFaviconPath), "Downloaded favicon does not exist in temp path");
// Load and compare similarity
var similarity = expectedFaviconPath.CalculateSimilarity(actualFaviconPath); // Assuming you have this extension
Assert.True(similarity > 0.9f, $"Image similarity too low: {similarity}");
}
[Fact]
public async Task DownloadFaviconAsync_ShouldThrowKavitaException_WhenPreviouslyFailedUrlExistsInCache()
{
// Arrange
var testUrl = "https://example.com";
var encodeFormat = EncodeFormat.WEBP;
var provider = Substitute.For<IEasyCachingProvider>();
provider.GetAsync<string>(Arg.Any<string>())
.Returns(new CacheValue<string>(string.Empty, true)); // Simulate previous failure
_cacheFactory.GetCachingProvider(EasyCacheProfiles.Favicon).Returns(provider);
// Act & Assert
await Assert.ThrowsAsync<KavitaException>(() =>
_coverDbService.DownloadFaviconAsync(testUrl, encodeFormat));
}
#endregion
}

View File

@ -18,13 +18,13 @@ public class DeviceServiceDbTests : AbstractDbTest
public DeviceServiceDbTests() : base()
{
_deviceService = new DeviceService(_unitOfWork, _logger, Substitute.For<IEmailService>());
_deviceService = new DeviceService(UnitOfWork, _logger, Substitute.For<IEmailService>());
}
protected override async Task ResetDb()
{
_context.Users.RemoveRange(_context.Users.ToList());
await _unitOfWork.CommitAsync();
Context.Users.RemoveRange(Context.Users.ToList());
await UnitOfWork.CommitAsync();
}
@ -39,8 +39,8 @@ public class DeviceServiceDbTests : AbstractDbTest
Devices = new List<Device>()
};
_context.Users.Add(user);
await _unitOfWork.CommitAsync();
Context.Users.Add(user);
await UnitOfWork.CommitAsync();
var device = await _deviceService.Create(new CreateDeviceDto()
{
@ -62,8 +62,8 @@ public class DeviceServiceDbTests : AbstractDbTest
Devices = new List<Device>()
};
_context.Users.Add(user);
await _unitOfWork.CommitAsync();
Context.Users.Add(user);
await UnitOfWork.CommitAsync();
var device = await _deviceService.Create(new CreateDeviceDto()
{

File diff suppressed because it is too large Load Diff

View File

@ -99,14 +99,14 @@ public class ParseScannedFilesTests : AbstractDbTest
{
// Since ProcessFile relies on _readingItemService, we can implement our own versions of _readingItemService so we have control over how the calls work
GlobalConfiguration.Configuration.UseInMemoryStorage();
_scannerHelper = new ScannerHelper(_unitOfWork, testOutputHelper);
_scannerHelper = new ScannerHelper(UnitOfWork, testOutputHelper);
}
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
#region MergeName
@ -206,13 +206,13 @@ public class ParseScannedFilesTests : AbstractDbTest
var library =
await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
LibraryIncludes.Folders | LibraryIncludes.FileTypes);
Assert.NotNull(library);
library.Type = LibraryType.Manga;
var parsedSeries = await psf.ScanLibrariesForSeries(library, new List<string>() {Root + "Data/"}, false,
await _unitOfWork.SeriesRepository.GetFolderPathMap(1));
await UnitOfWork.SeriesRepository.GetFolderPathMap(1));
// Assert.Equal(3, parsedSeries.Values.Count);
@ -251,9 +251,9 @@ public class ParseScannedFilesTests : AbstractDbTest
new MockReadingItemService(ds, Substitute.For<IBookService>()), Substitute.For<IEventHub>());
var directoriesSeen = new HashSet<string>();
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
LibraryIncludes.Folders | LibraryIncludes.FileTypes);
var scanResults = await psf.ScanFiles("C:/Data/", true, await _unitOfWork.SeriesRepository.GetFolderPathMap(1), library);
var scanResults = await psf.ScanFiles("C:/Data/", true, await UnitOfWork.SeriesRepository.GetFolderPathMap(1), library);
foreach (var scanResult in scanResults)
{
directoriesSeen.Add(scanResult.Folder);
@ -270,13 +270,13 @@ public class ParseScannedFilesTests : AbstractDbTest
var psf = new ParseScannedFiles(Substitute.For<ILogger<ParseScannedFiles>>(), ds,
new MockReadingItemService(ds, Substitute.For<IBookService>()), Substitute.For<IEventHub>());
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
LibraryIncludes.Folders | LibraryIncludes.FileTypes);
Assert.NotNull(library);
var directoriesSeen = new HashSet<string>();
var scanResults = await psf.ScanFiles("C:/Data/", false,
await _unitOfWork.SeriesRepository.GetFolderPathMap(1), library);
await UnitOfWork.SeriesRepository.GetFolderPathMap(1), library);
foreach (var scanResult in scanResults)
{
@ -305,10 +305,10 @@ public class ParseScannedFilesTests : AbstractDbTest
var psf = new ParseScannedFiles(Substitute.For<ILogger<ParseScannedFiles>>(), ds,
new MockReadingItemService(ds, Substitute.For<IBookService>()), Substitute.For<IEventHub>());
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
LibraryIncludes.Folders | LibraryIncludes.FileTypes);
Assert.NotNull(library);
var scanResults = await psf.ScanFiles("C:/Data", true, await _unitOfWork.SeriesRepository.GetFolderPathMap(1), library);
var scanResults = await psf.ScanFiles("C:/Data", true, await UnitOfWork.SeriesRepository.GetFolderPathMap(1), library);
Assert.Equal(2, scanResults.Count);
}
@ -334,11 +334,11 @@ public class ParseScannedFilesTests : AbstractDbTest
var psf = new ParseScannedFiles(Substitute.For<ILogger<ParseScannedFiles>>(), ds,
new MockReadingItemService(ds, Substitute.For<IBookService>()), Substitute.For<IEventHub>());
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1,
LibraryIncludes.Folders | LibraryIncludes.FileTypes);
Assert.NotNull(library);
var scanResults = await psf.ScanFiles("C:/Data", false,
await _unitOfWork.SeriesRepository.GetFolderPathMap(1), library);
await UnitOfWork.SeriesRepository.GetFolderPathMap(1), library);
Assert.Single(scanResults);
}
@ -357,8 +357,8 @@ public class ParseScannedFilesTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var fs = new FileSystem();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), fs);
@ -368,7 +368,7 @@ public class ParseScannedFilesTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices(ds, fs);
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(4, postLib.Series.Count);
@ -391,7 +391,7 @@ public class ParseScannedFilesTests : AbstractDbTest
Path.Join(executionerCopyDir, "The Executioner and Her Way of Life Vol. 1 Ch. 0002.cbz"));
// 4 series, of which 2 have volumes as directories
var folderMap = await _unitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id);
var folderMap = await UnitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id);
Assert.Equal(6, folderMap.Count);
var res = await psf.ScanFiles(testDirectoryPath, true, folderMap, postLib);
@ -409,8 +409,8 @@ public class ParseScannedFilesTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var fs = new FileSystem();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), fs);
@ -420,7 +420,7 @@ public class ParseScannedFilesTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices(ds, fs);
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(4, postLib.Series.Count);
@ -438,7 +438,7 @@ public class ParseScannedFilesTests : AbstractDbTest
Path.Join(executionerCopyDir, "The Executioner and Her Way of Life Vol. 2.cbz"));
var res = await psf.ScanFiles(testDirectoryPath, true,
await _unitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
await UnitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
var changes = res.Count(sc => sc.HasChanged);
Assert.Equal(1, changes);
}
@ -452,8 +452,8 @@ public class ParseScannedFilesTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var fs = new FileSystem();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), fs);
@ -463,7 +463,7 @@ public class ParseScannedFilesTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices(ds, fs);
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -476,7 +476,7 @@ public class ParseScannedFilesTests : AbstractDbTest
await Task.Delay(1100); // Ensure at least one second has passed since library scan
var res = await psf.ScanFiles(testDirectoryPath, true,
await _unitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
await UnitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
Assert.DoesNotContain(res, sc => sc.HasChanged);
}
@ -488,8 +488,8 @@ public class ParseScannedFilesTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var fs = new FileSystem();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), fs);
@ -499,7 +499,7 @@ public class ParseScannedFilesTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices(ds, fs);
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -508,8 +508,8 @@ public class ParseScannedFilesTests : AbstractDbTest
Assert.Equal(4, spiceAndWolf.Volumes.Sum(v => v.Chapters.Count));
spiceAndWolf.LastFolderScanned = DateTime.Now.Subtract(TimeSpan.FromMinutes(2));
_context.Series.Update(spiceAndWolf);
await _context.SaveChangesAsync();
Context.Series.Update(spiceAndWolf);
await Context.SaveChangesAsync();
// Add file at series root
var spiceAndWolfDir = Path.Join(testDirectoryPath, "Spice and Wolf");
@ -517,7 +517,7 @@ public class ParseScannedFilesTests : AbstractDbTest
Path.Join(spiceAndWolfDir, "Spice and Wolf Vol. 4.cbz"));
var res = await psf.ScanFiles(testDirectoryPath, true,
await _unitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
await UnitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
var changes = res.Count(sc => sc.HasChanged);
Assert.Equal(2, changes);
}
@ -530,8 +530,8 @@ public class ParseScannedFilesTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var fs = new FileSystem();
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), fs);
@ -541,7 +541,7 @@ public class ParseScannedFilesTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices(ds, fs);
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -550,8 +550,8 @@ public class ParseScannedFilesTests : AbstractDbTest
Assert.Equal(4, spiceAndWolf.Volumes.Sum(v => v.Chapters.Count));
spiceAndWolf.LastFolderScanned = DateTime.Now.Subtract(TimeSpan.FromMinutes(2));
_context.Series.Update(spiceAndWolf);
await _context.SaveChangesAsync();
Context.Series.Update(spiceAndWolf);
await Context.SaveChangesAsync();
// Add file in subfolder
var spiceAndWolfDir = Path.Join(Path.Join(testDirectoryPath, "Spice and Wolf"), "Spice and Wolf Vol. 3");
@ -559,7 +559,7 @@ public class ParseScannedFilesTests : AbstractDbTest
Path.Join(spiceAndWolfDir, "Spice and Wolf Vol. 3 Ch. 0013.cbz"));
var res = await psf.ScanFiles(testDirectoryPath, true,
await _unitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
await UnitOfWork.SeriesRepository.GetFolderPathMap(postLib.Id), postLib);
var changes = res.Count(sc => sc.HasChanged);
Assert.Equal(2, changes);
}

View File

@ -20,7 +20,7 @@ public class RatingServiceTests: AbstractDbTest
public RatingServiceTests()
{
_ratingService = new RatingService(_unitOfWork, Substitute.For<IScrobblingService>(), Substitute.For<ILogger<RatingService>>());
_ratingService = new RatingService(UnitOfWork, Substitute.For<IScrobblingService>(), Substitute.For<ILogger<RatingService>>());
}
[Fact]
@ -28,7 +28,7 @@ public class RatingServiceTests: AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -39,10 +39,10 @@ public class RatingServiceTests: AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var user = await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
JobStorage.Current = new InMemoryStorage();
var result = await _ratingService.UpdateSeriesRating(user, new UpdateRatingDto
@ -53,7 +53,7 @@ public class RatingServiceTests: AbstractDbTest
Assert.True(result);
var ratings = (await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))!
var ratings = (await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))!
.Ratings;
Assert.NotEmpty(ratings);
Assert.Equal(3, ratings.First().Rating);
@ -64,7 +64,7 @@ public class RatingServiceTests: AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -75,9 +75,9 @@ public class RatingServiceTests: AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var user = await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var result = await _ratingService.UpdateSeriesRating(user, new UpdateRatingDto
{
@ -88,7 +88,7 @@ public class RatingServiceTests: AbstractDbTest
Assert.True(result);
JobStorage.Current = new InMemoryStorage();
var ratings = (await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))
var ratings = (await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))
.Ratings;
Assert.NotEmpty(ratings);
Assert.Equal(3, ratings.First().Rating);
@ -103,7 +103,7 @@ public class RatingServiceTests: AbstractDbTest
Assert.True(result2);
var ratings2 = (await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))
var ratings2 = (await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings))
.Ratings;
Assert.NotEmpty(ratings2);
Assert.True(ratings2.Count == 1);
@ -115,7 +115,7 @@ public class RatingServiceTests: AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -125,9 +125,9 @@ public class RatingServiceTests: AbstractDbTest
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var user = await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var result = await _ratingService.UpdateSeriesRating(user, new UpdateRatingDto
{
@ -138,7 +138,7 @@ public class RatingServiceTests: AbstractDbTest
Assert.True(result);
JobStorage.Current = new InMemoryStorage();
var ratings = (await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007",
var ratings = (await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007",
AppUserIncludes.Ratings)!)
.Ratings;
Assert.NotEmpty(ratings);
@ -150,7 +150,7 @@ public class RatingServiceTests: AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -160,9 +160,9 @@ public class RatingServiceTests: AbstractDbTest
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var user = await UnitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Ratings);
var result = await _ratingService.UpdateSeriesRating(user, new UpdateRatingDto
{
@ -177,13 +177,13 @@ public class RatingServiceTests: AbstractDbTest
}
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
_context.AppUserRating.RemoveRange(_context.AppUserRating.ToList());
_context.Genre.RemoveRange(_context.Genre.ToList());
_context.CollectionTag.RemoveRange(_context.CollectionTag.ToList());
_context.Person.RemoveRange(_context.Person.ToList());
_context.Library.RemoveRange(_context.Library.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
Context.AppUserRating.RemoveRange(Context.AppUserRating.ToList());
Context.Genre.RemoveRange(Context.Genre.ToList());
Context.CollectionTag.RemoveRange(Context.CollectionTag.ToList());
Context.Person.RemoveRange(Context.Person.ToList());
Context.Library.RemoveRange(Context.Library.ToList());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -28,13 +28,13 @@ public class ScannerServiceTests : AbstractDbTest
// Set up Hangfire to use in-memory storage for testing
GlobalConfiguration.Configuration.UseInMemoryStorage();
_scannerHelper = new ScannerHelper(_unitOfWork, testOutputHelper);
_scannerHelper = new ScannerHelper(UnitOfWork, testOutputHelper);
}
protected override async Task ResetDb()
{
_context.Library.RemoveRange(_context.Library);
await _context.SaveChangesAsync();
Context.Library.RemoveRange(Context.Library);
await Context.SaveChangesAsync();
}
@ -44,18 +44,18 @@ public class ScannerServiceTests : AbstractDbTest
{
await SetLastScannedInThePast(series, duration, false);
}
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
protected async Task SetLastScannedInThePast(Series series, TimeSpan? duration = null, bool save = true)
{
duration ??= TimeSpan.FromMinutes(2);
series.LastFolderScanned = DateTime.Now.Subtract(duration.Value);
_context.Series.Update(series);
Context.Series.Update(series);
if (save)
{
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
}
@ -66,7 +66,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(4, postLib.Series.Count);
@ -79,7 +79,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -94,7 +94,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -110,7 +110,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -125,7 +125,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -141,7 +141,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -157,7 +157,7 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase);
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -188,7 +188,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -213,7 +213,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -244,7 +244,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -268,7 +268,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -288,7 +288,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -326,7 +326,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -350,7 +350,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -369,7 +369,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -399,7 +399,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -436,7 +436,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -464,7 +464,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -484,13 +484,13 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
library.LibraryExcludePatterns = [new LibraryExcludePattern() {Pattern = "**/Extra/*"}];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -508,13 +508,13 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
library.LibraryExcludePatterns = [new LibraryExcludePattern() {Pattern = "**\\Extra\\*"}];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -541,13 +541,13 @@ public class ScannerServiceTests : AbstractDbTest
new FolderPath() {Path = Path.Join(testDirectoryPath, "Root 2")}
];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(2, postLib.Series.Count);
@ -563,7 +563,7 @@ public class ScannerServiceTests : AbstractDbTest
// Rescan to ensure nothing changes yet again
await scanner.ScanLibrary(library.Id, true);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.Equal(2, postLib.Series.Count);
s = postLib.Series.First(s => s.Name == "Plush");
Assert.Equal(3, s.Volumes.Count);
@ -594,13 +594,13 @@ public class ScannerServiceTests : AbstractDbTest
new FolderPath() {Path = Path.Join(testDirectoryPath, "Root 2")}
];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(2, postLib.Series.Count);
@ -619,7 +619,7 @@ public class ScannerServiceTests : AbstractDbTest
// Rescan to ensure nothing changes yet again
await scanner.ScanLibrary(library.Id, false);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.Equal(2, postLib.Series.Count);
s = postLib.Series.First(s => s.Name == "Plush");
Assert.Equal(3, s.Volumes.Count);
@ -647,14 +647,14 @@ public class ScannerServiceTests : AbstractDbTest
new FolderPath() { Path = Path.Combine(testDirectoryPath, "Root 2") }
];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
// First Scan: Everything should be added
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Contains(postLib.Series, s => s.Name == "Accel");
@ -662,19 +662,19 @@ public class ScannerServiceTests : AbstractDbTest
// Second Scan: Remove Root 2, expect Accel to be removed
library.Folders = [new FolderPath() { Path = Path.Combine(testDirectoryPath, "Root 1") }];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
// Emulate time passage by updating lastFolderScan to be a min in the past
foreach (var s in postLib.Series)
{
s.LastFolderScanned = DateTime.Now.Subtract(TimeSpan.FromMinutes(1));
_context.Series.Update(s);
Context.Series.Update(s);
}
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.DoesNotContain(postLib.Series, s => s.Name == "Accel"); // Ensure Accel is gone
Assert.Contains(postLib.Series, s => s.Name == "Plush");
@ -685,19 +685,19 @@ public class ScannerServiceTests : AbstractDbTest
new FolderPath() { Path = Path.Combine(testDirectoryPath, "Root 1") },
new FolderPath() { Path = Path.Combine(testDirectoryPath, "Root 2") }
];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
// Emulate time passage by updating lastFolderScan to be a min in the past
foreach (var s in postLib.Series)
{
s.LastFolderScanned = DateTime.Now.Subtract(TimeSpan.FromMinutes(1));
_context.Series.Update(s);
Context.Series.Update(s);
}
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.Contains(postLib.Series, s => s.Name == "Accel"); // Accel should be back
Assert.Contains(postLib.Series, s => s.Name == "Plush");
@ -707,7 +707,7 @@ public class ScannerServiceTests : AbstractDbTest
// Fourth Scan: Run again to check stability (should not remove Accel)
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.Contains(postLib.Series, s => s.Name == "Accel");
Assert.Contains(postLib.Series, s => s.Name == "Plush");
@ -732,14 +732,14 @@ public class ScannerServiceTests : AbstractDbTest
new FolderPath() { Path = Path.Combine(testDirectoryPath, "Root 2") }
];
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
// First Scan: Everything should be added
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Contains(postLib.Series, s => s.Name == "Accel");
@ -747,14 +747,14 @@ public class ScannerServiceTests : AbstractDbTest
// Second Scan: Delete the Series
library.Series = [];
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Empty(postLib.Series);
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.Contains(postLib.Series, s => s.Name == "Accel"); // Ensure Accel is gone
Assert.Contains(postLib.Series, s => s.Name == "Plush");
@ -768,13 +768,13 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(4, postLib.Series.Count);
@ -800,9 +800,9 @@ public class ScannerServiceTests : AbstractDbTest
Path.Join(executionerCopyDir, "The Executioner and Her Way of Life Vol. 1 Ch. 0002.cbz"));
await scanner.ScanLibrary(library.Id);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(4, postLib.Series.Count);
@ -827,13 +827,13 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Equal(2, postLib.Series.Count);
@ -841,9 +841,9 @@ public class ScannerServiceTests : AbstractDbTest
Directory.Delete(executionerCopyDir, true);
await scanner.ScanLibrary(library.Id);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
Assert.Single(postLib.Series, s => s.Name == "Spice and Wolf");
@ -859,13 +859,13 @@ public class ScannerServiceTests : AbstractDbTest
var library = await _scannerHelper.GenerateScannerData(testcase, infos);
var testDirectoryPath = library.Folders.First().Path;
_unitOfWork.LibraryRepository.Update(library);
await _unitOfWork.CommitAsync();
UnitOfWork.LibraryRepository.Update(library);
await UnitOfWork.CommitAsync();
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -882,7 +882,7 @@ public class ScannerServiceTests : AbstractDbTest
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -899,7 +899,7 @@ public class ScannerServiceTests : AbstractDbTest
await scanner.ScanLibrary(library.Id);
postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
Assert.Single(postLib.Series);
@ -923,7 +923,7 @@ public class ScannerServiceTests : AbstractDbTest
var scanner = _scannerHelper.CreateServices();
await scanner.ScanLibrary(library.Id);
var postLib = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
var postLib = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(library.Id, LibraryIncludes.Series);
Assert.NotNull(postLib);
// Get the loose leaf volume and confirm each chapter aligns with expectation of Sort Order

View File

@ -28,17 +28,17 @@ public class ScrobblingServiceTests : AbstractDbTest
_logger = Substitute.For<ILogger<ScrobblingService>>();
_emailService = Substitute.For<IEmailService>();
_service = new ScrobblingService(_unitOfWork, Substitute.For<IEventHub>(), _logger, _licenseService, _localizationService, _emailService);
_service = new ScrobblingService(UnitOfWork, Substitute.For<IEventHub>(), _logger, _licenseService, _localizationService, _emailService);
}
protected override async Task ResetDb()
{
_context.ScrobbleEvent.RemoveRange(_context.ScrobbleEvent.ToList());
_context.Series.RemoveRange(_context.Series.ToList());
_context.Library.RemoveRange(_context.Library.ToList());
_context.AppUser.RemoveRange(_context.AppUser.ToList());
Context.ScrobbleEvent.RemoveRange(Context.ScrobbleEvent.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
Context.Library.RemoveRange(Context.Library.ToList());
Context.AppUser.RemoveRange(Context.AppUser.ToList());
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
private async Task SeedData()
@ -54,7 +54,7 @@ public class ScrobblingServiceTests : AbstractDbTest
.Build();
_context.Library.Add(library);
Context.Library.Add(library);
var user = new AppUserBuilder("testuser", "testuser")
//.WithPreferences(new UserPreferencesBuilder().WithAniListScrobblingEnabled(true).Build())
@ -62,9 +62,9 @@ public class ScrobblingServiceTests : AbstractDbTest
user.UserPreferences.AniListScrobblingEnabled = true;
_unitOfWork.UserRepository.Add(user);
UnitOfWork.UserRepository.Add(user);
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
#region ScrobbleWantToReadUpdate Tests
@ -83,7 +83,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, true);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.Equal(ScrobbleEventType.AddWantToRead, events[0].ScrobbleEventType);
Assert.Equal(userId, events[0].AppUserId);
@ -103,7 +103,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, false);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.Equal(ScrobbleEventType.RemoveWantToRead, events[0].ScrobbleEventType);
Assert.Equal(userId, events[0].AppUserId);
@ -126,7 +126,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, true);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.All(events, e => Assert.Equal(ScrobbleEventType.AddWantToRead, e.ScrobbleEventType));
@ -149,7 +149,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, false);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.Contains(events, e => e.ScrobbleEventType == ScrobbleEventType.RemoveWantToRead);
@ -172,7 +172,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, false);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.All(events, e => Assert.Equal(ScrobbleEventType.RemoveWantToRead, e.ScrobbleEventType));
@ -195,7 +195,7 @@ public class ScrobblingServiceTests : AbstractDbTest
await _service.ScrobbleWantToReadUpdate(userId, seriesId, true);
// Assert
var events = await _unitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
var events = await UnitOfWork.ScrobbleRepository.GetAllEventsForSeries(seriesId);
Assert.Single(events);
Assert.Contains(events, e => e.ScrobbleEventType == ScrobbleEventType.AddWantToRead);

View File

@ -56,7 +56,7 @@ public class SeriesServiceTests : AbstractDbTest
var locService = new LocalizationService(ds, new MockHostingEnvironment(),
Substitute.For<IMemoryCache>(), Substitute.For<IUnitOfWork>());
_seriesService = new SeriesService(_unitOfWork, Substitute.For<IEventHub>(),
_seriesService = new SeriesService(UnitOfWork, Substitute.For<IEventHub>(),
Substitute.For<ITaskScheduler>(), Substitute.For<ILogger<SeriesService>>(),
Substitute.For<IScrobblingService>(), locService, Substitute.For<IReadingListService>());
}
@ -65,14 +65,14 @@ public class SeriesServiceTests : AbstractDbTest
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
_context.AppUserRating.RemoveRange(_context.AppUserRating.ToList());
_context.Genre.RemoveRange(_context.Genre.ToList());
_context.CollectionTag.RemoveRange(_context.CollectionTag.ToList());
_context.Person.RemoveRange(_context.Person.ToList());
_context.Library.RemoveRange(_context.Library.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
Context.AppUserRating.RemoveRange(Context.AppUserRating.ToList());
Context.Genre.RemoveRange(Context.Genre.ToList());
Context.CollectionTag.RemoveRange(Context.CollectionTag.ToList());
Context.Person.RemoveRange(Context.Person.ToList());
Context.Library.RemoveRange(Context.Library.ToList());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
private static UpdateRelatedSeriesDto CreateRelationsDto(Series series)
@ -105,7 +105,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -126,7 +126,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var expectedRanges = new[] {"Omake", "Something SP02"};
@ -141,7 +141,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -162,7 +162,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build()
);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.NotEmpty(detail.Chapters);
@ -178,7 +178,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -196,7 +196,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.NotEmpty(detail.Chapters);
@ -212,7 +212,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
.WithVolume(new VolumeBuilder(Parser.LooseLeafVolume)
@ -229,7 +229,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.NotEmpty(detail.Chapters);
@ -248,7 +248,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -263,7 +263,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.NotEmpty(detail.Volumes);
@ -277,7 +277,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -294,7 +294,7 @@ public class SeriesServiceTests : AbstractDbTest
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.NotEmpty(detail.Volumes);
@ -314,7 +314,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -332,7 +332,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
Assert.Equal("Volume 1", detail.Volumes.ElementAt(0).Name);
@ -349,7 +349,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -373,7 +373,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
@ -400,7 +400,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Comic)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Comic)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -424,7 +424,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
@ -450,7 +450,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.ComicVine)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.ComicVine)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -474,7 +474,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
@ -500,7 +500,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -522,7 +522,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
@ -548,7 +548,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.LightNovel)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.LightNovel)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -570,7 +570,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build())
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var detail = await _seriesService.GetSeriesDetail(1, 1);
@ -602,8 +602,8 @@ public class SeriesServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test LIb", LibraryType.Book).Build();
_context.Series.Add(s);
await _context.SaveChangesAsync();
Context.Series.Add(s);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -617,7 +617,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Contains("New Genre".SentenceCase(), series.Metadata.Genres.Select(g => g.Title));
@ -634,10 +634,10 @@ public class SeriesServiceTests : AbstractDbTest
var g = new GenreBuilder("Existing Genre").Build();
s.Metadata.Genres = new List<Genre> {g};
_context.Series.Add(s);
Context.Series.Add(s);
_context.Genre.Add(g);
await _context.SaveChangesAsync();
Context.Genre.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -651,7 +651,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.True(series.Metadata.Genres.Select(g1 => g1.Title).All(g2 => g2 == "New Genre".SentenceCase()));
@ -663,7 +663,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
var g = new PersonBuilder("Existing Person").Build();
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var s = new SeriesBuilder("Test")
.WithMetadata(new SeriesMetadataBuilder()
@ -673,10 +673,10 @@ public class SeriesServiceTests : AbstractDbTest
s.Library = new LibraryBuilder("Test LIb", LibraryType.Book).Build();
_context.Series.Add(s);
Context.Series.Add(s);
_context.Person.Add(g);
await _context.SaveChangesAsync();
Context.Person.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -690,7 +690,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.True(series.Metadata.People.Select(g => g.Person.Name).All(personName => personName == "Existing Person"));
@ -713,10 +713,10 @@ public class SeriesServiceTests : AbstractDbTest
new SeriesMetadataPeople() {Person = new PersonBuilder("Existing Publisher 2").Build(), Role = PersonRole.Publisher}
};
_context.Series.Add(s);
Context.Series.Add(s);
_context.Person.Add(g);
await _context.SaveChangesAsync();
Context.Person.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -731,7 +731,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.True(series.Metadata.People.Select(g => g.Person.Name).All(personName => personName == "Existing Person"));
@ -763,9 +763,9 @@ public class SeriesServiceTests : AbstractDbTest
new SeriesMetadataPeople { Person = new PersonBuilder("Existing Publisher 2").Build(), Role = PersonRole.Publisher }
};
_context.Series.Add(series);
_context.Person.Add(existingPerson);
await _context.SaveChangesAsync();
Context.Series.Add(series);
Context.Person.Add(existingPerson);
await Context.SaveChangesAsync();
// Act: Update series metadata, attempting to update the writer to "Existing Writer"
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
@ -782,7 +782,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
// Reload the series from the database
var updatedSeries = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(series.Id);
var updatedSeries = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(series.Id);
Assert.NotNull(updatedSeries.Metadata);
// Assert that the people list still contains the updated person with the new name
@ -804,10 +804,10 @@ public class SeriesServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test LIb", LibraryType.Book).Build();
var g = new PersonBuilder("Existing Person").Build();
_context.Series.Add(s);
Context.Series.Add(s);
_context.Person.Add(g);
await _context.SaveChangesAsync();
Context.Person.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -821,7 +821,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.False(series.Metadata.People.Any());
@ -839,10 +839,10 @@ public class SeriesServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test LIb", LibraryType.Book).Build();
var g = new PersonBuilder("Existing Person").Build();
_context.Series.Add(s);
Context.Series.Add(s);
_context.Person.Add(g);
await _context.SaveChangesAsync();
Context.Person.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -857,7 +857,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.True(series.Metadata.People.Count != 0);
@ -891,10 +891,10 @@ public class SeriesServiceTests : AbstractDbTest
var g = new GenreBuilder("Existing Genre").Build();
s.Metadata.Genres = new List<Genre> {g};
s.Metadata.GenresLocked = true;
_context.Series.Add(s);
Context.Series.Add(s);
_context.Genre.Add(g);
await _context.SaveChangesAsync();
Context.Genre.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -909,7 +909,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.True(series.Metadata.Genres.Select(g => g.Title).All(g => g == "Existing Genre".SentenceCase()));
@ -924,8 +924,8 @@ public class SeriesServiceTests : AbstractDbTest
.WithMetadata(new SeriesMetadataBuilder().Build())
.Build();
s.Library = new LibraryBuilder("Test LIb", LibraryType.Book).Build();
_context.Series.Add(s);
await _context.SaveChangesAsync();
Context.Series.Add(s);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -939,7 +939,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Equal(0, series.Metadata.ReleaseYear);
@ -958,8 +958,8 @@ public class SeriesServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test Lib", LibraryType.Book).Build();
_context.Series.Add(s);
await _context.SaveChangesAsync();
Context.Series.Add(s);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -972,7 +972,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Contains("New Genre".SentenceCase(), series.Metadata.Genres.Select(g => g.Title));
@ -991,9 +991,9 @@ public class SeriesServiceTests : AbstractDbTest
var g = new GenreBuilder("Existing Genre").Build();
s.Metadata.Genres = new List<Genre> { g };
_context.Series.Add(s);
_context.Genre.Add(g);
await _context.SaveChangesAsync();
Context.Series.Add(s);
Context.Genre.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -1006,7 +1006,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.DoesNotContain("Existing Genre".SentenceCase(), series.Metadata.Genres.Select(g => g.Title));
@ -1025,9 +1025,9 @@ public class SeriesServiceTests : AbstractDbTest
var g = new GenreBuilder("Existing Genre").Build();
s.Metadata.Genres = new List<Genre> { g };
_context.Series.Add(s);
_context.Genre.Add(g);
await _context.SaveChangesAsync();
Context.Series.Add(s);
Context.Genre.Add(g);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -1040,7 +1040,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Empty(series.Metadata.Genres);
@ -1058,8 +1058,8 @@ public class SeriesServiceTests : AbstractDbTest
.Build();
s.Library = new LibraryBuilder("Test Lib", LibraryType.Book).Build();
_context.Series.Add(s);
await _context.SaveChangesAsync();
Context.Series.Add(s);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -1072,7 +1072,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Contains("New Tag".SentenceCase(), series.Metadata.Tags.Select(t => t.Title));
@ -1090,9 +1090,9 @@ public class SeriesServiceTests : AbstractDbTest
var t = new TagBuilder("Existing Tag").Build();
s.Metadata.Tags = new List<Tag> { t };
_context.Series.Add(s);
_context.Tag.Add(t);
await _context.SaveChangesAsync();
Context.Series.Add(s);
Context.Tag.Add(t);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -1105,7 +1105,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.DoesNotContain("Existing Tag".SentenceCase(), series.Metadata.Tags.Select(t => t.Title));
@ -1124,9 +1124,9 @@ public class SeriesServiceTests : AbstractDbTest
var t = new TagBuilder("Existing Tag").Build();
s.Metadata.Tags = new List<Tag> { t };
_context.Series.Add(s);
_context.Tag.Add(t);
await _context.SaveChangesAsync();
Context.Series.Add(s);
Context.Tag.Add(t);
await Context.SaveChangesAsync();
var success = await _seriesService.UpdateSeriesMetadata(new UpdateSeriesMetadataDto
{
@ -1139,7 +1139,7 @@ public class SeriesServiceTests : AbstractDbTest
Assert.True(success);
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
var series = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(s.Id);
Assert.NotNull(series);
Assert.NotNull(series.Metadata);
Assert.Empty(series.Metadata.Tags);
@ -1276,7 +1276,7 @@ public class SeriesServiceTests : AbstractDbTest
public async Task UpdateRelatedSeries_ShouldAddAllRelations()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1295,9 +1295,9 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(2);
@ -1312,7 +1312,7 @@ public class SeriesServiceTests : AbstractDbTest
public async Task UpdateRelatedSeries_ShouldAddPrequelWhenAddingSequel()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1330,10 +1330,10 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series2 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series2 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Sequels.Add(2);
@ -1348,7 +1348,7 @@ public class SeriesServiceTests : AbstractDbTest
public async Task UpdateRelatedSeries_DeleteAllRelations()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1367,9 +1367,9 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(2);
@ -1392,7 +1392,7 @@ public class SeriesServiceTests : AbstractDbTest
public async Task UpdateRelatedSeries_DeleteTargetSeries_ShouldSucceed()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1410,9 +1410,9 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(2);
@ -1421,10 +1421,10 @@ public class SeriesServiceTests : AbstractDbTest
Assert.NotNull(series1);
Assert.Equal(2, series1.Relations.Single(s => s.TargetSeriesId == 2).TargetSeriesId);
_context.Series.Remove(await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2));
Context.Series.Remove(await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2));
try
{
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
catch (Exception)
{
@ -1432,14 +1432,14 @@ public class SeriesServiceTests : AbstractDbTest
}
// Remove relations
Assert.Empty((await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related)).Relations);
Assert.Empty((await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related)).Relations);
}
[Fact]
public async Task UpdateRelatedSeries_DeleteSourceSeries_ShouldSucceed()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1457,9 +1457,9 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(2);
@ -1467,12 +1467,12 @@ public class SeriesServiceTests : AbstractDbTest
Assert.NotNull(series1);
Assert.Equal(2, series1.Relations.Single(s => s.TargetSeriesId == 2).TargetSeriesId);
var seriesToRemove = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
var seriesToRemove = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1);
Assert.NotNull(seriesToRemove);
_context.Series.Remove(seriesToRemove);
Context.Series.Remove(seriesToRemove);
try
{
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
catch (Exception)
{
@ -1480,14 +1480,14 @@ public class SeriesServiceTests : AbstractDbTest
}
// Remove relations
Assert.Empty((await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2, SeriesIncludes.Related)).Relations);
Assert.Empty((await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2, SeriesIncludes.Related)).Relations);
}
[Fact]
public async Task UpdateRelatedSeries_ShouldNotAllowDuplicates()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1505,9 +1505,9 @@ public class SeriesServiceTests : AbstractDbTest
}
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var relation = new SeriesRelation
{
Series = series1,
@ -1532,7 +1532,7 @@ public class SeriesServiceTests : AbstractDbTest
public async Task GetRelatedSeries_EditionPrequelSequel_ShouldNotHaveParent()
{
await ResetDb();
_context.Library.Add(new Library
Context.Library.Add(new Library
{
AppUsers = new List<AppUser>
{
@ -1552,8 +1552,8 @@ public class SeriesServiceTests : AbstractDbTest
new SeriesBuilder("Test Series Adaption").Build(),
}
});
await _context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
await Context.SaveChangesAsync();
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Editions.Add(2);
@ -1579,30 +1579,30 @@ public class SeriesServiceTests : AbstractDbTest
.WithSeries(new SeriesBuilder("Test Series Sequels").Build())
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.Build();
_context.Library.Add(lib);
Context.Library.Add(lib);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(2);
addRelationDto.Sequels.Add(3);
await _seriesService.UpdateRelatedSeries(addRelationDto);
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(lib.Id);
_unitOfWork.LibraryRepository.Delete(library);
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(lib.Id);
UnitOfWork.LibraryRepository.Delete(library);
try
{
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
catch (Exception)
{
Assert.False(true);
}
Assert.Null(await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1));
Assert.Null(await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1));
}
[Fact]
@ -1623,7 +1623,7 @@ public class SeriesServiceTests : AbstractDbTest
.WithSeries(new SeriesBuilder("Test Series Sequels").Build())
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.Build();
_context.Library.Add(lib1);
Context.Library.Add(lib1);
var lib2 = new LibraryBuilder("Test LIb 2", LibraryType.Book)
.WithSeries(new SeriesBuilder("Test Series 2").Build())
@ -1631,29 +1631,29 @@ public class SeriesServiceTests : AbstractDbTest
.WithSeries(new SeriesBuilder("Test Series Prequels 3").Build())// TODO: Is this a bug
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.Build();
_context.Library.Add(lib2);
Context.Library.Add(lib2);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1, SeriesIncludes.Related);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
addRelationDto.Adaptations.Add(4); // cross library link
await _seriesService.UpdateRelatedSeries(addRelationDto);
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(lib1.Id, LibraryIncludes.Series);
_unitOfWork.LibraryRepository.Delete(library);
var library = await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(lib1.Id, LibraryIncludes.Series);
UnitOfWork.LibraryRepository.Delete(library);
try
{
await _unitOfWork.CommitAsync();
await UnitOfWork.CommitAsync();
}
catch (Exception)
{
Assert.False(true);
}
Assert.Null(await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(1));
Assert.Null(await UnitOfWork.LibraryRepository.GetLibraryForIdAsync(1));
}
#endregion
@ -1675,13 +1675,13 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty)
.WithLocale("en")
.Build())
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
Assert.Equal(expected, await _seriesService.FormatChapterName(1, libraryType, withHash));
}
@ -1846,18 +1846,18 @@ public class SeriesServiceTests : AbstractDbTest
.WithSeries(new SeriesBuilder("Test Series Sequels").Build())
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.Build();
_context.Library.Add(lib1);
Context.Library.Add(lib1);
var lib2 = new LibraryBuilder("Test LIb 2", LibraryType.Book)
.WithSeries(new SeriesBuilder("Test Series 2").Build())
.WithSeries(new SeriesBuilder("Test Series Prequels 2").Build())
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.Build();
_context.Library.Add(lib2);
Context.Library.Add(lib2);
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var series1 = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1,
var series1 = await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1,
SeriesIncludes.Related | SeriesIncludes.ExternalRatings);
// Add relations
var addRelationDto = CreateRelationsDto(series1);
@ -1903,12 +1903,12 @@ public class SeriesServiceTests : AbstractDbTest
}
};
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
// Ensure we can delete the series
Assert.True(await _seriesService.DeleteMultipleSeries(new[] {1, 2}));
Assert.Null(await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(1));
Assert.Null(await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(2));
Assert.Null(await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(1));
Assert.Null(await UnitOfWork.SeriesRepository.GetSeriesByIdAsync(2));
}
#endregion
@ -1920,7 +1920,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -1933,7 +1933,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var nextChapter = await _seriesService.GetEstimatedChapterCreationDate(1, 1);
Assert.Equal(Parser.LooseLeafVolumeNumber, nextChapter.VolumeNumber);
@ -1945,7 +1945,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
.WithPublicationStatus(PublicationStatus.Completed)
@ -1958,7 +1958,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var nextChapter = await _seriesService.GetEstimatedChapterCreationDate(1, 1);
Assert.Equal(Parser.LooseLeafVolumeNumber, nextChapter.VolumeNumber);
@ -1970,7 +1970,7 @@ public class SeriesServiceTests : AbstractDbTest
{
await ResetDb();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
@ -1982,7 +1982,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var nextChapter = await _seriesService.GetEstimatedChapterCreationDate(1, 1);
Assert.NotNull(nextChapter);
@ -1996,7 +1996,7 @@ public class SeriesServiceTests : AbstractDbTest
await ResetDb();
var now = DateTime.Parse("2021-01-01", CultureInfo.InvariantCulture); // 10/31/2024 can trigger an edge case bug
_context.Library.Add(new LibraryBuilder("Test LIb")
Context.Library.Add(new LibraryBuilder("Test LIb")
.WithAppUser(new AppUserBuilder("majora2007", string.Empty).Build())
.WithSeries(new SeriesBuilder("Test")
.WithPublicationStatus(PublicationStatus.OnGoing)
@ -2010,7 +2010,7 @@ public class SeriesServiceTests : AbstractDbTest
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var nextChapter = await _seriesService.GetEstimatedChapterCreationDate(1, 1);
Assert.NotNull(nextChapter);

View File

@ -31,24 +31,24 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
protected override async Task ResetDb()
{
_context.SiteTheme.RemoveRange(_context.SiteTheme);
await _context.SaveChangesAsync();
Context.SiteTheme.RemoveRange(Context.SiteTheme);
await Context.SaveChangesAsync();
// Recreate defaults
await Seed.SeedThemes(_context);
await Seed.SeedThemes(Context);
}
[Fact]
public async Task UpdateDefault_ShouldThrowOnInvalidId()
{
await ResetDb();
_testOutputHelper.WriteLine($"[UpdateDefault_ShouldThrowOnInvalidId] All Themes: {(await _unitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
_testOutputHelper.WriteLine($"[UpdateDefault_ShouldThrowOnInvalidId] All Themes: {(await UnitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
var filesystem = CreateFileSystem();
filesystem.AddFile($"{SiteThemeDirectory}custom.css", new MockFileData("123"));
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var siteThemeService = new ThemeService(ds, _unitOfWork, _messageHub, Substitute.For<IFileService>(),
var siteThemeService = new ThemeService(ds, UnitOfWork, _messageHub, Substitute.For<IFileService>(),
Substitute.For<ILogger<ThemeService>>(), Substitute.For<IMemoryCache>());
_context.SiteTheme.Add(new SiteTheme()
Context.SiteTheme.Add(new SiteTheme()
{
Name = "Custom",
NormalizedName = "Custom".ToNormalized(),
@ -56,7 +56,7 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
FileName = "custom.css",
IsDefault = false
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var ex = await Assert.ThrowsAsync<KavitaException>(() => siteThemeService.UpdateDefault(10));
Assert.Equal("Theme file missing or invalid", ex.Message);
@ -68,14 +68,14 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
public async Task GetContent_ShouldReturnContent()
{
await ResetDb();
_testOutputHelper.WriteLine($"[GetContent_ShouldReturnContent] All Themes: {(await _unitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
_testOutputHelper.WriteLine($"[GetContent_ShouldReturnContent] All Themes: {(await UnitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
var filesystem = CreateFileSystem();
filesystem.AddFile($"{SiteThemeDirectory}custom.css", new MockFileData("123"));
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var siteThemeService = new ThemeService(ds, _unitOfWork, _messageHub, Substitute.For<IFileService>(),
var siteThemeService = new ThemeService(ds, UnitOfWork, _messageHub, Substitute.For<IFileService>(),
Substitute.For<ILogger<ThemeService>>(), Substitute.For<IMemoryCache>());
_context.SiteTheme.Add(new SiteTheme()
Context.SiteTheme.Add(new SiteTheme()
{
Name = "Custom",
NormalizedName = "Custom".ToNormalized(),
@ -83,9 +83,9 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
FileName = "custom.css",
IsDefault = false
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var content = await siteThemeService.GetContent((await _unitOfWork.SiteThemeRepository.GetThemeDtoByName("Custom")).Id);
var content = await siteThemeService.GetContent((await UnitOfWork.SiteThemeRepository.GetThemeDtoByName("Custom")).Id);
Assert.NotNull(content);
Assert.NotEmpty(content);
Assert.Equal("123", content);
@ -95,14 +95,14 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
public async Task UpdateDefault_ShouldHaveOneDefault()
{
await ResetDb();
_testOutputHelper.WriteLine($"[UpdateDefault_ShouldHaveOneDefault] All Themes: {(await _unitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
_testOutputHelper.WriteLine($"[UpdateDefault_ShouldHaveOneDefault] All Themes: {(await UnitOfWork.SiteThemeRepository.GetThemes()).Count(t => t.IsDefault)}");
var filesystem = CreateFileSystem();
filesystem.AddFile($"{SiteThemeDirectory}custom.css", new MockFileData("123"));
var ds = new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), filesystem);
var siteThemeService = new ThemeService(ds, _unitOfWork, _messageHub, Substitute.For<IFileService>(),
var siteThemeService = new ThemeService(ds, UnitOfWork, _messageHub, Substitute.For<IFileService>(),
Substitute.For<ILogger<ThemeService>>(), Substitute.For<IMemoryCache>());
_context.SiteTheme.Add(new SiteTheme()
Context.SiteTheme.Add(new SiteTheme()
{
Name = "Custom",
NormalizedName = "Custom".ToNormalized(),
@ -110,16 +110,16 @@ public abstract class SiteThemeServiceTest : AbstractDbTest
FileName = "custom.css",
IsDefault = false
});
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var customTheme = (await _unitOfWork.SiteThemeRepository.GetThemeDtoByName("Custom"));
var customTheme = (await UnitOfWork.SiteThemeRepository.GetThemeDtoByName("Custom"));
Assert.NotNull(customTheme);
await siteThemeService.UpdateDefault(customTheme.Id);
Assert.Equal(customTheme.Id, (await _unitOfWork.SiteThemeRepository.GetDefaultTheme()).Id);
Assert.Equal(customTheme.Id, (await UnitOfWork.SiteThemeRepository.GetDefaultTheme()).Id);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 678 B

View File

@ -16,19 +16,15 @@ namespace API.Tests.Services;
public class VersionUpdaterServiceTests : IDisposable
{
private readonly ILogger<VersionUpdaterService> _logger;
private readonly IEventHub _eventHub;
private readonly IDirectoryService _directoryService;
private readonly ILogger<VersionUpdaterService> _logger = Substitute.For<ILogger<VersionUpdaterService>>();
private readonly IEventHub _eventHub = Substitute.For<IEventHub>();
private readonly IDirectoryService _directoryService = Substitute.For<IDirectoryService>();
private readonly VersionUpdaterService _service;
private readonly string _tempPath;
private readonly HttpTest _httpTest;
public VersionUpdaterServiceTests()
{
_logger = Substitute.For<ILogger<VersionUpdaterService>>();
_eventHub = Substitute.For<IEventHub>();
_directoryService = Substitute.For<IDirectoryService>();
// Create temp directory for cache
_tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(_tempPath);
@ -55,6 +51,7 @@ public class VersionUpdaterServiceTests : IDisposable
// Reset BuildInfo.Version
typeof(BuildInfo).GetProperty(nameof(BuildInfo.Version))?.SetValue(null, null);
GC.SuppressFinalize(this);
}
[Fact]
@ -302,7 +299,7 @@ public class VersionUpdaterServiceTests : IDisposable
var result = await _service.GetAllReleases();
Assert.Equal(1, result.Count);
Assert.Single(result);
Assert.Equal("0.7.0.0", result[0].UpdateVersion);
Assert.NotEmpty(_httpTest.CallLog); // HTTP call was made
}

View File

@ -26,9 +26,10 @@ public class WordCountAnalysisTests : AbstractDbTest
private const long MinHoursToRead = 1;
private const float AvgHoursToRead = 1.66954792f;
private const long MaxHoursToRead = 3;
public WordCountAnalysisTests() : base()
public WordCountAnalysisTests()
{
_readerService = new ReaderService(_unitOfWork, Substitute.For<ILogger<ReaderService>>(),
_readerService = new ReaderService(UnitOfWork, Substitute.For<ILogger<ReaderService>>(),
Substitute.For<IEventHub>(), Substitute.For<IImageService>(),
new DirectoryService(Substitute.For<ILogger<DirectoryService>>(), new MockFileSystem()),
Substitute.For<IScrobblingService>());
@ -36,9 +37,9 @@ public class WordCountAnalysisTests : AbstractDbTest
protected override async Task ResetDb()
{
_context.Series.RemoveRange(_context.Series.ToList());
Context.Series.RemoveRange(Context.Series.ToList());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
}
[Fact]
@ -56,7 +57,7 @@ public class WordCountAnalysisTests : AbstractDbTest
MangaFormat.Epub).Build())
.Build();
_context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test LIb", LibraryType.Book)
.WithSeries(series)
.Build());
@ -67,11 +68,11 @@ public class WordCountAnalysisTests : AbstractDbTest
.Build(),
};
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var cacheService = new CacheHelper(new FileService());
var service = new WordCountAnalyzerService(Substitute.For<ILogger<WordCountAnalyzerService>>(), _unitOfWork,
var service = new WordCountAnalyzerService(Substitute.For<ILogger<WordCountAnalyzerService>>(), UnitOfWork,
Substitute.For<IEventHub>(), cacheService, _readerService, Substitute.For<IMediaErrorService>());
@ -83,7 +84,7 @@ public class WordCountAnalysisTests : AbstractDbTest
Assert.Equal(MaxHoursToRead, series.MaxHoursToRead);
// Validate the Chapter gets updated correctly
var volume = series.Volumes.First();
var volume = series.Volumes[0];
Assert.Equal(WordCount, volume.WordCount);
Assert.Equal(MinHoursToRead, volume.MinHoursToRead);
Assert.Equal(AvgHoursToRead, volume.AvgHoursToRead);
@ -114,16 +115,16 @@ public class WordCountAnalysisTests : AbstractDbTest
.Build())
.Build();
_context.Library.Add(new LibraryBuilder("Test", LibraryType.Book)
Context.Library.Add(new LibraryBuilder("Test", LibraryType.Book)
.WithSeries(series)
.Build());
await _context.SaveChangesAsync();
await Context.SaveChangesAsync();
var cacheService = new CacheHelper(new FileService());
var service = new WordCountAnalyzerService(Substitute.For<ILogger<WordCountAnalyzerService>>(), _unitOfWork,
var service = new WordCountAnalyzerService(Substitute.For<ILogger<WordCountAnalyzerService>>(), UnitOfWork,
Substitute.For<IEventHub>(), cacheService, _readerService, Substitute.For<IMediaErrorService>());
await service.ScanSeries(1, 1);
@ -139,21 +140,21 @@ public class WordCountAnalysisTests : AbstractDbTest
.WithChapter(chapter2)
.Build());
series.Volumes.First().Chapters.Add(chapter2);
await _unitOfWork.CommitAsync();
series.Volumes[0].Chapters.Add(chapter2);
await UnitOfWork.CommitAsync();
await service.ScanSeries(1, 1);
Assert.Equal(WordCount * 2L, series.WordCount);
Assert.Equal(MinHoursToRead * 2, series.MinHoursToRead);
var firstVolume = series.Volumes.ElementAt(0);
var firstVolume = series.Volumes[0];
Assert.Equal(WordCount, firstVolume.WordCount);
Assert.Equal(MinHoursToRead, firstVolume.MinHoursToRead);
Assert.True(series.AvgHoursToRead.Is(AvgHoursToRead * 2));
Assert.Equal(MaxHoursToRead, firstVolume.MaxHoursToRead);
var secondVolume = series.Volumes.ElementAt(1);
var secondVolume = series.Volumes[1];
Assert.Equal(WordCount, secondVolume.WordCount);
Assert.Equal(MinHoursToRead, secondVolume.MinHoursToRead);
Assert.Equal(AvgHoursToRead, secondVolume.AvgHoursToRead);

View File

@ -68,7 +68,8 @@ public class ChapterController : BaseApiController
{
if (User.IsInRole(PolicyConstants.ReadOnlyRole)) return BadRequest(await _localizationService.Translate(User.GetUserId(), "permission-denied"));
var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId);
var chapter = await _unitOfWork.ChapterRepository.GetChapterAsync(chapterId,
ChapterIncludes.Files | ChapterIncludes.ExternalReviews | ChapterIncludes.ExternalRatings);
if (chapter == null)
return BadRequest(_localizationService.Translate(User.GetUserId(), "chapter-doesnt-exist"));
@ -86,6 +87,15 @@ public class ChapterController : BaseApiController
_unitOfWork.ChapterRepository.Remove(chapter);
}
// If we removed the volume, do an additional check if we need to delete the actual series as well or not
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(vol.SeriesId, SeriesIncludes.ExternalData | SeriesIncludes.Volumes);
var needToRemoveSeries = needToRemoveVolume && series != null && series.Volumes.Count <= 1;
if (needToRemoveSeries)
{
_unitOfWork.SeriesRepository.Remove(series!);
}
if (!await _unitOfWork.CommitAsync()) return Ok(false);
@ -95,6 +105,12 @@ public class ChapterController : BaseApiController
await _eventHub.SendMessageAsync(MessageFactory.VolumeRemoved, MessageFactory.VolumeRemovedEvent(chapter.VolumeId, vol.SeriesId), false);
}
if (needToRemoveSeries)
{
await _eventHub.SendMessageAsync(MessageFactory.SeriesRemoved,
MessageFactory.SeriesRemovedEvent(series!.Id, series.Name, series.LibraryId), false);
}
return Ok(true);
}
@ -419,7 +435,7 @@ public class ChapterController : BaseApiController
ret.HasBeenRated = ownRating.HasBeenRated;
}
var externalReviews = await _unitOfWork.ChapterRepository.GetExternalChapterReviews(chapterId);
var externalReviews = await _unitOfWork.ChapterRepository.GetExternalChapterReviewDtos(chapterId);
if (externalReviews.Count > 0)
{
userReviews.AddRange(ReviewHelper.SelectSpectrumOfReviews(externalReviews));
@ -427,7 +443,7 @@ public class ChapterController : BaseApiController
ret.Reviews = userReviews;
ret.Ratings = await _unitOfWork.ChapterRepository.GetExternalChapterRatings(chapterId);
ret.Ratings = await _unitOfWork.ChapterRepository.GetExternalChapterRatingDtos(chapterId);
return Ok(ret);
}

View File

@ -221,7 +221,7 @@ public class MetadataController(IUnitOfWork unitOfWork, ILocalizationService loc
return Ok(ret);
}
private async Task PrepareSeriesDetail(List<UserReviewDto> userReviews, SeriesDetailPlusDto ret)
private async Task PrepareSeriesDetail(List<UserReviewDto> userReviews, SeriesDetailPlusDto? ret)
{
var isAdmin = User.IsInRole(PolicyConstants.AdminRole);
var user = await unitOfWork.UserRepository.GetUserByIdAsync(User.GetUserId())!;
@ -235,12 +235,12 @@ public class MetadataController(IUnitOfWork unitOfWork, ILocalizationService loc
ret.Recommendations.OwnedSeries =
await unitOfWork.SeriesRepository.GetSeriesDtoByIdsAsync(
ret.Recommendations.OwnedSeries.Select(s => s.Id), user);
ret.Recommendations.ExternalSeries = new List<ExternalSeriesDto>();
ret.Recommendations.ExternalSeries = [];
}
if (ret.Recommendations != null && user != null)
{
ret.Recommendations.OwnedSeries ??= new List<SeriesDto>();
ret.Recommendations.OwnedSeries ??= [];
await unitOfWork.SeriesRepository.AddSeriesModifiers(user.Id, ret.Recommendations.OwnedSeries);
}
}

View File

@ -30,7 +30,7 @@ public class PluginController(IUnitOfWork unitOfWork, ITokenService tokenService
public async Task<ActionResult<UserDto>> Authenticate([Required] string apiKey, [Required] string pluginName)
{
// NOTE: In order to log information about plugins, we need some Plugin Description information for each request
// Should log into access table so we can tell the user
// Should log into the access table so we can tell the user
var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();
var userAgent = HttpContext.Request.Headers.UserAgent;
var userId = await unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);

View File

@ -71,6 +71,7 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
public DbSet<ExternalSeriesMetadata> ExternalSeriesMetadata { get; set; } = null!;
public DbSet<ExternalRecommendation> ExternalRecommendation { get; set; } = null!;
public DbSet<ManualMigrationHistory> ManualMigrationHistory { get; set; } = null!;
[Obsolete]
public DbSet<SeriesBlacklist> SeriesBlacklist { get; set; } = null!;
public DbSet<AppUserCollection> AppUserCollection { get; set; } = null!;
public DbSet<ChapterPeople> ChapterPeople { get; set; } = null!;

View File

@ -8,6 +8,7 @@ using API.DTOs.Reader;
using API.DTOs.SeriesDetail;
using API.Entities;
using API.Entities.Enums;
using API.Entities.Metadata;
using API.Extensions;
using API.Extensions.QueryExtensions;
using AutoMapper;
@ -27,6 +28,7 @@ public enum ChapterIncludes
Genres = 16,
Tags = 32,
ExternalReviews = 1 << 6,
ExternalRatings = 1 << 7
}
public interface IChapterRepository
@ -51,8 +53,10 @@ public interface IChapterRepository
IEnumerable<Chapter> GetChaptersForSeries(int seriesId);
Task<IList<Chapter>> GetAllChaptersForSeries(int seriesId);
Task<int> GetAverageUserRating(int chapterId, int userId);
Task<IList<UserReviewDto>> GetExternalChapterReviews(int chapterId);
Task<IList<RatingDto>> GetExternalChapterRatings(int chapterId);
Task<IList<UserReviewDto>> GetExternalChapterReviewDtos(int chapterId);
Task<IList<ExternalReview>> GetExternalChapterReview(int chapterId);
Task<IList<RatingDto>> GetExternalChapterRatingDtos(int chapterId);
Task<IList<ExternalRating>> GetExternalChapterRatings(int chapterId);
}
public class ChapterRepository : IChapterRepository
{
@ -332,7 +336,7 @@ public class ChapterRepository : IChapterRepository
return avg.HasValue ? (int) (avg.Value * 20) : 0;
}
public async Task<IList<UserReviewDto>> GetExternalChapterReviews(int chapterId)
public async Task<IList<UserReviewDto>> GetExternalChapterReviewDtos(int chapterId)
{
return await _context.Chapter
.Where(c => c.Id == chapterId)
@ -342,7 +346,15 @@ public class ChapterRepository : IChapterRepository
.ToListAsync();
}
public async Task<IList<RatingDto>> GetExternalChapterRatings(int chapterId)
public async Task<IList<ExternalReview>> GetExternalChapterReview(int chapterId)
{
return await _context.Chapter
.Where(c => c.Id == chapterId)
.SelectMany(c => c.ExternalReviews)
.ToListAsync();
}
public async Task<IList<RatingDto>> GetExternalChapterRatingDtos(int chapterId)
{
return await _context.Chapter
.Where(c => c.Id == chapterId)
@ -350,4 +362,12 @@ public class ChapterRepository : IChapterRepository
.ProjectTo<RatingDto>(_mapper.ConfigurationProvider)
.ToListAsync();
}
public async Task<IList<ExternalRating>> GetExternalChapterRatings(int chapterId)
{
return await _context.Chapter
.Where(c => c.Id == chapterId)
.SelectMany(c => c.ExternalRatings)
.ToListAsync();
}
}

View File

@ -57,6 +57,8 @@ public enum SeriesIncludes
ExternalRatings = 128,
ExternalRecommendations = 256,
ExternalMetadata = 512,
ExternalData = ExternalMetadata | ExternalReviews | ExternalRatings | ExternalRecommendations,
}
/// <summary>
@ -563,7 +565,13 @@ public class SeriesRepository : ISeriesRepository
if (!fullSeries) return await query.ToListAsync();
return await query.Include(s => s.Volumes)
return await query
.Include(s => s.Volumes)
.ThenInclude(v => v.Chapters)
.ThenInclude(c => c.ExternalRatings)
.Include(s => s.Volumes)
.ThenInclude(v => v.Chapters)
.ThenInclude(c => c.ExternalReviews)
.Include(s => s.Relations)
.Include(s => s.Metadata)

View File

@ -1,18 +1,62 @@
using System;
using System.Collections.Generic;
using System.IO;
using NetVips;
using System.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Image = NetVips.Image;
using Image = SixLabors.ImageSharp.Image;
namespace API.Extensions;
public static class ImageExtensions
{
public static int GetResolution(this Image image)
/// <summary>
/// Structure to hold various image quality metrics
/// </summary>
private sealed class ImageQualityMetrics
{
return image.Width * image.Height;
public int Width { get; set; }
public int Height { get; set; }
public bool IsColor { get; set; }
public double Colorfulness { get; set; }
public double Contrast { get; set; }
public double Sharpness { get; set; }
public double NoiseLevel { get; set; }
}
/// <summary>
/// Calculate a similarity score (0-1f) based on resolution difference and MSE.
/// </summary>
/// <param name="imagePath1">Path to first image</param>
/// <param name="imagePath2">Path to the second image</param>
/// <returns>Similarity score between 0-1, where 1 is identical</returns>
public static float CalculateSimilarity(this string imagePath1, string imagePath2)
{
if (!File.Exists(imagePath1) || !File.Exists(imagePath2))
{
throw new FileNotFoundException("One or both image files do not exist");
}
// Load both images as Rgba32 (consistent with the rest of the code)
using var img1 = Image.Load<Rgba32>(imagePath1);
using var img2 = Image.Load<Rgba32>(imagePath2);
// Calculate resolution difference factor
var res1 = img1.Width * img1.Height;
var res2 = img2.Width * img2.Height;
var resolutionDiff = Math.Abs(res1 - res2) / (float) Math.Max(res1, res2);
// Calculate mean squared error for pixel differences
var mse = img1.GetMeanSquaredError(img2);
// Normalize MSE (65025 = 255², which is the max possible squared difference per channel)
var normalizedMse = 1f - Math.Min(1f, mse / 65025f);
// Final similarity score (weighted average of resolution difference and color difference)
return Math.Max(0f, 1f - (resolutionDiff * 0.5f) - (1f - normalizedMse) * 0.5f);
}
/// <summary>
@ -43,80 +87,351 @@ public static class ImageExtensions
}
}
return (float)(totalDiff / (img1.Width * img1.Height));
}
public static float GetSimilarity(this string imagePath1, string imagePath2)
{
if (!File.Exists(imagePath1) || !File.Exists(imagePath2))
{
throw new FileNotFoundException("One or both image files do not exist");
}
// Calculate similarity score
return CalculateSimilarity(imagePath1, imagePath2);
return (float) (totalDiff / (img1.Width * img1.Height));
}
/// <summary>
/// Determines which image is "better" based on similarity and resolution.
/// Determines which image is "better" based on multiple quality factors
/// using only the cross-platform ImageSharp library
/// </summary>
/// <param name="imagePath1">Path to first image</param>
/// <param name="imagePath2">Path to second image</param>
/// <param name="similarityThreshold">Minimum similarity to consider images similar</param>
/// <param name="imagePath2">Path to the second image</param>
/// <param name="preferColor">Whether to prefer color images over grayscale (default: true)</param>
/// <returns>The path of the better image</returns>
public static string GetBetterImage(this string imagePath1, string imagePath2, float similarityThreshold = 0.7f)
public static string GetBetterImage(this string imagePath1, string imagePath2, bool preferColor = true)
{
if (!File.Exists(imagePath1) || !File.Exists(imagePath2))
{
throw new FileNotFoundException("One or both image files do not exist");
}
// Calculate similarity score
var similarity = CalculateSimilarity(imagePath1, imagePath2);
// Quick metadata check to get width/height without loading full pixel data
var info1 = Image.Identify(imagePath1);
var info2 = Image.Identify(imagePath2);
using var img1 = Image.NewFromFile(imagePath1, access: Enums.Access.Sequential);
using var img2 = Image.NewFromFile(imagePath2, access: Enums.Access.Sequential);
// Calculate resolution factor
double resolutionFactor1 = info1.Width * info1.Height;
double resolutionFactor2 = info2.Width * info2.Height;
var resolution1 = img1.Width * img1.Height;
var resolution2 = img2.Width * img2.Height;
// If one image is significantly higher resolution (3x or more), just pick it
// This avoids fully loading both images when the choice is obvious
if (resolutionFactor1 > resolutionFactor2 * 3)
return imagePath1;
if (resolutionFactor2 > resolutionFactor1 * 3)
return imagePath2;
// If images are similar, choose the one with higher resolution
if (similarity >= similarityThreshold)
// Otherwise, we need to analyze the actual image data for both
// NOTE: We HAVE to use these scope blocks and load image here otherwise memory-mapped section exception will occur
ImageQualityMetrics metrics1;
using (var img1 = Image.Load<Rgba32>(imagePath1))
{
return resolution1 >= resolution2 ? imagePath1 : imagePath2;
metrics1 = GetImageQualityMetrics(img1);
}
// If images are not similar, allow the new image
return imagePath2;
ImageQualityMetrics metrics2;
using (var img2 = Image.Load<Rgba32>(imagePath2))
{
metrics2 = GetImageQualityMetrics(img2);
}
// If one is color, and one is grayscale, then we prefer color
if (preferColor && metrics1.IsColor != metrics2.IsColor)
{
return metrics1.IsColor ? imagePath1 : imagePath2;
}
// Calculate overall quality scores
var score1 = CalculateOverallScore(metrics1);
var score2 = CalculateOverallScore(metrics2);
return score1 >= score2 ? imagePath1 : imagePath2;
}
/// <summary>
/// Calculate a weighted overall score based on metrics
/// </summary>
private static double CalculateOverallScore(ImageQualityMetrics metrics)
{
// Resolution factor (normalized to HD resolution)
var resolutionFactor = Math.Min(1.0, (metrics.Width * metrics.Height) / (double) (1920 * 1080));
// Color factor
var colorFactor = metrics.IsColor ? (0.5 + 0.5 * metrics.Colorfulness) : 0.3;
// Quality factors
var contrastFactor = Math.Min(1.0, metrics.Contrast);
var sharpnessFactor = Math.Min(1.0, metrics.Sharpness);
// Noise penalty (less noise is better)
var noisePenalty = Math.Max(0, 1.0 - metrics.NoiseLevel);
// Weighted combination
return (resolutionFactor * 0.35) +
(colorFactor * 0.3) +
(contrastFactor * 0.15) +
(sharpnessFactor * 0.15) +
(noisePenalty * 0.05);
}
/// <summary>
/// Calculate a similarity score (0-1f) based on resolution difference and MSE.
/// Gets quality metrics for an image
/// </summary>
/// <param name="imagePath1"></param>
/// <param name="imagePath2"></param>
/// <returns></returns>
private static float CalculateSimilarity(string imagePath1, string imagePath2)
private static ImageQualityMetrics GetImageQualityMetrics(Image<Rgba32> image)
{
if (!File.Exists(imagePath1) || !File.Exists(imagePath2))
// Create a smaller version if the image is large to speed up analysis
Image<Rgba32> workingImage;
if (image.Width > 512 || image.Height > 512)
{
return -1;
workingImage = image.Clone(ctx => ctx.Resize(
new ResizeOptions {
Size = new Size(512),
Mode = ResizeMode.Max
}));
}
else
{
workingImage = image.Clone();
}
using var img1 = Image.NewFromFile(imagePath1, access: Enums.Access.Sequential);
using var img2 = Image.NewFromFile(imagePath2, access: Enums.Access.Sequential);
var metrics = new ImageQualityMetrics
{
Width = image.Width,
Height = image.Height
};
var res1 = img1.Width * img1.Height;
var res2 = img2.Width * img2.Height;
var resolutionDiff = Math.Abs(res1 - res2) / (float)Math.Max(res1, res2);
// Color analysis (is the image color or grayscale?)
var colorInfo = AnalyzeColorfulness(workingImage);
metrics.IsColor = colorInfo.IsColor;
metrics.Colorfulness = colorInfo.Colorfulness;
using var imgSharp1 = SixLabors.ImageSharp.Image.Load<Rgba32>(imagePath1);
using var imgSharp2 = SixLabors.ImageSharp.Image.Load<Rgba32>(imagePath2);
// Contrast analysis
metrics.Contrast = CalculateContrast(workingImage);
var mse = imgSharp1.GetMeanSquaredError(imgSharp2);
var normalizedMse = 1f - Math.Min(1f, mse / 65025f); // Normalize based on max color diff
// Sharpness estimation
metrics.Sharpness = EstimateSharpness(workingImage);
// Final similarity score (weighted)
return Math.Max(0f, 1f - (resolutionDiff * 0.5f) - (1f - normalizedMse) * 0.5f);
// Noise estimation
metrics.NoiseLevel = EstimateNoiseLevel(workingImage);
// Clean up
workingImage.Dispose();
return metrics;
}
/// <summary>
/// Analyzes colorfulness of an image
/// </summary>
private static (bool IsColor, double Colorfulness) AnalyzeColorfulness(Image<Rgba32> image)
{
// For performance, sample a subset of pixels
var sampleSize = Math.Min(1000, image.Width * image.Height);
var stepSize = Math.Max(1, (image.Width * image.Height) / sampleSize);
var colorCount = 0;
List<(int R, int G, int B)> samples = [];
// Sample pixels
for (var i = 0; i < image.Width * image.Height; i += stepSize)
{
var x = i % image.Width;
var y = i / image.Width;
var pixel = image[x, y];
// Check if RGB channels differ by a threshold
// High difference indicates color, low difference indicates grayscale
var rMinusG = Math.Abs(pixel.R - pixel.G);
var rMinusB = Math.Abs(pixel.R - pixel.B);
var gMinusB = Math.Abs(pixel.G - pixel.B);
if (rMinusG > 15 || rMinusB > 15 || gMinusB > 15)
{
colorCount++;
}
samples.Add((pixel.R, pixel.G, pixel.B));
}
// Calculate colorfulness metric based on Hasler and Süsstrunk's approach
// This measures the spread and intensity of colors
if (samples.Count <= 0) return (false, 0);
// Calculate rg and yb opponent channels
var rg = samples.Select(p => p.R - p.G).ToList();
var yb = samples.Select(p => 0.5 * (p.R + p.G) - p.B).ToList();
// Calculate standard deviation and mean of opponent channels
var rgStdDev = CalculateStdDev(rg);
var ybStdDev = CalculateStdDev(yb);
var rgMean = rg.Average();
var ybMean = yb.Average();
// Combine into colorfulness metric
var stdRoot = Math.Sqrt(rgStdDev * rgStdDev + ybStdDev * ybStdDev);
var meanRoot = Math.Sqrt(rgMean * rgMean + ybMean * ybMean);
var colorfulness = stdRoot + 0.3 * meanRoot;
// Normalize to 0-1 range (typical colorfulness is 0-100)
colorfulness = Math.Min(1.0, colorfulness / 100.0);
var isColor = (double)colorCount / samples.Count > 0.05;
return (isColor, colorfulness);
}
/// <summary>
/// Calculate standard deviation of a list of values
/// </summary>
private static double CalculateStdDev(List<int> values)
{
var mean = values.Average();
var sumOfSquaresOfDifferences = values.Select(val => (val - mean) * (val - mean)).Sum();
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
}
/// <summary>
/// Calculate standard deviation of a list of values
/// </summary>
private static double CalculateStdDev(List<double> values)
{
var mean = values.Average();
var sumOfSquaresOfDifferences = values.Select(val => (val - mean) * (val - mean)).Sum();
return Math.Sqrt(sumOfSquaresOfDifferences / values.Count);
}
/// <summary>
/// Calculates contrast of an image
/// </summary>
private static double CalculateContrast(Image<Rgba32> image)
{
// For performance, sample a subset of pixels
var sampleSize = Math.Min(1000, image.Width * image.Height);
var stepSize = Math.Max(1, (image.Width * image.Height) / sampleSize);
List<int> luminanceValues = new();
// Sample pixels and calculate luminance
for (var i = 0; i < image.Width * image.Height; i += stepSize)
{
var x = i % image.Width;
var y = i / image.Width;
var pixel = image[x, y];
// Calculate luminance
var luminance = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);
luminanceValues.Add(luminance);
}
if (luminanceValues.Count < 2)
return 0;
// Use RMS contrast (root-mean-square of pixel intensity)
var mean = luminanceValues.Average();
var sumOfSquaresOfDifferences = luminanceValues.Sum(l => Math.Pow(l - mean, 2));
var rmsContrast = Math.Sqrt(sumOfSquaresOfDifferences / luminanceValues.Count) / mean;
// Normalize to 0-1 range
return Math.Min(1.0, rmsContrast);
}
/// <summary>
/// Estimates sharpness using simple Laplacian-based method
/// </summary>
private static double EstimateSharpness(Image<Rgba32> image)
{
// For simplicity, convert to grayscale
var grayImage = new int[image.Width, image.Height];
// Convert to grayscale
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var pixel = image[x, y];
grayImage[x, y] = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);
}
}
// Apply Laplacian filter (3x3)
// The Laplacian measures local variations - higher values indicate edges/details
double laplacianSum = 0;
var validPixels = 0;
// Laplacian kernel: [0, 1, 0, 1, -4, 1, 0, 1, 0]
for (var y = 1; y < image.Height - 1; y++)
{
for (var x = 1; x < image.Width - 1; x++)
{
var laplacian =
grayImage[x, y - 1] +
grayImage[x - 1, y] - 4 * grayImage[x, y] + grayImage[x + 1, y] +
grayImage[x, y + 1];
laplacianSum += Math.Abs(laplacian);
validPixels++;
}
}
if (validPixels == 0)
return 0;
// Calculate variance of Laplacian
var laplacianVariance = laplacianSum / validPixels;
// Normalize to 0-1 range (typical values range from 0-1000)
return Math.Min(1.0, laplacianVariance / 1000.0);
}
/// <summary>
/// Estimates noise level using simple block-based variance method
/// </summary>
private static double EstimateNoiseLevel(Image<Rgba32> image)
{
// Block size for noise estimation
const int blockSize = 8;
List<double> blockVariances = new();
// Calculate variance in small blocks throughout the image
for (var y = 0; y < image.Height - blockSize; y += blockSize)
{
for (var x = 0; x < image.Width - blockSize; x += blockSize)
{
List<int> blockValues = new();
// Sample block
for (var by = 0; by < blockSize; by++)
{
for (var bx = 0; bx < blockSize; bx++)
{
var pixel = image[x + bx, y + by];
var value = (int)(0.299 * pixel.R + 0.587 * pixel.G + 0.114 * pixel.B);
blockValues.Add(value);
}
}
// Calculate variance of this block
var blockMean = blockValues.Average();
var blockVariance = blockValues.Sum(v => Math.Pow(v - blockMean, 2)) / blockValues.Count;
blockVariances.Add(blockVariance);
}
}
if (blockVariances.Count == 0)
return 0;
// Sort block variances and take lowest 10% (likely uniform areas where noise is most visible)
blockVariances.Sort();
var smoothBlocksCount = Math.Max(1, blockVariances.Count / 10);
var averageNoiseVariance = blockVariances.Take(smoothBlocksCount).Average();
// Normalize to 0-1 range (typical noise variances are 0-100)
return Math.Min(1.0, averageNoiseVariance / 100.0);
}
}

View File

@ -79,6 +79,12 @@ public static class IncludesExtensions
.Include(c => c.ExternalReviews);
}
if (includes.HasFlag(ChapterIncludes.ExternalRatings))
{
queryable = queryable
.Include(c => c.ExternalRatings);
}
return queryable.AsSplitQuery();
}

View File

@ -20,9 +20,11 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NetVips;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.AspNetCore.SignalR.Extensions;
using Log = Serilog.Log;
namespace API;
#nullable enable
@ -143,6 +145,8 @@ public class Program
var settings = await unitOfWork.SettingsRepository.GetSettingsDtoAsync();
LogLevelOptions.SwitchLogLevel(settings.LoggingLevel);
InitNetVips();
await host.RunAsync();
} catch (Exception ex)
{
@ -225,4 +229,14 @@ public class Program
webBuilder.UseStartup<Startup>();
});
/// <summary>
/// Ensure NetVips does not cache
/// </summary>
/// <remarks>https://github.com/kleisauke/net-vips/issues/6#issuecomment-394379299</remarks>
private static void InitNetVips()
{
Cache.MaxFiles = 0;
}
}

View File

@ -69,6 +69,7 @@ public interface IDirectoryService
IEnumerable<string> GetFiles(string path, string fileNameRegex = "", SearchOption searchOption = SearchOption.TopDirectoryOnly);
bool ExistOrCreate(string directoryPath);
void DeleteFiles(IEnumerable<string> files);
void CopyFile(string sourcePath, string destinationPath, bool overwrite = true);
void RemoveNonImages(string directoryName);
void Flatten(string directoryName);
Task<bool> CheckWriteAccess(string directoryName);
@ -937,6 +938,27 @@ public class DirectoryService : IDirectoryService
}
}
public void CopyFile(string sourcePath, string destinationPath, bool overwrite = true)
{
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException("Source file not found", sourcePath);
}
var destinationDirectory = Path.GetDirectoryName(destinationPath);
if (string.IsNullOrEmpty(destinationDirectory))
{
throw new ArgumentException("Destination path does not contain a directory", nameof(destinationPath));
}
if (!Directory.Exists(destinationDirectory))
{
FileSystem.Directory.CreateDirectory(destinationDirectory);
}
FileSystem.File.Copy(sourcePath, destinationPath, overwrite);
}
/// <summary>
/// Returns the human-readable file size for an arbitrary, 64-bit file size
/// <remarks>The default format is "0.## XB", e.g. "4.2 KB" or "1.43 GB"</remarks>
@ -1090,4 +1112,23 @@ public class DirectoryService : IDirectoryService
FlattenDirectory(root, subDirectory, ref directoryIndex);
}
}
/// <summary>
/// If the file is locked or not existing
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool IsFileLocked(string filePath)
{
try
{
if (!File.Exists(filePath)) return false;
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
return false; // If this works, the file is not locked
}
catch (IOException)
{
return true; // File is locked by another process
}
}
}

View File

@ -1085,7 +1085,7 @@ public class ExternalMetadataService : IExternalMetadataService
madeModification = await UpdateChapterPeople(chapter, settings, PersonRole.Writer, potentialMatch.Writers) || madeModification;
madeModification = await UpdateChapterCoverImage(chapter, settings, potentialMatch.CoverImageUrl) || madeModification;
madeModification = UpdateExternalChapterMetadata(chapter, settings, potentialMatch) || madeModification;
madeModification = await UpdateExternalChapterMetadata(chapter, settings, potentialMatch) || madeModification;
_unitOfWork.ChapterRepository.Update(chapter);
await _unitOfWork.CommitAsync();
@ -1094,7 +1094,7 @@ public class ExternalMetadataService : IExternalMetadataService
return madeModification;
}
private bool UpdateExternalChapterMetadata(Chapter chapter, MetadataSettingsDto settings, ExternalChapterDto metadata)
private async Task<bool> UpdateExternalChapterMetadata(Chapter chapter, MetadataSettingsDto settings, ExternalChapterDto metadata)
{
if (!settings.Enabled) return false;
@ -1106,7 +1106,12 @@ public class ExternalMetadataService : IExternalMetadataService
var madeModification = false;
#region Review
_unitOfWork.ExternalSeriesMetadataRepository.Remove(chapter.ExternalReviews);
// Remove existing Reviews
var existingReviews = await _unitOfWork.ChapterRepository.GetExternalChapterReview(chapter.Id);
_unitOfWork.ExternalSeriesMetadataRepository.Remove(existingReviews);
List<ExternalReview> externalReviews = [];
externalReviews.AddRange(metadata.CriticReviews
.Where(r => !string.IsNullOrWhiteSpace(r.Username) && !string.IsNullOrWhiteSpace(r.Body))
@ -1139,7 +1144,9 @@ public class ExternalMetadataService : IExternalMetadataService
var averageCriticRating = metadata.CriticReviews.Average(r => r.Rating);
var averageUserRating = metadata.UserReviews.Average(r => r.Rating);
_unitOfWork.ExternalSeriesMetadataRepository.Remove(chapter.ExternalRatings);
var existingRatings = await _unitOfWork.ChapterRepository.GetExternalChapterRatings(chapter.Id);
_unitOfWork.ExternalSeriesMetadataRepository.Remove(existingRatings);
chapter.ExternalRatings =
[
new ExternalRating

View File

@ -450,7 +450,7 @@ public class SeriesService : ISeriesService
try
{
var chapterMappings =
await _unitOfWork.SeriesRepository.GetChapterIdWithSeriesIdForSeriesAsync(seriesIds.ToArray());
await _unitOfWork.SeriesRepository.GetChapterIdWithSeriesIdForSeriesAsync([.. seriesIds]);
var allChapterIds = new List<int>();
foreach (var mapping in chapterMappings)
@ -458,9 +458,8 @@ public class SeriesService : ISeriesService
allChapterIds.AddRange(mapping.Value);
}
// NOTE: This isn't getting all the people and whatnot currently
// NOTE: This isn't getting all the people and whatnot currently due to the lack of includes
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdsAsync(seriesIds);
_unitOfWork.SeriesRepository.Remove(series);
var libraryIds = series.Select(s => s.LibraryId);
@ -481,7 +480,8 @@ public class SeriesService : ISeriesService
await _unitOfWork.AppUserProgressRepository.CleanupAbandonedChapters();
await _unitOfWork.CollectionTagRepository.RemoveCollectionsWithoutSeries();
_taskScheduler.CleanupChapters(allChapterIds.ToArray());
_taskScheduler.CleanupChapters([.. allChapterIds]);
return true;
}
catch (Exception ex)

View File

@ -81,6 +81,22 @@ public class CoverDbService : ICoverDbService
_eventHub = eventHub;
}
/// <summary>
/// Downloads the favicon image from a given website URL, optionally falling back to a custom method if standard methods fail.
/// </summary>
/// <param name="url">The full URL of the website to extract the favicon from.</param>
/// <param name="encodeFormat">The desired image encoding format for saving the favicon (e.g., WebP, PNG).</param>
/// <returns>
/// A string representing the filename of the downloaded favicon image, saved to the configured favicon directory.
/// </returns>
/// <exception cref="KavitaException">
/// Thrown when favicon retrieval fails or if a previously failed domain is detected in cache.
/// </exception>
/// <remarks>
/// This method first checks for a cached failure to avoid re-requesting bad links.
/// It then attempts to parse HTML for `link` tags pointing to `.png` favicons and
/// falls back to an internal fallback method if needed. Valid results are saved to disk.
/// </remarks>
public async Task<string> DownloadFaviconAsync(string url, EncodeFormat encodeFormat)
{
// Parse the URL to get the domain (including subdomain)
@ -157,23 +173,10 @@ public class CoverDbService : ICoverDbService
// Create the destination file path
using var image = Image.PngloadStream(faviconStream);
var filename = ImageService.GetWebLinkFormat(baseUrl, encodeFormat);
switch (encodeFormat)
{
case EncodeFormat.PNG:
image.Pngsave(Path.Combine(_directoryService.FaviconDirectory, filename));
break;
case EncodeFormat.WEBP:
image.Webpsave(Path.Combine(_directoryService.FaviconDirectory, filename));
break;
case EncodeFormat.AVIF:
image.Heifsave(Path.Combine(_directoryService.FaviconDirectory, filename));
break;
default:
throw new ArgumentOutOfRangeException(nameof(encodeFormat), encodeFormat, null);
}
image.WriteToFile(Path.Combine(_directoryService.FaviconDirectory, filename));
_logger.LogDebug("Favicon for {Domain} downloaded and saved successfully", domain);
return filename;
} catch (Exception ex)
{
@ -212,23 +215,10 @@ public class CoverDbService : ICoverDbService
// Create the destination file path
using var image = Image.NewFromStream(publisherStream);
var filename = ImageService.GetPublisherFormat(publisherName, encodeFormat);
switch (encodeFormat)
{
case EncodeFormat.PNG:
image.Pngsave(Path.Combine(_directoryService.PublisherDirectory, filename));
break;
case EncodeFormat.WEBP:
image.Webpsave(Path.Combine(_directoryService.PublisherDirectory, filename));
break;
case EncodeFormat.AVIF:
image.Heifsave(Path.Combine(_directoryService.PublisherDirectory, filename));
break;
default:
throw new ArgumentOutOfRangeException(nameof(encodeFormat), encodeFormat, null);
}
image.WriteToFile(Path.Combine(_directoryService.PublisherDirectory, filename));
_logger.LogDebug("Publisher image for {PublisherName} downloaded and saved successfully", publisherName.Sanitize());
return filename;
} catch (Exception ex)
{
@ -294,40 +284,30 @@ public class CoverDbService : ICoverDbService
return null;
}
private async Task<string> DownloadImageFromUrl(string filenameWithoutExtension, EncodeFormat encodeFormat, string url)
private async Task<string> DownloadImageFromUrl(string filenameWithoutExtension, EncodeFormat encodeFormat, string url, string? targetDirectory = null)
{
// TODO: I need to unit test this to ensure it works when overwriting, etc
// Target Directory defaults to CoverImageDirectory, but can be temp for when comparison between images is used
targetDirectory ??= _directoryService.CoverImageDirectory;
// Create the destination file path
var filename = filenameWithoutExtension + encodeFormat.GetExtension();
var targetFile = Path.Combine(_directoryService.CoverImageDirectory, filename);
// Ensure if file exists, we delete to overwrite
var targetFile = Path.Combine(targetDirectory, filename);
_logger.LogTrace("Fetching person image from {Url}", url.Sanitize());
// Download the file using Flurl
var personStream = await url
var imageStream = await url
.AllowHttpStatus("2xx,304")
.GetStreamAsync();
using var image = Image.NewFromStream(personStream);
switch (encodeFormat)
{
case EncodeFormat.PNG:
image.Pngsave(targetFile);
break;
case EncodeFormat.WEBP:
image.Webpsave(targetFile);
break;
case EncodeFormat.AVIF:
image.Heifsave(targetFile);
break;
default:
throw new ArgumentOutOfRangeException(nameof(encodeFormat), encodeFormat, null);
}
using var image = Image.NewFromStream(imageStream);
image.WriteToFile(targetFile);
return filename;
}
private async Task<string> GetCoverPersonImagePath(Person person)
private async Task<string?> GetCoverPersonImagePath(Person person)
{
var tempFile = Path.Join(_directoryService.LongTermCacheDirectory, "people.yml");
@ -384,25 +364,22 @@ public class CoverDbService : ICoverDbService
await CacheDataAsync(urlsFileName, allOverrides);
if (!string.IsNullOrEmpty(allOverrides))
if (string.IsNullOrEmpty(allOverrides)) return correctSizeLink;
var cleanedBaseUrl = baseUrl.Replace("https://", string.Empty);
var externalFile = allOverrides
.Split("\n")
.FirstOrDefault(url =>
cleanedBaseUrl.Equals(url.Replace(".png", string.Empty)) ||
cleanedBaseUrl.Replace("www.", string.Empty).Equals(url.Replace(".png", string.Empty)
));
if (string.IsNullOrEmpty(externalFile))
{
var cleanedBaseUrl = baseUrl.Replace("https://", string.Empty);
var externalFile = allOverrides
.Split("\n")
.FirstOrDefault(url =>
cleanedBaseUrl.Equals(url.Replace(".png", string.Empty)) ||
cleanedBaseUrl.Replace("www.", string.Empty).Equals(url.Replace(".png", string.Empty)
));
if (string.IsNullOrEmpty(externalFile))
{
throw new KavitaException($"Could not grab favicon from {baseUrl.Sanitize()}");
}
correctSizeLink = $"{NewHost}favicons/" + externalFile;
throw new KavitaException($"Could not grab favicon from {baseUrl.Sanitize()}");
}
return correctSizeLink;
return $"{NewHost}favicons/{externalFile}";
}
private async Task<string> FallbackToKavitaReaderPublisher(string publisherName)
@ -415,34 +392,30 @@ public class CoverDbService : ICoverDbService
// Cache immediately
await CacheDataAsync(publisherFileName, allOverrides);
if (string.IsNullOrEmpty(allOverrides)) return externalLink;
if (!string.IsNullOrEmpty(allOverrides))
{
var externalFile = allOverrides
.Split("\n")
.Select(publisherLine =>
{
var tokens = publisherLine.Split("|");
if (tokens.Length != 2) return null;
var aliases = tokens[0];
// Multiple publisher aliases are separated by #
if (aliases.Split("#").Any(name => name.ToLowerInvariant().Trim().Equals(publisherName.ToLowerInvariant().Trim())))
{
return tokens[1];
}
return null;
})
.FirstOrDefault(url => !string.IsNullOrEmpty(url));
if (string.IsNullOrEmpty(externalFile))
var externalFile = allOverrides
.Split("\n")
.Select(publisherLine =>
{
throw new KavitaException($"Could not grab publisher image for {publisherName}");
}
var tokens = publisherLine.Split("|");
if (tokens.Length != 2) return null;
var aliases = tokens[0];
// Multiple publisher aliases are separated by #
if (aliases.Split("#").Any(name => name.ToLowerInvariant().Trim().Equals(publisherName.ToLowerInvariant().Trim())))
{
return tokens[1];
}
return null;
})
.FirstOrDefault(url => !string.IsNullOrEmpty(url));
externalLink = $"{NewHost}publishers/" + externalFile;
if (string.IsNullOrEmpty(externalFile))
{
throw new KavitaException($"Could not grab publisher image for {publisherName}");
}
return externalLink;
return $"{NewHost}publishers/{externalLink}";
}
private async Task CacheDataAsync(string fileName, string? content)
@ -485,33 +458,67 @@ public class CoverDbService : ICoverDbService
/// <param name="checkNoImagePlaceholder">Will check against all known null image placeholders to avoid writing it</param>
public async Task SetPersonCoverByUrl(Person person, string url, bool fromBase64 = true, bool checkNoImagePlaceholder = false)
{
// TODO: Refactor checkNoImagePlaceholder bool to an action that evaluates how to process Image
if (!string.IsNullOrEmpty(url))
{
var filePath = await CreateThumbnail(url, $"{ImageService.GetPersonFormat(person.Id)}", fromBase64);
var tempDir = _directoryService.TempDirectory;
var format = ImageService.GetPersonFormat(person.Id);
var finalFileName = format + ".webp";
var tempFileName = format + "_new";
var tempFilePath = await CreateThumbnail(url, tempFileName, fromBase64, tempDir);
// Additional check to see if downloaded image is similar and we have a higher resolution
if (checkNoImagePlaceholder)
if (!string.IsNullOrEmpty(tempFilePath))
{
var matchRating = Path.Join(_directoryService.AssetsDirectory, "anilist-no-image-placeholder.jpg").GetSimilarity(Path.Join(_directoryService.CoverImageDirectory, filePath))!;
var tempFullPath = Path.Combine(tempDir, tempFilePath);
var finalFullPath = Path.Combine(_directoryService.CoverImageDirectory, finalFileName);
if (matchRating >= 0.9f)
// Skip setting image if it's similar to a known placeholder
if (checkNoImagePlaceholder)
{
if (string.IsNullOrEmpty(person.CoverImage))
var placeholderPath = Path.Combine(_directoryService.AssetsDirectory, "anilist-no-image-placeholder.jpg");
var similarity = placeholderPath.CalculateSimilarity(tempFullPath);
if (similarity >= 0.9f)
{
filePath = null;
_logger.LogInformation("Skipped setting placeholder image for person {PersonId} due to high similarity ({Similarity})", person.Id, similarity);
_directoryService.DeleteFiles([tempFullPath]);
return;
}
}
try
{
if (!string.IsNullOrEmpty(person.CoverImage))
{
var existingPath = Path.Combine(_directoryService.CoverImageDirectory, person.CoverImage);
var betterImage = existingPath.GetBetterImage(tempFullPath)!;
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
if (choseNewImage)
{
_directoryService.DeleteFiles([existingPath]);
_directoryService.CopyFile(tempFullPath, finalFullPath);
person.CoverImage = finalFileName;
}
else
{
_directoryService.DeleteFiles([tempFullPath]);
person.CoverImage = Path.GetFileName(existingPath);
}
}
else
{
filePath = Path.GetFileName(Path.Join(_directoryService.CoverImageDirectory, person.CoverImage));
_directoryService.CopyFile(tempFullPath, finalFullPath);
person.CoverImage = finalFileName;
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error choosing better image for Person: {PersonId}", person.Id);
_directoryService.CopyFile(tempFullPath, finalFullPath);
person.CoverImage = finalFileName;
}
_directoryService.DeleteFiles([tempFullPath]);
if (!string.IsNullOrEmpty(filePath))
{
person.CoverImage = filePath;
person.CoverImageLocked = true;
_imageService.UpdateColorScape(person);
_unitOfWork.PersonRepository.Update(person);
@ -544,31 +551,52 @@ public class CoverDbService : ICoverDbService
{
if (!string.IsNullOrEmpty(url))
{
var filePath = await CreateThumbnail(url, $"{ImageService.GetSeriesFormat(series.Id)}", fromBase64);
var tempDir = _directoryService.TempDirectory;
var format = ImageService.GetSeriesFormat(series.Id);
var finalFileName = format + ".webp";
var tempFileName = format + "_new";
var tempFilePath = await CreateThumbnail(url, tempFileName, fromBase64, tempDir);
if (!string.IsNullOrEmpty(filePath))
if (!string.IsNullOrEmpty(tempFilePath))
{
// Additional check to see if downloaded image is similar and we have a higher resolution
var tempFullPath = Path.Combine(tempDir, tempFilePath);
var finalFullPath = Path.Combine(_directoryService.CoverImageDirectory, finalFileName);
if (chooseBetterImage && !string.IsNullOrEmpty(series.CoverImage))
{
try
{
var betterImage = Path.Join(_directoryService.CoverImageDirectory, series.CoverImage)
.GetBetterImage(Path.Join(_directoryService.CoverImageDirectory, filePath))!;
filePath = Path.GetFileName(betterImage);
var existingPath = Path.Combine(_directoryService.CoverImageDirectory, series.CoverImage);
var betterImage = existingPath.GetBetterImage(tempFullPath)!;
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
if (choseNewImage)
{
_directoryService.DeleteFiles([existingPath]);
_directoryService.CopyFile(tempFullPath, finalFullPath);
series.CoverImage = finalFileName;
}
else
{
_directoryService.DeleteFiles([tempFullPath]);
series.CoverImage = Path.GetFileName(existingPath);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "There was an issue trying to choose a better cover image for Series: {SeriesName} ({SeriesId})", series.Name, series.Id);
_logger.LogError(ex, "Error choosing better image for Series: {SeriesId}", series.Id);
_directoryService.CopyFile(tempFullPath, finalFullPath);
series.CoverImage = finalFileName;
}
}
series.CoverImage = filePath;
series.CoverImageLocked = true;
if (series.CoverImage == null)
else
{
_logger.LogDebug("[SeriesCoverImageBug] Setting Series Cover Image to null");
_directoryService.CopyFile(tempFullPath, finalFullPath);
series.CoverImage = finalFileName;
}
_directoryService.DeleteFiles([tempFullPath]);
series.CoverImageLocked = true;
_imageService.UpdateColorScape(series);
_unitOfWork.SeriesRepository.Update(series);
}
@ -577,10 +605,7 @@ public class CoverDbService : ICoverDbService
{
series.CoverImage = null;
series.CoverImageLocked = false;
if (series.CoverImage == null)
{
_logger.LogDebug("[SeriesCoverImageBug] Setting Series Cover Image to null");
}
_logger.LogDebug("[SeriesCoverImageBug] Setting Series Cover Image to null");
_imageService.UpdateColorScape(series);
_unitOfWork.SeriesRepository.Update(series);
}
@ -597,26 +622,52 @@ public class CoverDbService : ICoverDbService
{
if (!string.IsNullOrEmpty(url))
{
var filePath = await CreateThumbnail(url, $"{ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId)}", fromBase64);
var tempDirectory = _directoryService.TempDirectory;
var finalFileName = ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId) + ".webp";
var tempFileName = ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId) + "_new";
if (!string.IsNullOrEmpty(filePath))
var tempFilePath = await CreateThumbnail(url, tempFileName, fromBase64, tempDirectory);
if (!string.IsNullOrEmpty(tempFilePath))
{
// Additional check to see if downloaded image is similar and we have a higher resolution
var tempFullPath = Path.Combine(tempDirectory, tempFilePath);
var finalFullPath = Path.Combine(_directoryService.CoverImageDirectory, finalFileName);
if (chooseBetterImage && !string.IsNullOrEmpty(chapter.CoverImage))
{
try
{
var betterImage = Path.Join(_directoryService.CoverImageDirectory, chapter.CoverImage)
.GetBetterImage(Path.Join(_directoryService.CoverImageDirectory, filePath))!;
filePath = Path.GetFileName(betterImage);
var existingPath = Path.Combine(_directoryService.CoverImageDirectory, chapter.CoverImage);
var betterImage = existingPath.GetBetterImage(tempFullPath)!;
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
if (choseNewImage)
{
// This will fail if Cover gen is done just before this as there is a bug with files getting locked.
_directoryService.DeleteFiles([existingPath]);
_directoryService.CopyFile(tempFullPath, finalFullPath);
_directoryService.DeleteFiles([tempFullPath]);
}
else
{
_directoryService.DeleteFiles([tempFullPath]);
}
chapter.CoverImage = finalFileName;
}
catch (Exception ex)
{
_logger.LogError(ex, "There was an issue trying to choose a better cover image for Chapter: {FileName} ({ChapterId})", chapter.Range, chapter.Id);
}
}
else
{
// No comparison needed, just copy and rename to final
_directoryService.CopyFile(tempFullPath, finalFullPath);
_directoryService.DeleteFiles([tempFullPath]);
chapter.CoverImage = finalFileName;
}
chapter.CoverImage = filePath;
chapter.CoverImageLocked = true;
_imageService.UpdateColorScape(chapter);
_unitOfWork.ChapterRepository.Update(chapter);
@ -633,13 +684,26 @@ public class CoverDbService : ICoverDbService
if (_unitOfWork.HasChanges())
{
await _unitOfWork.CommitAsync();
await _eventHub.SendMessageAsync(MessageFactory.CoverUpdate,
MessageFactory.CoverUpdateEvent(chapter.Id, MessageFactoryEntityTypes.Chapter), false);
await _eventHub.SendMessageAsync(
MessageFactory.CoverUpdate,
MessageFactory.CoverUpdateEvent(chapter.Id, MessageFactoryEntityTypes.Chapter),
false
);
}
}
private async Task<string> CreateThumbnail(string url, string filename, bool fromBase64 = true)
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="filenameWithoutExtension">Filename without extension</param>
/// <param name="fromBase64"></param>
/// <param name="targetDirectory">Not useable with fromBase64. Allows a different directory to be written to</param>
/// <returns></returns>
private async Task<string> CreateThumbnail(string url, string filenameWithoutExtension, bool fromBase64 = true, string? targetDirectory = null)
{
targetDirectory ??= _directoryService.CoverImageDirectory;
var settings = await _unitOfWork.SettingsRepository.GetSettingsDtoAsync();
var encodeFormat = settings.EncodeMediaAs;
var coverImageSize = settings.CoverImageSize;
@ -647,9 +711,9 @@ public class CoverDbService : ICoverDbService
if (fromBase64)
{
return _imageService.CreateThumbnailFromBase64(url,
filename, encodeFormat, coverImageSize.GetDimensions().Width);
filenameWithoutExtension, encodeFormat, coverImageSize.GetDimensions().Width);
}
return await DownloadImageFromUrl(filename, encodeFormat, url);
return await DownloadImageFromUrl(filenameWithoutExtension, encodeFormat, url, targetDirectory);
}
}

View File

@ -194,8 +194,8 @@ public class ProcessSeries : IProcessSeries
if (seriesAdded)
{
// See if any recommendations can link up to the series and pre-fetch external metadata for the series
BackgroundJob.Enqueue(() =>
_externalMetadataService.FetchSeriesMetadata(series.Id, series.Library.Type));
// BackgroundJob.Enqueue(() =>
// _externalMetadataService.FetchSeriesMetadata(series.Id, series.Library.Type));
await _eventHub.SendMessageAsync(MessageFactory.SeriesAdded,
MessageFactory.SeriesAddedEvent(series.Id, series.Name, series.LibraryId), false);
@ -214,6 +214,10 @@ public class ProcessSeries : IProcessSeries
return;
}
if (seriesAdded)
{
await _externalMetadataService.FetchSeriesMetadata(series.Id, series.Library.Type);
}
await _metadataService.GenerateCoversForSeries(series.LibraryId, series.Id, false, false);
await _wordCountAnalyzerService.ScanSeries(series.LibraryId, series.Id, forceUpdate);
}

View File

@ -53,7 +53,7 @@
<app-match-series-result-item [item]="item" [isDarkMode]="(themeService.isDarkMode$ | async)!" (selected)="selectMatch($event)"></app-match-series-result-item>
} @empty {
@if (!isLoading) {
{{t('no-results')}}
<p>{{t('no-results')}}</p>
}
}
}

View File

@ -279,7 +279,11 @@ export class ChapterDetailComponent implements OnInit {
this.showDetailsTab = hasAnyCast(this.chapter) || (this.chapter.genres || []).length > 0 ||
(this.chapter.tags || []).length > 0 || this.chapter.webLinks.length > 0;
if (!this.showDetailsTab && this.activeTabId === TabID.Details) {
this.activeTabId = TabID.Reviews;
}
this.isLoading = false;
this.cdRef.markForCheck();
});