WebP Covers + Series Detail Enhancements (#1652)

* Implemented save covers as webp. Reworked screen to provide more information up front about webp and what browsers can support it.

* cleaned up pages to use compact numbering and made compact numbering expand into one decimal place (20.5K)

* Fixed an issue with adding new device

* If a book has an invalid language set, drop the language altogether rather than reading in a corrupted entry.

* Ensure genres and tags render alphabetically.

Improved support for partial volumes in Comic parser.

* Ensure all people, tags, collections, and genres are in alphabetical order.

* Moved some code to Extensions to clean up code.

* More unit tests

* Cleaned up release year filter css

* Tweaked some code in all series to make bulk deletes cleaner on the UI.

* Trying out want to read and unread count on series detail page

* Added Want to Read button for series page to make it easy to see when something is in want to read list and toggle it.

Added tooltips instead of title to buttons, but they don't style correctly.

Added a continue point under cover image.

* Code smells
This commit is contained in:
Joe Milazzo 2022-11-14 08:43:19 -06:00 committed by GitHub
parent f907486c74
commit e75b208d59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 481 additions and 175 deletions

View File

@ -100,6 +100,7 @@ public class ComicParserTests
[InlineData("Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)", "1")] [InlineData("Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)", "1")]
[InlineData("Scott Pilgrim 02 - Scott Pilgrim vs. The World (2005)", "0")] [InlineData("Scott Pilgrim 02 - Scott Pilgrim vs. The World (2005)", "0")]
[InlineData("Superman v1 024 (09-10 1943)", "1")] [InlineData("Superman v1 024 (09-10 1943)", "1")]
[InlineData("Superman v1.5 024 (09-10 1943)", "1.5")]
[InlineData("Amazing Man Comics chapter 25", "0")] [InlineData("Amazing Man Comics chapter 25", "0")]
[InlineData("Invincible 033.5 - Marvel Team-Up 14 (2006) (digital) (Minutemen-Slayer)", "0")] [InlineData("Invincible 033.5 - Marvel Team-Up 14 (2006) (digital) (Minutemen-Slayer)", "0")]
[InlineData("Cyberpunk 2077 - Trauma Team 04.cbz", "0")] [InlineData("Cyberpunk 2077 - Trauma Team 04.cbz", "0")]
@ -118,6 +119,7 @@ public class ComicParserTests
[InlineData("Cyberpunk 2077 - Trauma Team 04.cbz", "0")] [InlineData("Cyberpunk 2077 - Trauma Team 04.cbz", "0")]
[InlineData("2000 AD 0366 [1984-04-28] (flopbie)", "0")] [InlineData("2000 AD 0366 [1984-04-28] (flopbie)", "0")]
[InlineData("Daredevil - v6 - 10 - (2019)", "6")] [InlineData("Daredevil - v6 - 10 - (2019)", "6")]
[InlineData("Daredevil - v6.5", "6.5")]
// Tome Tests // Tome Tests
[InlineData("Daredevil - t6 - 10 - (2019)", "6")] [InlineData("Daredevil - t6 - 10 - (2019)", "6")]
[InlineData("Batgirl T2000 #57", "2000")] [InlineData("Batgirl T2000 #57", "2000")]

View File

@ -41,7 +41,7 @@ internal class MockReadingItemServiceForCacheService : IReadingItemService
return 1; return 1;
} }
public string GetCoverImage(string fileFilePath, string fileName, MangaFormat format) public string GetCoverImage(string fileFilePath, string fileName, MangaFormat format, bool saveAsWebP)
{ {
return string.Empty; return string.Empty;
} }

View File

@ -6,9 +6,11 @@ using System.IO.Abstractions.TestingHelpers;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Data; using API.Data;
using API.Data.Repositories;
using API.DTOs.Settings; using API.DTOs.Settings;
using API.Entities; using API.Entities;
using API.Entities.Enums; using API.Entities.Enums;
using API.Entities.Metadata;
using API.Helpers; using API.Helpers;
using API.Helpers.Converters; using API.Helpers.Converters;
using API.Services; using API.Services;
@ -129,7 +131,6 @@ public class CleanupServiceTests
#endregion #endregion
#region DeleteSeriesCoverImages #region DeleteSeriesCoverImages
[Fact] [Fact]
@ -469,6 +470,105 @@ public class CleanupServiceTests
#endregion #endregion
#region CleanupDbEntries
[Fact]
public async Task CleanupDbEntries_CleanupAbandonedChapters()
{
var c = EntityFactory.CreateChapter("1", false, new List<MangaFile>(), 1);
_context.Series.Add(new Series()
{
Name = "Test",
Library = new Library() {
Name = "Test LIb",
Type = LibraryType.Manga,
},
Volumes = new List<Volume>()
{
EntityFactory.CreateVolume("0", new List<Chapter>()
{
c,
}),
}
});
_context.AppUser.Add(new AppUser()
{
UserName = "majora2007"
});
await _context.SaveChangesAsync();
var readerService = new ReaderService(_unitOfWork, Substitute.For<ILogger<ReaderService>>(), Substitute.For<IEventHub>());
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync("majora2007", AppUserIncludes.Progress);
await readerService.MarkChaptersUntilAsRead(user, 1, 5);
await _context.SaveChangesAsync();
// Validate correct chapters have read status
Assert.Equal(1, (await _unitOfWork.AppUserProgressRepository.GetUserProgressAsync(1, 1)).PagesRead);
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.Single(await _unitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
await cleanupService.CleanupDbEntries();
Assert.Empty(await _unitOfWork.AppUserProgressRepository.GetUserProgressForSeriesAsync(1, 1));
}
[Fact]
public async Task CleanupDbEntries_RemoveTagsWithoutSeries()
{
var c = new CollectionTag()
{
Title = "Test Tag"
};
var s = new Series()
{
Name = "Test",
Library = new Library()
{
Name = "Test LIb",
Type = LibraryType.Manga,
},
Volumes = new List<Volume>(),
Metadata = new SeriesMetadata()
{
CollectionTags = new List<CollectionTag>()
{
c
}
}
};
_context.Series.Add(s);
_context.AppUser.Add(new AppUser()
{
UserName = "majora2007"
});
await _context.SaveChangesAsync();
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();
await cleanupService.CleanupDbEntries();
Assert.Empty(await _unitOfWork.CollectionTagRepository.GetAllTagsAsync());
}
#endregion
// #region CleanupBookmarks // #region CleanupBookmarks
// //
// [Fact] // [Fact]

View File

@ -46,7 +46,7 @@ internal class MockReadingItemService : IReadingItemService
return 1; return 1;
} }
public string GetCoverImage(string fileFilePath, string fileName, MangaFormat format) public string GetCoverImage(string fileFilePath, string fileName, MangaFormat format, bool saveAsWebP)
{ {
return string.Empty; return string.Empty;
} }

View File

@ -19,7 +19,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using TaskScheduler = System.Threading.Tasks.TaskScheduler; using TaskScheduler = API.Services.TaskScheduler;
namespace API.Controllers; namespace API.Controllers;
@ -119,6 +119,8 @@ public class ServerController : BaseApiController
[HttpPost("convert-bookmarks")] [HttpPost("convert-bookmarks")]
public ActionResult ScheduleConvertBookmarks() public ActionResult ScheduleConvertBookmarks()
{ {
if (TaskScheduler.HasAlreadyEnqueuedTask(BookmarkService.Name, "ConvertAllBookmarkToWebP", Array.Empty<object>(),
TaskScheduler.DefaultQueue, true)) return Ok();
BackgroundJob.Enqueue(() => _bookmarkService.ConvertAllBookmarkToWebP()); BackgroundJob.Enqueue(() => _bookmarkService.ConvertAllBookmarkToWebP());
return Ok(); return Ok();
} }

View File

@ -176,6 +176,12 @@ public class SettingsController : BaseApiController
_unitOfWork.SettingsRepository.Update(setting); _unitOfWork.SettingsRepository.Update(setting);
} }
if (setting.Key == ServerSettingKey.ConvertCoverToWebP && updateSettingsDto.ConvertCoverToWebP + string.Empty != setting.Value)
{
setting.Value = updateSettingsDto.ConvertCoverToWebP + string.Empty;
_unitOfWork.SettingsRepository.Update(setting);
}
if (setting.Key == ServerSettingKey.BookmarkDirectory && bookmarkDirectory != setting.Value) if (setting.Key == ServerSettingKey.BookmarkDirectory && bookmarkDirectory != setting.Value)
{ {

View File

@ -41,6 +41,13 @@ public class WantToReadController : BaseApiController
return Ok(pagedList); return Ok(pagedList);
} }
[HttpGet]
public async Task<ActionResult<PagedList<SeriesDto>>> GetWantToRead([FromQuery] int seriesId)
{
var user = await _unitOfWork.UserRepository.GetUserByUsernameAsync(User.GetUsername());
return Ok(await _unitOfWork.SeriesRepository.IsSeriesInWantToRead(user.Id, seriesId));
}
/// <summary> /// <summary>
/// Given a list of Series Ids, add them to the current logged in user's Want To Read list /// Given a list of Series Ids, add them to the current logged in user's Want To Read list
/// </summary> /// </summary>

View File

@ -24,5 +24,13 @@ public class SeriesDetailDto
/// These are chapters that are in Volume 0 and should be read AFTER the volumes /// These are chapters that are in Volume 0 and should be read AFTER the volumes
/// </summary> /// </summary>
public IEnumerable<ChapterDto> StorylineChapters { get; set; } public IEnumerable<ChapterDto> StorylineChapters { get; set; }
/// <summary>
/// How many chapters are unread
/// </summary>
public int UnreadCount { get; set; }
/// <summary>
/// How many chapters are there
/// </summary>
public int TotalCount { get; set; }
} }

View File

@ -65,4 +65,8 @@ public class ServerSettingDto
/// </summary> /// </summary>
/// <remarks>Value should be between 1 and 30</remarks> /// <remarks>Value should be between 1 and 30</remarks>
public int TotalLogs { get; set; } public int TotalLogs { get; set; }
/// <summary>
/// If the server should save covers as WebP encoding
/// </summary>
public bool ConvertCoverToWebP { get; set; }
} }

View File

@ -1,5 +1,5 @@
using System.Collections.Generic; using System;
using System.IO; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Data.Misc; using API.Data.Misc;
@ -12,6 +12,13 @@ using Microsoft.EntityFrameworkCore;
namespace API.Data.Repositories; namespace API.Data.Repositories;
[Flags]
public enum CollectionTagIncludes
{
None = 1,
SeriesMetadata = 2,
}
public interface ICollectionTagRepository public interface ICollectionTagRepository
{ {
void Add(CollectionTag tag); void Add(CollectionTag tag);
@ -21,7 +28,7 @@ public interface ICollectionTagRepository
Task<string> GetCoverImageAsync(int collectionTagId); Task<string> GetCoverImageAsync(int collectionTagId);
Task<IEnumerable<CollectionTagDto>> GetAllPromotedTagDtosAsync(int userId); Task<IEnumerable<CollectionTagDto>> GetAllPromotedTagDtosAsync(int userId);
Task<CollectionTag> GetTagAsync(int tagId); Task<CollectionTag> GetTagAsync(int tagId);
Task<CollectionTag> GetFullTagAsync(int tagId); Task<CollectionTag> GetFullTagAsync(int tagId, CollectionTagIncludes includes = CollectionTagIncludes.SeriesMetadata);
void Update(CollectionTag tag); void Update(CollectionTag tag);
Task<int> RemoveTagsWithoutSeries(); Task<int> RemoveTagsWithoutSeries();
Task<IEnumerable<CollectionTag>> GetAllTagsAsync(); Task<IEnumerable<CollectionTag>> GetAllTagsAsync();
@ -76,6 +83,15 @@ public class CollectionTagRepository : ICollectionTagRepository
.ToListAsync(); .ToListAsync();
} }
public async Task<string> GetCoverImageAsync(int collectionTagId)
{
return await _context.CollectionTag
.Where(c => c.Id == collectionTagId)
.Select(c => c.CoverImage)
.AsNoTracking()
.SingleOrDefaultAsync();
}
public async Task<IList<string>> GetAllCoverImagesAsync() public async Task<IList<string>> GetAllCoverImagesAsync()
{ {
return await _context.CollectionTag return await _context.CollectionTag
@ -114,11 +130,11 @@ public class CollectionTagRepository : ICollectionTagRepository
.SingleOrDefaultAsync(); .SingleOrDefaultAsync();
} }
public async Task<CollectionTag> GetFullTagAsync(int tagId) public async Task<CollectionTag> GetFullTagAsync(int tagId, CollectionTagIncludes includes = CollectionTagIncludes.SeriesMetadata)
{ {
return await _context.CollectionTag return await _context.CollectionTag
.Where(c => c.Id == tagId) .Where(c => c.Id == tagId)
.Include(c => c.SeriesMetadatas) .Includes(includes)
.AsSplitQuery() .AsSplitQuery()
.SingleOrDefaultAsync(); .SingleOrDefaultAsync();
} }
@ -143,19 +159,9 @@ public class CollectionTagRepository : ICollectionTagRepository
.Where(s => EF.Functions.Like(s.Title, $"%{searchQuery}%") .Where(s => EF.Functions.Like(s.Title, $"%{searchQuery}%")
|| EF.Functions.Like(s.NormalizedTitle, $"%{searchQuery}%")) || EF.Functions.Like(s.NormalizedTitle, $"%{searchQuery}%"))
.RestrictAgainstAgeRestriction(userRating) .RestrictAgainstAgeRestriction(userRating)
.OrderBy(s => s.Title) .OrderBy(s => s.NormalizedTitle)
.AsNoTracking() .AsNoTracking()
.OrderBy(c => c.NormalizedTitle)
.ProjectTo<CollectionTagDto>(_mapper.ConfigurationProvider) .ProjectTo<CollectionTagDto>(_mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();
} }
public async Task<string> GetCoverImageAsync(int collectionTagId)
{
return await _context.CollectionTag
.Where(c => c.Id == collectionTagId)
.Select(c => c.CoverImage)
.AsNoTracking()
.SingleOrDefaultAsync();
}
} }

View File

@ -80,7 +80,7 @@ public class GenreRepository : IGenreRepository
.SelectMany(s => s.Metadata.Genres) .SelectMany(s => s.Metadata.Genres)
.AsSplitQuery() .AsSplitQuery()
.Distinct() .Distinct()
.OrderBy(p => p.Title) .OrderBy(p => p.NormalizedTitle)
.ProjectTo<GenreTagDto>(_mapper.ConfigurationProvider) .ProjectTo<GenreTagDto>(_mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();
} }
@ -101,6 +101,7 @@ public class GenreRepository : IGenreRepository
var ageRating = await _context.AppUser.GetUserAgeRestriction(userId); var ageRating = await _context.AppUser.GetUserAgeRestriction(userId);
return await _context.Genre return await _context.Genre
.RestrictAgainstAgeRestriction(ageRating) .RestrictAgainstAgeRestriction(ageRating)
.OrderBy(g => g.NormalizedTitle)
.AsNoTracking() .AsNoTracking()
.ProjectTo<GenreTagDto>(_mapper.ConfigurationProvider) .ProjectTo<GenreTagDto>(_mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();

View File

@ -101,6 +101,7 @@ public interface ISeriesRepository
Task<SeriesDto> GetSeriesForMangaFile(int mangaFileId, int userId); Task<SeriesDto> GetSeriesForMangaFile(int mangaFileId, int userId);
Task<SeriesDto> GetSeriesForChapter(int chapterId, int userId); Task<SeriesDto> GetSeriesForChapter(int chapterId, int userId);
Task<PagedList<SeriesDto>> GetWantToReadForUserAsync(int userId, UserParams userParams, FilterDto filter); Task<PagedList<SeriesDto>> GetWantToReadForUserAsync(int userId, UserParams userParams, FilterDto filter);
Task<bool> IsSeriesInWantToRead(int userId, int seriesId);
Task<Series> GetSeriesByFolderPath(string folder, SeriesIncludes includes = SeriesIncludes.None); Task<Series> GetSeriesByFolderPath(string folder, SeriesIncludes includes = SeriesIncludes.None);
Task<Series> GetFullSeriesByAnyName(string seriesName, string localizedName, int libraryId, MangaFormat format, bool withFullIncludes = true); Task<Series> GetFullSeriesByAnyName(string seriesName, string localizedName, int libraryId, MangaFormat format, bool withFullIncludes = true);
Task<IList<Series>> RemoveSeriesNotInList(IList<ParsedSeries> seenSeries, int libraryId); Task<IList<Series>> RemoveSeriesNotInList(IList<ParsedSeries> seenSeries, int libraryId);
@ -161,12 +162,10 @@ public class SeriesRepository : ISeriesRepository
public async Task<IEnumerable<Series>> GetSeriesForLibraryIdAsync(int libraryId, SeriesIncludes includes = SeriesIncludes.None) public async Task<IEnumerable<Series>> GetSeriesForLibraryIdAsync(int libraryId, SeriesIncludes includes = SeriesIncludes.None)
{ {
var query = _context.Series return await _context.Series
.Where(s => s.LibraryId == libraryId); .Where(s => s.LibraryId == libraryId)
.Includes(includes)
query = AddIncludesToQuery(query, includes); .OrderBy(s => s.SortName).ToListAsync();
return await query.OrderBy(s => s.SortName).ToListAsync();
} }
/// <summary> /// <summary>
@ -427,13 +426,10 @@ public class SeriesRepository : ISeriesRepository
/// <returns></returns> /// <returns></returns>
public async Task<Series> GetSeriesByIdAsync(int seriesId, SeriesIncludes includes = SeriesIncludes.Volumes | SeriesIncludes.Metadata) public async Task<Series> GetSeriesByIdAsync(int seriesId, SeriesIncludes includes = SeriesIncludes.Volumes | SeriesIncludes.Metadata)
{ {
var query = _context.Series return await _context.Series
.Where(s => s.Id == seriesId) .Where(s => s.Id == seriesId)
.AsSplitQuery(); .Includes(includes)
.SingleOrDefaultAsync();
query = AddIncludesToQuery(query, includes);
return await query.SingleOrDefaultAsync();
} }
/// <summary> /// <summary>
@ -833,8 +829,8 @@ public class SeriesRepository : ISeriesRepository
{ {
var metadataDto = await _context.SeriesMetadata var metadataDto = await _context.SeriesMetadata
.Where(metadata => metadata.SeriesId == seriesId) .Where(metadata => metadata.SeriesId == seriesId)
.Include(m => m.Genres) .Include(m => m.Genres.OrderBy(g => g.NormalizedTitle))
.Include(m => m.Tags) .Include(m => m.Tags.OrderBy(g => g.NormalizedTitle))
.Include(m => m.People) .Include(m => m.People)
.AsNoTracking() .AsNoTracking()
.ProjectTo<SeriesMetadataDto>(_mapper.ConfigurationProvider) .ProjectTo<SeriesMetadataDto>(_mapper.ConfigurationProvider)
@ -848,6 +844,7 @@ public class SeriesRepository : ISeriesRepository
.Where(t => t.SeriesMetadatas.Select(s => s.SeriesId).Contains(seriesId)) .Where(t => t.SeriesMetadatas.Select(s => s.SeriesId).Contains(seriesId))
.ProjectTo<CollectionTagDto>(_mapper.ConfigurationProvider) .ProjectTo<CollectionTagDto>(_mapper.ConfigurationProvider)
.AsNoTracking() .AsNoTracking()
.OrderBy(t => t.Title)
.AsSplitQuery() .AsSplitQuery()
.ToListAsync(); .ToListAsync();
} }
@ -1147,11 +1144,10 @@ public class SeriesRepository : ISeriesRepository
public async Task<Series> GetSeriesByFolderPath(string folder, SeriesIncludes includes = SeriesIncludes.None) public async Task<Series> GetSeriesByFolderPath(string folder, SeriesIncludes includes = SeriesIncludes.None)
{ {
var normalized = Services.Tasks.Scanner.Parser.Parser.NormalizePath(folder); var normalized = Services.Tasks.Scanner.Parser.Parser.NormalizePath(folder);
var query = _context.Series.Where(s => s.FolderPath.Equals(normalized)); return await _context.Series
.Where(s => s.FolderPath.Equals(normalized))
query = AddIncludesToQuery(query, includes); .Includes(includes)
.SingleOrDefaultAsync();
return await query.SingleOrDefaultAsync();
} }
/// <summary> /// <summary>
@ -1479,6 +1475,17 @@ public class SeriesRepository : ISeriesRepository
return await PagedList<SeriesDto>.CreateAsync(filteredQuery.ProjectTo<SeriesDto>(_mapper.ConfigurationProvider), userParams.PageNumber, userParams.PageSize); return await PagedList<SeriesDto>.CreateAsync(filteredQuery.ProjectTo<SeriesDto>(_mapper.ConfigurationProvider), userParams.PageNumber, userParams.PageSize);
} }
public async Task<bool> IsSeriesInWantToRead(int userId, int seriesId)
{
var libraryIds = GetLibraryIdsForUser(userId);
return await _context.AppUser
.Where(user => user.Id == userId)
.SelectMany(u => u.WantToRead)
.AsSplitQuery()
.AsNoTracking()
.AnyAsync(s => libraryIds.Contains(s.LibraryId) && s.Id == seriesId);
}
public async Task<IDictionary<string, IList<SeriesModified>>> GetFolderPathMap(int libraryId) public async Task<IDictionary<string, IList<SeriesModified>>> GetFolderPathMap(int libraryId)
{ {
var info = await _context.Series var info = await _context.Series
@ -1528,40 +1535,4 @@ public class SeriesRepository : ISeriesRepository
.OrderBy(s => s) .OrderBy(s => s)
.LastOrDefaultAsync(); .LastOrDefaultAsync();
} }
private static IQueryable<Series> AddIncludesToQuery(IQueryable<Series> query, SeriesIncludes includeFlags)
{
// TODO: Move this to an Extension Method
if (includeFlags.HasFlag(SeriesIncludes.Library))
{
query = query.Include(u => u.Library);
}
if (includeFlags.HasFlag(SeriesIncludes.Volumes))
{
query = query.Include(s => s.Volumes);
}
if (includeFlags.HasFlag(SeriesIncludes.Related))
{
query = query.Include(s => s.Relations)
.ThenInclude(r => r.TargetSeries)
.Include(s => s.RelationOf);
}
if (includeFlags.HasFlag(SeriesIncludes.Metadata))
{
query = query.Include(s => s.Metadata)
.ThenInclude(m => m.CollectionTags)
.Include(s => s.Metadata)
.ThenInclude(m => m.Genres)
.Include(s => s.Metadata)
.ThenInclude(m => m.People)
.Include(s => s.Metadata)
.ThenInclude(m => m.Tags);
}
return query.AsSplitQuery();
}
} }

View File

@ -64,7 +64,7 @@ public class TagRepository : ITagRepository
.SelectMany(s => s.Metadata.Tags) .SelectMany(s => s.Metadata.Tags)
.AsSplitQuery() .AsSplitQuery()
.Distinct() .Distinct()
.OrderBy(t => t.Title) .OrderBy(t => t.NormalizedTitle)
.AsNoTracking() .AsNoTracking()
.ProjectTo<TagDto>(_mapper.ConfigurationProvider) .ProjectTo<TagDto>(_mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();
@ -81,7 +81,7 @@ public class TagRepository : ITagRepository
return await _context.Tag return await _context.Tag
.AsNoTracking() .AsNoTracking()
.RestrictAgainstAgeRestriction(userRating) .RestrictAgainstAgeRestriction(userRating)
.OrderBy(t => t.Title) .OrderBy(t => t.NormalizedTitle)
.ProjectTo<TagDto>(_mapper.ConfigurationProvider) .ProjectTo<TagDto>(_mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();
} }

View File

@ -102,6 +102,7 @@ public static class Seed
new() {Key = ServerSettingKey.TotalBackups, Value = "30"}, new() {Key = ServerSettingKey.TotalBackups, Value = "30"},
new() {Key = ServerSettingKey.TotalLogs, Value = "30"}, new() {Key = ServerSettingKey.TotalLogs, Value = "30"},
new() {Key = ServerSettingKey.EnableFolderWatching, Value = "false"}, new() {Key = ServerSettingKey.EnableFolderWatching, Value = "false"},
new() {Key = ServerSettingKey.ConvertCoverToWebP, Value = "false"},
}.ToArray()); }.ToArray());
foreach (var defaultSetting in DefaultSettings) foreach (var defaultSetting in DefaultSettings)

View File

@ -101,4 +101,9 @@ public enum ServerSettingKey
/// </summary> /// </summary>
[Description("TotalLogs")] [Description("TotalLogs")]
TotalLogs = 18, TotalLogs = 18,
/// <summary>
/// If Kavita should save covers as WebP images
/// </summary>
[Description("ConvertCoverToWebP")]
ConvertCoverToWebP = 19,
} }

View File

@ -1,6 +1,7 @@
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Data.Misc; using API.Data.Misc;
using API.Data.Repositories;
using API.Entities; using API.Entities;
using API.Entities.Enums; using API.Entities.Enums;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@ -110,4 +111,51 @@ public static class QueryableExtensions
}) })
.SingleAsync(); .SingleAsync();
} }
public static IQueryable<CollectionTag> Includes(this IQueryable<CollectionTag> queryable,
CollectionTagIncludes includes)
{
if (includes.HasFlag(CollectionTagIncludes.SeriesMetadata))
{
queryable = queryable.Include(c => c.SeriesMetadatas);
}
return queryable.AsSplitQuery();
}
public static IQueryable<Series> Includes(this IQueryable<Series> query,
SeriesIncludes includeFlags)
{
if (includeFlags.HasFlag(SeriesIncludes.Library))
{
query = query.Include(u => u.Library);
}
if (includeFlags.HasFlag(SeriesIncludes.Volumes))
{
query = query.Include(s => s.Volumes);
}
if (includeFlags.HasFlag(SeriesIncludes.Related))
{
query = query.Include(s => s.Relations)
.ThenInclude(r => r.TargetSeries)
.Include(s => s.RelationOf);
}
if (includeFlags.HasFlag(SeriesIncludes.Metadata))
{
query = query.Include(s => s.Metadata)
.ThenInclude(m => m.CollectionTags.OrderBy(g => g.NormalizedTitle))
.Include(s => s.Metadata)
.ThenInclude(m => m.Genres.OrderBy(g => g.NormalizedTitle))
.Include(s => s.Metadata)
.ThenInclude(m => m.People)
.Include(s => s.Metadata)
.ThenInclude(m => m.Tags.OrderBy(g => g.NormalizedTitle));
}
return query.AsSplitQuery();
}
} }

View File

@ -37,66 +37,88 @@ public class AutoMapperProfiles : Profile
CreateMap<SeriesMetadata, SeriesMetadataDto>() CreateMap<SeriesMetadata, SeriesMetadataDto>()
.ForMember(dest => dest.Writers, .ForMember(dest => dest.Writers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Writer))) opt.MapFrom(
src => src.People.Where(p => p.Role == PersonRole.Writer).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.CoverArtists, .ForMember(dest => dest.CoverArtists,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.CoverArtist))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.CoverArtist).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Characters, .ForMember(dest => dest.Characters,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Character))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Character).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Publishers, .ForMember(dest => dest.Publishers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Publisher))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Publisher).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Colorists, .ForMember(dest => dest.Colorists,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Colorist))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Colorist).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Inkers, .ForMember(dest => dest.Inkers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Inker))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Inker).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Letterers, .ForMember(dest => dest.Letterers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Letterer))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Letterer).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Pencillers, .ForMember(dest => dest.Pencillers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Penciller))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Penciller).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Translators, .ForMember(dest => dest.Translators,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Translator))) opt.MapFrom(src =>
src.People.Where(p => p.Role == PersonRole.Translator).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Editors, .ForMember(dest => dest.Editors,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Editor))); opt.MapFrom(
src => src.People.Where(p => p.Role == PersonRole.Editor).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Genres,
opt =>
opt.MapFrom(
src => src.Genres.OrderBy(p => p.NormalizedTitle)))
.ForMember(dest => dest.CollectionTags,
opt =>
opt.MapFrom(
src => src.CollectionTags.OrderBy(p => p.NormalizedTitle)))
.ForMember(dest => dest.Tags,
opt =>
opt.MapFrom(
src => src.Tags.OrderBy(p => p.NormalizedTitle)));
CreateMap<Chapter, ChapterMetadataDto>() CreateMap<Chapter, ChapterMetadataDto>()
.ForMember(dest => dest.Writers, .ForMember(dest => dest.Writers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Writer))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Writer).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.CoverArtists, .ForMember(dest => dest.CoverArtists,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.CoverArtist))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.CoverArtist).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Colorists, .ForMember(dest => dest.Colorists,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Colorist))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Colorist).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Inkers, .ForMember(dest => dest.Inkers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Inker))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Inker).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Letterers, .ForMember(dest => dest.Letterers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Letterer))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Letterer).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Pencillers, .ForMember(dest => dest.Pencillers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Penciller))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Penciller).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Publishers, .ForMember(dest => dest.Publishers,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Publisher))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Publisher).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Translators, .ForMember(dest => dest.Translators,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Translator))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Translator).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Characters, .ForMember(dest => dest.Characters,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Character))) opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Character).OrderBy(p => p.NormalizedName)))
.ForMember(dest => dest.Editors, .ForMember(dest => dest.Editors,
opt => opt =>
opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Editor))); opt.MapFrom(src => src.People.Where(p => p.Role == PersonRole.Editor).OrderBy(p => p.NormalizedName)));
CreateMap<AppUser, UserDto>() CreateMap<AppUser, UserDto>()
.ForMember(dest => dest.AgeRestriction, .ForMember(dest => dest.AgeRestriction,

View File

@ -51,6 +51,9 @@ public class ServerSettingConverter : ITypeConverter<IEnumerable<ServerSetting>,
case ServerSettingKey.ConvertBookmarkToWebP: case ServerSettingKey.ConvertBookmarkToWebP:
destination.ConvertBookmarkToWebP = bool.Parse(row.Value); destination.ConvertBookmarkToWebP = bool.Parse(row.Value);
break; break;
case ServerSettingKey.ConvertCoverToWebP:
destination.ConvertCoverToWebP = bool.Parse(row.Value);
break;
case ServerSettingKey.EnableSwaggerUi: case ServerSettingKey.EnableSwaggerUi:
destination.EnableSwaggerUi = bool.Parse(row.Value); destination.EnableSwaggerUi = bool.Parse(row.Value);
break; break;

View File

@ -20,7 +20,7 @@ public interface IArchiveService
{ {
void ExtractArchive(string archivePath, string extractPath); void ExtractArchive(string archivePath, string extractPath);
int GetNumberOfPagesFromArchive(string archivePath); int GetNumberOfPagesFromArchive(string archivePath);
string GetCoverImage(string archivePath, string fileName, string outputDirectory); string GetCoverImage(string archivePath, string fileName, string outputDirectory, bool saveAsWebP = false);
bool IsValidArchive(string archivePath); bool IsValidArchive(string archivePath);
ComicInfo GetComicInfo(string archivePath); ComicInfo GetComicInfo(string archivePath);
ArchiveLibrary CanOpen(string archivePath); ArchiveLibrary CanOpen(string archivePath);
@ -196,8 +196,9 @@ public class ArchiveService : IArchiveService
/// <param name="archivePath"></param> /// <param name="archivePath"></param>
/// <param name="fileName">File name to use based on context of entity.</param> /// <param name="fileName">File name to use based on context of entity.</param>
/// <param name="outputDirectory">Where to output the file, defaults to covers directory</param> /// <param name="outputDirectory">Where to output the file, defaults to covers directory</param>
/// <param name="saveAsWebP">When saving the file, use WebP encoding instead of PNG</param>
/// <returns></returns> /// <returns></returns>
public string GetCoverImage(string archivePath, string fileName, string outputDirectory) public string GetCoverImage(string archivePath, string fileName, string outputDirectory, bool saveAsWebP = false)
{ {
if (archivePath == null || !IsValidArchive(archivePath)) return string.Empty; if (archivePath == null || !IsValidArchive(archivePath)) return string.Empty;
try try
@ -213,7 +214,7 @@ public class ArchiveService : IArchiveService
var entry = archive.Entries.Single(e => e.FullName == entryName); var entry = archive.Entries.Single(e => e.FullName == entryName);
using var stream = entry.Open(); using var stream = entry.Open();
return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory); return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory, saveAsWebP);
} }
case ArchiveLibrary.SharpCompress: case ArchiveLibrary.SharpCompress:
{ {
@ -224,7 +225,7 @@ public class ArchiveService : IArchiveService
var entry = archive.Entries.Single(e => e.Key == entryName); var entry = archive.Entries.Single(e => e.Key == entryName);
using var stream = entry.OpenEntryStream(); using var stream = entry.OpenEntryStream();
return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory); return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory, saveAsWebP);
} }
case ArchiveLibrary.NotSupported: case ArchiveLibrary.NotSupported:
_logger.LogWarning("[GetCoverImage] This archive cannot be read: {ArchivePath}. Defaulting to no cover image", archivePath); _logger.LogWarning("[GetCoverImage] This archive cannot be read: {ArchivePath}. Defaulting to no cover image", archivePath);

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -31,7 +32,7 @@ namespace API.Services;
public interface IBookService public interface IBookService
{ {
int GetNumberOfPages(string filePath); int GetNumberOfPages(string filePath);
string GetCoverImage(string fileFilePath, string fileName, string outputDirectory); string GetCoverImage(string fileFilePath, string fileName, string outputDirectory, bool saveAsWebP = false);
Task<Dictionary<string, int>> CreateKeyToPageMappingAsync(EpubBookRef book); Task<Dictionary<string, int>> CreateKeyToPageMappingAsync(EpubBookRef book);
/// <summary> /// <summary>
@ -432,7 +433,7 @@ public class BookService : IBookService
Year = year, Year = year,
Title = epubBook.Title, Title = epubBook.Title,
Genre = string.Join(",", epubBook.Schema.Package.Metadata.Subjects.Select(s => s.ToLower().Trim())), Genre = string.Join(",", epubBook.Schema.Package.Metadata.Subjects.Select(s => s.ToLower().Trim())),
LanguageISO = epubBook.Schema.Package.Metadata.Languages.FirstOrDefault() ?? string.Empty LanguageISO = ValidateLanguage(epubBook.Schema.Package.Metadata.Languages.FirstOrDefault())
}; };
ComicInfo.CleanComicInfo(info); ComicInfo.CleanComicInfo(info);
@ -477,6 +478,24 @@ public class BookService : IBookService
return null; return null;
} }
#nullable enable
private static string ValidateLanguage(string? language)
{
if (string.IsNullOrEmpty(language)) return string.Empty;
try
{
CultureInfo.GetCultureInfo(language);
}
catch (Exception)
{
return string.Empty;
}
return language;
}
#nullable disable
private bool IsValidFile(string filePath) private bool IsValidFile(string filePath)
{ {
if (!File.Exists(filePath)) if (!File.Exists(filePath))
@ -880,14 +899,15 @@ public class BookService : IBookService
/// <param name="fileFilePath"></param> /// <param name="fileFilePath"></param>
/// <param name="fileName">Name of the new file.</param> /// <param name="fileName">Name of the new file.</param>
/// <param name="outputDirectory">Where to output the file, defaults to covers directory</param> /// <param name="outputDirectory">Where to output the file, defaults to covers directory</param>
/// <param name="saveAsWebP">When saving the file, use WebP encoding instead of PNG</param>
/// <returns></returns> /// <returns></returns>
public string GetCoverImage(string fileFilePath, string fileName, string outputDirectory) public string GetCoverImage(string fileFilePath, string fileName, string outputDirectory, bool saveAsWebP = false)
{ {
if (!IsValidFile(fileFilePath)) return string.Empty; if (!IsValidFile(fileFilePath)) return string.Empty;
if (Tasks.Scanner.Parser.Parser.IsPdf(fileFilePath)) if (Tasks.Scanner.Parser.Parser.IsPdf(fileFilePath))
{ {
return GetPdfCoverImage(fileFilePath, fileName, outputDirectory); return GetPdfCoverImage(fileFilePath, fileName, outputDirectory, saveAsWebP);
} }
using var epubBook = EpubReader.OpenBook(fileFilePath, BookReaderOptions); using var epubBook = EpubReader.OpenBook(fileFilePath, BookReaderOptions);
@ -902,7 +922,7 @@ public class BookService : IBookService
if (coverImageContent == null) return string.Empty; if (coverImageContent == null) return string.Empty;
using var stream = coverImageContent.GetContentStream(); using var stream = coverImageContent.GetContentStream();
return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory); return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory, saveAsWebP);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -913,7 +933,7 @@ public class BookService : IBookService
} }
private string GetPdfCoverImage(string fileFilePath, string fileName, string outputDirectory) private string GetPdfCoverImage(string fileFilePath, string fileName, string outputDirectory, bool saveAsWebP)
{ {
try try
{ {
@ -923,7 +943,7 @@ public class BookService : IBookService
using var stream = StreamManager.GetStream("BookService.GetPdfPage"); using var stream = StreamManager.GetStream("BookService.GetPdfPage");
GetPdfPage(docReader, 0, stream); GetPdfPage(docReader, 0, stream);
return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory); return _imageService.WriteCoverThumbnail(stream, fileName, outputDirectory, saveAsWebP);
} }
catch (Exception ex) catch (Exception ex)

View File

@ -27,6 +27,7 @@ public interface IBookmarkService
public class BookmarkService : IBookmarkService public class BookmarkService : IBookmarkService
{ {
public const string Name = "BookmarkService";
private readonly ILogger<BookmarkService> _logger; private readonly ILogger<BookmarkService> _logger;
private readonly IUnitOfWork _unitOfWork; private readonly IUnitOfWork _unitOfWork;
private readonly IDirectoryService _directoryService; private readonly IDirectoryService _directoryService;

View File

@ -10,7 +10,7 @@ namespace API.Services;
public interface IImageService public interface IImageService
{ {
void ExtractImages(string fileFilePath, string targetDirectory, int fileCount = 1); void ExtractImages(string fileFilePath, string targetDirectory, int fileCount = 1);
string GetCoverImage(string path, string fileName, string outputDirectory); string GetCoverImage(string path, string fileName, string outputDirectory, bool saveAsWebP = false);
/// <summary> /// <summary>
/// Creates a Thumbnail version of a base64 image /// Creates a Thumbnail version of a base64 image
@ -20,7 +20,7 @@ public interface IImageService
/// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns> /// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns>
string CreateThumbnailFromBase64(string encodedImage, string fileName); string CreateThumbnailFromBase64(string encodedImage, string fileName);
string WriteCoverThumbnail(Stream stream, string fileName, string outputDirectory); string WriteCoverThumbnail(Stream stream, string fileName, string outputDirectory, bool saveAsWebP = false);
/// <summary> /// <summary>
/// Converts the passed image to webP and outputs it in the same directory /// Converts the passed image to webP and outputs it in the same directory
/// </summary> /// </summary>
@ -67,14 +67,14 @@ public class ImageService : IImageService
} }
} }
public string GetCoverImage(string path, string fileName, string outputDirectory) public string GetCoverImage(string path, string fileName, string outputDirectory, bool saveAsWebP = false)
{ {
if (string.IsNullOrEmpty(path)) return string.Empty; if (string.IsNullOrEmpty(path)) return string.Empty;
try try
{ {
using var thumbnail = Image.Thumbnail(path, ThumbnailWidth); using var thumbnail = Image.Thumbnail(path, ThumbnailWidth);
var filename = fileName + ".png"; var filename = fileName + (saveAsWebP ? ".webp" : ".png");
thumbnail.WriteToFile(_directoryService.FileSystem.Path.Join(outputDirectory, filename)); thumbnail.WriteToFile(_directoryService.FileSystem.Path.Join(outputDirectory, filename));
return filename; return filename;
} }
@ -93,11 +93,12 @@ public class ImageService : IImageService
/// <param name="stream">Stream to write to disk. Ensure this is rewinded.</param> /// <param name="stream">Stream to write to disk. Ensure this is rewinded.</param>
/// <param name="fileName">filename to save as without extension</param> /// <param name="fileName">filename to save as without extension</param>
/// <param name="outputDirectory">Where to output the file, defaults to covers directory</param> /// <param name="outputDirectory">Where to output the file, defaults to covers directory</param>
/// <param name="saveAsWebP">Export the file as webP otherwise will default to png</param>
/// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns> /// <returns>File name with extension of the file. This will always write to <see cref="DirectoryService.CoverImageDirectory"/></returns>
public string WriteCoverThumbnail(Stream stream, string fileName, string outputDirectory) public string WriteCoverThumbnail(Stream stream, string fileName, string outputDirectory, bool saveAsWebP = false)
{ {
using var thumbnail = Image.ThumbnailStream(stream, ThumbnailWidth); using var thumbnail = Image.ThumbnailStream(stream, ThumbnailWidth);
var filename = fileName + ".png"; var filename = fileName + (saveAsWebP ? ".webp" : ".png");
_directoryService.ExistOrCreate(outputDirectory); _directoryService.ExistOrCreate(outputDirectory);
try try
{ {

View File

@ -39,7 +39,7 @@ public interface IMetadataService
/// <param name="forceUpdate">Overrides any cache logic and forces execution</param> /// <param name="forceUpdate">Overrides any cache logic and forces execution</param>
Task GenerateCoversForSeries(int libraryId, int seriesId, bool forceUpdate = true); Task GenerateCoversForSeries(int libraryId, int seriesId, bool forceUpdate = true);
Task GenerateCoversForSeries(Series series, bool forceUpdate = false); Task GenerateCoversForSeries(Series series, bool convertToWebP, bool forceUpdate = false);
Task RemoveAbandonedMetadataKeys(); Task RemoveAbandonedMetadataKeys();
} }
@ -70,7 +70,8 @@ public class MetadataService : IMetadataService
/// </summary> /// </summary>
/// <param name="chapter"></param> /// <param name="chapter"></param>
/// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param> /// <param name="forceUpdate">Force updating cover image even if underlying file has not been modified or chapter already has a cover image</param>
private Task<bool> UpdateChapterCoverImage(Chapter chapter, bool forceUpdate) /// <param name="convertToWebPOnWrite">Convert image to WebP when extracting the cover</param>
private Task<bool> UpdateChapterCoverImage(Chapter chapter, bool forceUpdate, bool convertToWebPOnWrite)
{ {
var firstFile = chapter.Files.MinBy(x => x.Chapter); var firstFile = chapter.Files.MinBy(x => x.Chapter);
@ -80,7 +81,9 @@ public class MetadataService : IMetadataService
if (firstFile == null) return Task.FromResult(false); if (firstFile == null) return Task.FromResult(false);
_logger.LogDebug("[MetadataService] Generating cover image for {File}", firstFile.FilePath); _logger.LogDebug("[MetadataService] Generating cover image for {File}", firstFile.FilePath);
chapter.CoverImage = _readingItemService.GetCoverImage(firstFile.FilePath, ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId), firstFile.Format);
chapter.CoverImage = _readingItemService.GetCoverImage(firstFile.FilePath,
ImageService.GetChapterFormat(chapter.Id, chapter.VolumeId), firstFile.Format, convertToWebPOnWrite);
_unitOfWork.ChapterRepository.Update(chapter); _unitOfWork.ChapterRepository.Update(chapter);
_updateEvents.Add(MessageFactory.CoverUpdateEvent(chapter.Id, MessageFactoryEntityTypes.Chapter)); _updateEvents.Add(MessageFactory.CoverUpdateEvent(chapter.Id, MessageFactoryEntityTypes.Chapter));
return Task.FromResult(true); return Task.FromResult(true);
@ -143,7 +146,8 @@ public class MetadataService : IMetadataService
/// </summary> /// </summary>
/// <param name="series"></param> /// <param name="series"></param>
/// <param name="forceUpdate"></param> /// <param name="forceUpdate"></param>
private async Task ProcessSeriesCoverGen(Series series, bool forceUpdate) /// <param name="convertToWebP"></param>
private async Task ProcessSeriesCoverGen(Series series, bool forceUpdate, bool convertToWebP)
{ {
_logger.LogDebug("[MetadataService] Processing cover image generation for series: {SeriesName}", series.OriginalName); _logger.LogDebug("[MetadataService] Processing cover image generation for series: {SeriesName}", series.OriginalName);
try try
@ -156,7 +160,7 @@ public class MetadataService : IMetadataService
var index = 0; var index = 0;
foreach (var chapter in volume.Chapters) foreach (var chapter in volume.Chapters)
{ {
var chapterUpdated = await UpdateChapterCoverImage(chapter, forceUpdate); var chapterUpdated = await UpdateChapterCoverImage(chapter, forceUpdate, convertToWebP);
// If cover was update, either the file has changed or first scan and we should force a metadata update // If cover was update, either the file has changed or first scan and we should force a metadata update
UpdateChapterLastModified(chapter, forceUpdate || chapterUpdated); UpdateChapterLastModified(chapter, forceUpdate || chapterUpdated);
if (index == 0 && chapterUpdated) if (index == 0 && chapterUpdated)
@ -194,7 +198,7 @@ public class MetadataService : IMetadataService
[AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Delete)] [AutomaticRetry(Attempts = 3, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
public async Task GenerateCoversForLibrary(int libraryId, bool forceUpdate = false) public async Task GenerateCoversForLibrary(int libraryId, bool forceUpdate = false)
{ {
var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(libraryId, LibraryIncludes.None); var library = await _unitOfWork.LibraryRepository.GetLibraryForIdAsync(libraryId);
_logger.LogInformation("[MetadataService] Beginning cover generation refresh of {LibraryName}", library.Name); _logger.LogInformation("[MetadataService] Beginning cover generation refresh of {LibraryName}", library.Name);
_updateEvents.Clear(); _updateEvents.Clear();
@ -207,6 +211,8 @@ public class MetadataService : IMetadataService
await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress, await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress,
MessageFactory.CoverUpdateProgressEvent(library.Id, 0F, ProgressEventType.Started, $"Starting {library.Name}")); MessageFactory.CoverUpdateProgressEvent(library.Id, 0F, ProgressEventType.Started, $"Starting {library.Name}"));
var convertToWebP = (await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).ConvertCoverToWebP;
for (var chunk = 1; chunk <= chunkInfo.TotalChunks; chunk++) for (var chunk = 1; chunk <= chunkInfo.TotalChunks; chunk++)
{ {
if (chunkInfo.TotalChunks == 0) continue; if (chunkInfo.TotalChunks == 0) continue;
@ -235,7 +241,7 @@ public class MetadataService : IMetadataService
try try
{ {
await ProcessSeriesCoverGen(series, forceUpdate); await ProcessSeriesCoverGen(series, forceUpdate, convertToWebP);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -285,21 +291,23 @@ public class MetadataService : IMetadataService
return; return;
} }
await GenerateCoversForSeries(series, forceUpdate); var convertToWebP = (await _unitOfWork.SettingsRepository.GetSettingsDtoAsync()).ConvertCoverToWebP;
await GenerateCoversForSeries(series, convertToWebP, forceUpdate);
} }
/// <summary> /// <summary>
/// Generate Cover for a Series. This is used by Scan Loop and should not be invoked directly via User Interaction. /// Generate Cover for a Series. This is used by Scan Loop and should not be invoked directly via User Interaction.
/// </summary> /// </summary>
/// <param name="series">A full Series, with metadata, chapters, etc</param> /// <param name="series">A full Series, with metadata, chapters, etc</param>
/// <param name="convertToWebP">When saving the file, use WebP encoding instead of PNG</param>
/// <param name="forceUpdate"></param> /// <param name="forceUpdate"></param>
public async Task GenerateCoversForSeries(Series series, bool forceUpdate = false) public async Task GenerateCoversForSeries(Series series, bool convertToWebP, bool forceUpdate = false)
{ {
var sw = Stopwatch.StartNew(); var sw = Stopwatch.StartNew();
await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress, await _eventHub.SendMessageAsync(MessageFactory.NotificationProgress,
MessageFactory.CoverUpdateProgressEvent(series.LibraryId, 0F, ProgressEventType.Started, series.Name)); MessageFactory.CoverUpdateProgressEvent(series.LibraryId, 0F, ProgressEventType.Started, series.Name));
await ProcessSeriesCoverGen(series, forceUpdate); await ProcessSeriesCoverGen(series, forceUpdate, convertToWebP);
if (_unitOfWork.HasChanges()) if (_unitOfWork.HasChanges())

View File

@ -10,7 +10,7 @@ public interface IReadingItemService
{ {
ComicInfo GetComicInfo(string filePath); ComicInfo GetComicInfo(string filePath);
int GetNumberOfPages(string filePath, MangaFormat format); int GetNumberOfPages(string filePath, MangaFormat format);
string GetCoverImage(string filePath, string fileName, MangaFormat format); string GetCoverImage(string filePath, string fileName, MangaFormat format, bool saveAsWebP);
void Extract(string fileFilePath, string targetDirectory, MangaFormat format, int imageCount = 1); void Extract(string fileFilePath, string targetDirectory, MangaFormat format, int imageCount = 1);
ParserInfo Parse(string path, string rootPath, LibraryType type); ParserInfo Parse(string path, string rootPath, LibraryType type);
ParserInfo ParseFile(string path, string rootPath, LibraryType type); ParserInfo ParseFile(string path, string rootPath, LibraryType type);
@ -162,19 +162,20 @@ public class ReadingItemService : IReadingItemService
} }
} }
public string GetCoverImage(string filePath, string fileName, MangaFormat format) public string GetCoverImage(string filePath, string fileName, MangaFormat format, bool saveAsWebP)
{ {
if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName)) if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName))
{ {
return string.Empty; return string.Empty;
} }
return format switch return format switch
{ {
MangaFormat.Epub => _bookService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory), MangaFormat.Epub => _bookService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory, saveAsWebP),
MangaFormat.Archive => _archiveService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory), MangaFormat.Archive => _archiveService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory, saveAsWebP),
MangaFormat.Image => _imageService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory), MangaFormat.Image => _imageService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory, saveAsWebP),
MangaFormat.Pdf => _bookService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory), MangaFormat.Pdf => _bookService.GetCoverImage(filePath, fileName, _directoryService.CoverImageDirectory, saveAsWebP),
_ => string.Empty _ => string.Empty
}; };
} }

View File

@ -553,7 +553,9 @@ public class SeriesService : ISeriesService
Specials = specials, Specials = specials,
Chapters = retChapters, Chapters = retChapters,
Volumes = processedVolumes, Volumes = processedVolumes,
StorylineChapters = storylineChapters StorylineChapters = storylineChapters,
TotalCount = chapters.Count,
UnreadCount = chapters.Count(c => c.Pages > 0 && c.PagesRead < c.Pages)
}; };
} }

View File

@ -408,7 +408,7 @@ public static class Parser
{ {
// Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus) // Teen Titans v1 001 (1966-02) (digital) (OkC.O.M.P.U.T.O.-Novus)
new Regex( new Regex(
@"^(?<Series>.*)(?: |_)(t|v)(?<Volume>\d+)", @"^(?<Series>.+?)(?: |_)(t|v)(?<Volume>" + NumberRange + @")",
MatchOptions, RegexTimeout), MatchOptions, RegexTimeout),
// Batgirl Vol.2000 #57 (December, 2004) // Batgirl Vol.2000 #57 (December, 2004)
new Regex( new Regex(

View File

@ -9,4 +9,6 @@ export interface SeriesDetail {
chapters: Array<Chapter>; chapters: Array<Chapter>;
volumes: Array<Volume>; volumes: Array<Volume>;
storylineChapters: Array<Chapter>; storylineChapters: Array<Chapter>;
unreadCount: number;
totalCount: number;
} }

View File

@ -130,6 +130,10 @@ export class SeriesService {
})); }));
} }
isWantToRead(seriesId: number) {
return this.httpClient.get<boolean>(this.baseUrl + 'want-to-read?seriesId=' + seriesId, {responseType: 'text' as 'json'});
}
getOnDeck(libraryId: number = 0, pageNum?: number, itemsPerPage?: number, filter?: SeriesFilter) { getOnDeck(libraryId: number = 0, pageNum?: number, itemsPerPage?: number, filter?: SeriesFilter) {
const data = this.filterUtilitySerivce.createSeriesFilter(filter); const data = this.filterUtilitySerivce.createSeriesFilter(filter);

View File

@ -10,6 +10,7 @@ export interface ServerSettings {
bookmarksDirectory: string; bookmarksDirectory: string;
emailServiceUrl: string; emailServiceUrl: string;
convertBookmarkToWebP: boolean; convertBookmarkToWebP: boolean;
convertCoverToWebP: boolean;
enableSwaggerUi: boolean; enableSwaggerUi: boolean;
totalBackups: number; totalBackups: number;
totalLogs: number; totalLogs: number;

View File

@ -1,15 +1,29 @@
<div class="container-fluid"> <div class="container-fluid">
<form [formGroup]="settingsForm" *ngIf="serverSettings !== undefined"> <form [formGroup]="settingsForm" *ngIf="serverSettings !== undefined">
<div class="row g-0"> <div class="row g-0">
<p>WebP can drastically reduce space requirements for files. WebP is not supported on all browsers or versions. To learn if these settings are appropriate for your setup, visit <a href="https://caniuse.com/?search=webp" target="_blank" rel="noopener noreferrer">Can I Use</a>.</p>
<div class="col-md-6 col-sm-12 mb-3"> <div class="col-md-6 col-sm-12 mb-3">
<label for="bookmark-webp" class="form-label" aria-describedby="collection-info">Save Bookmarks as WebP</label>&nbsp;<i class="fa fa-info-circle" placement="right" [ngbTooltip]="convertBookmarkToWebPTooltip" role="button" tabindex="0"></i> <label for="bookmark-webp" class="form-label me-1" aria-describedby="settings-convertBookmarkToWebP-help">Save Bookmarks as WebP</label>
<ng-template #convertBookmarkToWebPTooltip>When saving bookmarks, covert them to WebP. WebP is not supported on Safari devices and will not render at all. WebP can drastically reduce space requirements for files.</ng-template> <i class="fa fa-info-circle" placement="right" [ngbTooltip]="convertBookmarkToWebPTooltip" role="button" tabindex="0"></i>
<ng-template #convertBookmarkToWebPTooltip>When saving bookmarks, covert them to WebP.</ng-template>
<span class="visually-hidden" id="settings-convertBookmarkToWebP-help"><ng-container [ngTemplateOutlet]="convertBookmarkToWebPTooltip"></ng-container></span> <span class="visually-hidden" id="settings-convertBookmarkToWebP-help"><ng-container [ngTemplateOutlet]="convertBookmarkToWebPTooltip"></ng-container></span>
<div class="form-check form-switch"> <div class="form-check form-switch">
<input id="bookmark-webp" type="checkbox" class="form-check-input" formControlName="convertBookmarkToWebP" role="switch"> <input id="bookmark-webp" type="checkbox" class="form-check-input" formControlName="convertBookmarkToWebP" role="switch">
<label for="bookmark-webp" class="form-check-label" aria-describedby="settings-convertBookmarkToWebP-help">{{settingsForm.get('convertBookmarkToWebP')?.value ? 'WebP' : 'Original' }}</label> <label for="bookmark-webp" class="form-check-label" aria-describedby="settings-convertBookmarkToWebP-help">{{settingsForm.get('convertBookmarkToWebP')?.value ? 'WebP' : 'Original' }}</label>
</div> </div>
</div> </div>
<div class="col-md-6 col-sm-12 mb-3">
<label for="cover-webp" class="form-label me-1" aria-describedby="settings-convertCoverToWebP-help">Save Covers as WebP</label>
<i class="fa fa-info-circle" placement="right" [ngbTooltip]="convertCoverToWebPTooltip" role="button" tabindex="0"></i>
<ng-template #convertCoverToWebPTooltip>When generating covers, covert them to WebP.</ng-template>
<span class="visually-hidden" id="settings-convertCoverToWebP-help"><ng-container [ngTemplateOutlet]="convertBookmarkToWebPTooltip"></ng-container></span>
<div class="form-check form-switch">
<input id="cover-webp" type="checkbox" class="form-check-input" formControlName="convertCoverToWebP" role="switch">
<label for="cover-webp" class="form-check-label" aria-describedby="settings-convertCoverToWebP-help">{{settingsForm.get('convertCoverToWebP')?.value ? 'WebP' : 'Original' }}</label>
</div>
</div>
</div> </div>
<div class="col-auto d-flex d-md-block justify-content-sm-center text-md-end"> <div class="col-auto d-flex d-md-block justify-content-sm-center text-md-end">

View File

@ -21,17 +21,20 @@ export class ManageMediaSettingsComponent implements OnInit {
this.settingsService.getServerSettings().pipe(take(1)).subscribe((settings: ServerSettings) => { this.settingsService.getServerSettings().pipe(take(1)).subscribe((settings: ServerSettings) => {
this.serverSettings = settings; this.serverSettings = settings;
this.settingsForm.addControl('convertBookmarkToWebP', new FormControl(this.serverSettings.convertBookmarkToWebP, [Validators.required])); this.settingsForm.addControl('convertBookmarkToWebP', new FormControl(this.serverSettings.convertBookmarkToWebP, [Validators.required]));
this.settingsForm.addControl('convertCoverToWebP', new FormControl(this.serverSettings.convertCoverToWebP, [Validators.required]));
}); });
} }
resetForm() { resetForm() {
this.settingsForm.get('convertBookmarkToWebP')?.setValue(this.serverSettings.convertBookmarkToWebP); this.settingsForm.get('convertBookmarkToWebP')?.setValue(this.serverSettings.convertBookmarkToWebP);
this.settingsForm.get('convertCoverToWebP')?.setValue(this.serverSettings.convertCoverToWebP);
this.settingsForm.markAsPristine(); this.settingsForm.markAsPristine();
} }
async saveSettings() { async saveSettings() {
const modelSettings = Object.assign({}, this.serverSettings); const modelSettings = Object.assign({}, this.serverSettings);
modelSettings.convertBookmarkToWebP = this.settingsForm.get('convertBookmarkToWebP')?.value; modelSettings.convertBookmarkToWebP = this.settingsForm.get('convertBookmarkToWebP')?.value;
modelSettings.convertCoverToWebP = this.settingsForm.get('convertCoverToWebP')?.value;
this.settingsService.updateServerSettings(modelSettings).pipe(take(1)).subscribe(async (settings: ServerSettings) => { this.settingsService.updateServerSettings(modelSettings).pipe(take(1)).subscribe(async (settings: ServerSettings) => {
this.serverSettings = settings; this.serverSettings = settings;

View File

@ -9,7 +9,6 @@
[isLoading]="loadingSeries" [isLoading]="loadingSeries"
[items]="series" [items]="series"
[trackByIdentity]="trackByIdentity" [trackByIdentity]="trackByIdentity"
[pagination]="pagination"
[filterSettings]="filterSettings" [filterSettings]="filterSettings"
[filterOpen]="filterOpen" [filterOpen]="filterOpen"
[jumpBarKeys]="jumpbarKeys" [jumpBarKeys]="jumpbarKeys"

View File

@ -1,4 +1,4 @@
import { Component, EventEmitter, HostListener, OnDestroy, OnInit } from '@angular/core'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, HostListener, OnDestroy, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser'; import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
@ -13,13 +13,15 @@ import { Series } from '../_models/series';
import { FilterEvent, SeriesFilter } from '../_models/series-filter'; import { FilterEvent, SeriesFilter } from '../_models/series-filter';
import { Action, ActionItem } from '../_services/action-factory.service'; import { Action, ActionItem } from '../_services/action-factory.service';
import { ActionService } from '../_services/action.service'; import { ActionService } from '../_services/action.service';
import { JumpbarService } from '../_services/jumpbar.service';
import { EVENTS, Message, MessageHubService } from '../_services/message-hub.service'; import { EVENTS, Message, MessageHubService } from '../_services/message-hub.service';
import { SeriesService } from '../_services/series.service'; import { SeriesService } from '../_services/series.service';
@Component({ @Component({
selector: 'app-all-series', selector: 'app-all-series',
templateUrl: './all-series.component.html', templateUrl: './all-series.component.html',
styleUrls: ['./all-series.component.scss'] styleUrls: ['./all-series.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class AllSeriesComponent implements OnInit, OnDestroy { export class AllSeriesComponent implements OnInit, OnDestroy {
@ -85,7 +87,8 @@ export class AllSeriesComponent implements OnInit, OnDestroy {
private titleService: Title, private actionService: ActionService, private titleService: Title, private actionService: ActionService,
public bulkSelectionService: BulkSelectionService, private hubService: MessageHubService, public bulkSelectionService: BulkSelectionService, private hubService: MessageHubService,
private utilityService: UtilityService, private route: ActivatedRoute, private utilityService: UtilityService, private route: ActivatedRoute,
private filterUtilityService: FilterUtilitiesService) { private filterUtilityService: FilterUtilitiesService, private jumpbarService: JumpbarService,
private readonly cdRef: ChangeDetectorRef) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false; this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.titleService.setTitle('Kavita - All Series'); this.titleService.setTitle('Kavita - All Series');
@ -93,6 +96,7 @@ export class AllSeriesComponent implements OnInit, OnDestroy {
this.pagination = this.filterUtilityService.pagination(this.route.snapshot); this.pagination = this.filterUtilityService.pagination(this.route.snapshot);
[this.filterSettings.presets, this.filterSettings.openByDefault] = this.filterUtilityService.filterPresetsFromUrl(this.route.snapshot); [this.filterSettings.presets, this.filterSettings.openByDefault] = this.filterUtilityService.filterPresetsFromUrl(this.route.snapshot);
this.filterActiveCheck = this.filterUtilityService.createSeriesFilter(); this.filterActiveCheck = this.filterUtilityService.createSeriesFilter();
this.cdRef.markForCheck();
} }
ngOnInit(): void { ngOnInit(): void {
@ -131,33 +135,14 @@ export class AllSeriesComponent implements OnInit, OnDestroy {
loadPage() { loadPage() {
this.filterActive = !this.utilityService.deepEqual(this.filter, this.filterActiveCheck); this.filterActive = !this.utilityService.deepEqual(this.filter, this.filterActiveCheck);
this.loadingSeries = true;
this.cdRef.markForCheck();
this.seriesService.getAllSeries(undefined, undefined, this.filter).pipe(take(1)).subscribe(series => { this.seriesService.getAllSeries(undefined, undefined, this.filter).pipe(take(1)).subscribe(series => {
this.series = series.result; this.series = series.result;
const keys: {[key: string]: number} = {}; this.jumpbarKeys = this.jumpbarService.getJumpKeys(this.series, (s: Series) => s.name);
series.result.forEach(s => {
let ch = s.name.charAt(0);
if (/\d|\#|!|%|@|\(|\)|\^|\*/g.test(ch)) {
ch = '#';
}
if (!keys.hasOwnProperty(ch)) {
keys[ch] = 0;
}
keys[ch] += 1;
});
this.jumpbarKeys = Object.keys(keys).map(k => {
return {
key: k,
size: keys[k],
title: k.toUpperCase()
}
}).sort((a, b) => {
if (a.key < b.key) return -1;
if (a.key > b.key) return 1;
return 0;
});
this.pagination = series.pagination; this.pagination = series.pagination;
this.loadingSeries = false; this.loadingSeries = false;
window.scrollTo(0, 0); this.cdRef.markForCheck();
}); });
} }

View File

@ -19,8 +19,8 @@
<ng-container *ngIf="totalPages > 0"> <ng-container *ngIf="totalPages > 0">
<div class="col-auto mb-2"> <div class="col-auto mb-2">
<app-icon-and-title label="Print Length" [clickable]="false" fontClasses="fa-regular fa-file-lines" title="Pages"> <app-icon-and-title label="Length" [clickable]="false" fontClasses="fa-regular fa-file-lines" title="Pages">
{{totalPages | number:''}} Pages {{totalPages | compactNumber}} Pages
</app-icon-and-title> </app-icon-and-title>
</div> </div>
<div class="vr d-none d-lg-block m-2"></div> <div class="vr d-none d-lg-block m-2"></div>

View File

@ -71,8 +71,8 @@
</ng-container> </ng-container>
<ng-template #showPages> <ng-template #showPages>
<div class="d-none d-md-block col-lg-1 col-md-4 col-sm-4 col-4 mb-2"> <div class="d-none d-md-block col-lg-1 col-md-4 col-sm-4 col-4 mb-2">
<app-icon-and-title label="Print Length" [clickable]="false" fontClasses="fa-regular fa-file-lines"> <app-icon-and-title label="Length" [clickable]="false" fontClasses="fa-regular fa-file-lines">
{{series.pages | number:''}} Pages {{series.pages | compactNumber}} Pages
</app-icon-and-title> </app-icon-and-title>
</div> </div>
<div class="vr d-none d-lg-block m-2"></div> <div class="vr d-none d-lg-block m-2"></div>

View File

@ -328,10 +328,10 @@
<div class="col-md-2 me-3"> <div class="col-md-2 me-3">
<form [formGroup]="releaseYearRange" class="d-flex justify-content-between"> <form [formGroup]="releaseYearRange" class="d-flex justify-content-between">
<div class="mb-3"> <div class="mb-3">
<label for="release-year-min" class="form-label">Release Year</label> <label for="release-year-min" class="form-label">Release</label>
<input type="text" id="release-year-min" formControlName="min" class="form-control" style="width: 62px" placeholder="Min"> <input type="text" id="release-year-min" formControlName="min" class="form-control" style="width: 62px" placeholder="Min">
</div> </div>
<div style="margin-top: 37px !important; width: 49px;"> <div style="margin-top: 37px !important;">
<i class="fa-solid fa-minus" aria-hidden="true"></i> <i class="fa-solid fa-minus" aria-hidden="true"></i>
</div> </div>
<div class="mb-3" style="margin-top: 0.5rem"> <div class="mb-3" style="margin-top: 0.5rem">

View File

@ -3,7 +3,8 @@ import { Pipe, PipeTransform } from '@angular/core';
const formatter = new Intl.NumberFormat('en-GB', { const formatter = new Intl.NumberFormat('en-GB', {
//@ts-ignore //@ts-ignore
notation: 'compact' // https://github.com/microsoft/TypeScript/issues/36533 notation: 'compact', // https://github.com/microsoft/TypeScript/issues/36533
maximumSignificantDigits: 3
}); });
@Pipe({ @Pipe({

View File

@ -59,8 +59,13 @@
<div [ngStyle]="{'height': ScrollingBlockHeight}" class="main-container container-fluid pt-2" *ngIf="series !== undefined" #scrollingBlock> <div [ngStyle]="{'height': ScrollingBlockHeight}" class="main-container container-fluid pt-2" *ngIf="series !== undefined" #scrollingBlock>
<div class="row mb-3 info-container"> <div class="row mb-3 info-container">
<div class="image-container col-4 col-sm-6 col-md-4 col-lg-4 col-xl-2 col-xxl-2 d-none d-sm-block"> <div class="image-container col-4 col-sm-6 col-md-4 col-lg-4 col-xl-2 col-xxl-2 d-none d-sm-block">
<div class="to-read-counter" *ngIf="unreadCount > 0 && unreadCount !== totalCount">
<app-tag-badge [selectionMode]="TagBadgeCursor.NotAllowed" fillStyle="filled">{{unreadCount}}</app-tag-badge>
</div>
<app-image height="100%" maxHeight="400px" objectFit="contain" background="none" [imageUrl]="seriesImage"></app-image> <app-image height="100%" maxHeight="400px" objectFit="contain" background="none" [imageUrl]="seriesImage"></app-image>
<!-- NOTE: We can put continue point here as Vol X Ch Y or just Ch Y or Book Z ?--> <div class="under-image mt-1" *ngIf="hasReadingProgress && currentlyReadingChapter && !currentlyReadingChapter.isSpecial">
From {{ContinuePointTitle}}
</div>
</div> </div>
<div class="col-xlg-10 col-lg-8 col-md-8 col-xs-8 col-sm-6 mt-2"> <div class="col-xlg-10 col-lg-8 col-md-8 col-xs-8 col-sm-6 mt-2">
<div class="row g-0"> <div class="row g-0">
@ -72,8 +77,15 @@
<span class="d-none d-sm-inline-block">{{(hasReadingProgress) ? 'Continue' : 'Read'}}</span> <span class="d-none d-sm-inline-block">{{(hasReadingProgress) ? 'Continue' : 'Read'}}</span>
</button> </button>
</div> </div>
<div class="col-auto ms-2">
<button class="btn btn-secondary" (click)="toggleWantToRead()" placement="top" [closeDelay]="100000" ngbTooltip="{{isWantToRead ? 'Remove from' : 'Add to'}} Want to Read">
<span>
<i class="fa-{{isWantToRead ? 'solid' : 'regular'}} fa-star" aria-hidden="true"></i>
</span>
</button>
</div>
<div class="col-auto ms-2" *ngIf="isAdmin"> <div class="col-auto ms-2" *ngIf="isAdmin">
<button class="btn btn-secondary" (click)="openEditSeriesModal()" title="Edit Series information"> <button class="btn btn-secondary" (click)="openEditSeriesModal()" placement="top" ngbTooltip="Edit Series information">
<span> <span>
<i class="fa fa-pen" aria-hidden="true"></i> <i class="fa fa-pen" aria-hidden="true"></i>
</span> </span>

View File

@ -2,6 +2,29 @@
font-style: italic; font-style: italic;
} }
.want-to-read-star {
//position: absolute;
//top: 15px;
//left: 20px;
//color: var(--primary-color);
}
.to-read-counter {
position: absolute;
// top: 15px;
// right: 20px;
top: 15px;
left: 20px;
}
.under-image {
background-color: var(--breadcrumb-bg-color);
color: white;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
text-align: center;
}
.rating-star { .rating-star {
margin-top: 2px; margin-top: 2px;
font-size: 1.5rem; font-size: 1.5rem;

View File

@ -42,6 +42,7 @@ import { User } from '../_models/user';
import { ScrollService } from '../_services/scroll.service'; import { ScrollService } from '../_services/scroll.service';
import { DeviceService } from '../_services/device.service'; import { DeviceService } from '../_services/device.service';
import { Device } from '../_models/device/device'; import { Device } from '../_models/device/device';
import { ThisReceiver } from '@angular/compiler';
interface RelatedSeris { interface RelatedSeris {
series: Series; series: Series;
@ -107,6 +108,9 @@ export class SeriesDetailComponent implements OnInit, OnDestroy, AfterContentChe
libraryType: LibraryType = LibraryType.Manga; libraryType: LibraryType = LibraryType.Manga;
seriesMetadata: SeriesMetadata | null = null; seriesMetadata: SeriesMetadata | null = null;
readingLists: Array<ReadingList> = []; readingLists: Array<ReadingList> = [];
isWantToRead: boolean = false;
unreadCount: number = 0;
totalCount: number = 0;
/** /**
* Poster image for the Series * Poster image for the Series
*/ */
@ -233,6 +237,26 @@ export class SeriesDetailComponent implements OnInit, OnDestroy, AfterContentChe
return 'calc(var(--vh)*100 - ' + totalHeight + 'px)'; return 'calc(var(--vh)*100 - ' + totalHeight + 'px)';
} }
get ContinuePointTitle() {
if (this.currentlyReadingChapter === undefined || !this.hasReadingProgress) return '';
if (!this.currentlyReadingChapter.isSpecial) {
const vol = this.volumes.filter(v => v.id === this.currentlyReadingChapter?.volumeId);
// This is a lone chapter
if (vol.length === 0) {
return 'Ch ' + this.currentlyReadingChapter.number;
}
if (this.currentlyReadingChapter.number === "0") {
return 'Vol ' + vol[0].number;
}
return 'Vol ' + vol[0].number + ' Ch ' + this.currentlyReadingChapter.number;
}
return this.currentlyReadingChapter.title;
}
constructor(private route: ActivatedRoute, private seriesService: SeriesService, constructor(private route: ActivatedRoute, private seriesService: SeriesService,
private router: Router, public bulkSelectionService: BulkSelectionService, private router: Router, public bulkSelectionService: BulkSelectionService,
private modalService: NgbModal, public readerService: ReaderService, private modalService: NgbModal, public readerService: ReaderService,
@ -454,6 +478,11 @@ export class SeriesDetailComponent implements OnInit, OnDestroy, AfterContentChe
this.changeDetectionRef.markForCheck(); this.changeDetectionRef.markForCheck();
}); });
this.seriesService.isWantToRead(seriesId).subscribe(isWantToRead => {
this.isWantToRead = isWantToRead;
this.changeDetectionRef.markForCheck();
});
this.readingListService.getReadingListsForSeries(seriesId).subscribe(lists => { this.readingListService.getReadingListsForSeries(seriesId).subscribe(lists => {
this.readingLists = lists; this.readingLists = lists;
this.changeDetectionRef.markForCheck(); this.changeDetectionRef.markForCheck();
@ -508,6 +537,9 @@ export class SeriesDetailComponent implements OnInit, OnDestroy, AfterContentChe
return of(null); return of(null);
})).subscribe(detail => { })).subscribe(detail => {
if (detail == null) return; if (detail == null) return;
this.unreadCount = detail.unreadCount;
this.totalCount = detail.totalCount;
this.hasSpecials = detail.specials.length > 0; this.hasSpecials = detail.specials.length > 0;
this.specials = detail.specials; this.specials = detail.specials;
@ -761,4 +793,15 @@ export class SeriesDetailComponent implements OnInit, OnDestroy, AfterContentChe
// this.filter.sortOptions.isAscending = this.isAscendingSort; // this.filter.sortOptions.isAscending = this.isAscendingSort;
} }
toggleWantToRead() {
if (this.isWantToRead) {
this.actionService.addMultipleSeriesToWantToReadList([this.series.id]);
} else {
this.actionService.removeMultipleSeriesFromWantToReadList([this.series.id]);
}
this.isWantToRead = !this.isWantToRead;
this.changeDetectionRef.markForCheck();
}
} }

View File

@ -48,7 +48,6 @@
<app-badge-expander [items]="readingLists"> <app-badge-expander [items]="readingLists">
<ng-template #badgeExpanderItem let-item let-position="idx"> <ng-template #badgeExpanderItem let-item let-position="idx">
<app-tag-badge a11y-click="13,32" class="col-auto" routerLink="/lists/{{item.id}}" [selectionMode]="TagBadgeCursor.Clickable"> <app-tag-badge a11y-click="13,32" class="col-auto" routerLink="/lists/{{item.id}}" [selectionMode]="TagBadgeCursor.Clickable">
<!-- TODO: Build a promoted badge code -->
<span *ngIf="item.promoted"> <span *ngIf="item.promoted">
<i class="fa fa-angle-double-up" aria-hidden="true"></i>&nbsp; <i class="fa fa-angle-double-up" aria-hidden="true"></i>&nbsp;
<span class="visually-hidden">(promoted)</span> <span class="visually-hidden">(promoted)</span>

View File

@ -18,7 +18,7 @@
<input id="email" aria-describedby="email-help" <input id="email" aria-describedby="email-help"
class="form-control" formControlName="email" type="email" class="form-control" formControlName="email" type="email"
placeholder="@kindle.com" [class.is-invalid]="settingsForm.get('email')?.invalid && settingsForm.get('email')?.touched"> placeholder="id@kindle.com" [class.is-invalid]="settingsForm.get('email')?.invalid && settingsForm.get('email')?.touched">
<ng-container *ngIf="settingsForm.get('email')?.errors as errors"> <ng-container *ngIf="settingsForm.get('email')?.errors as errors">
<p class="invalid-feedback" *ngIf="errors.email"> <p class="invalid-feedback" *ngIf="errors.email">
This must be a valid email This must be a valid email

View File

@ -61,7 +61,7 @@ export class EditDeviceComponent implements OnInit, OnChanges, OnDestroy {
addDevice() { addDevice() {
if (this.device !== undefined) { if (this.device !== undefined) {
this.deviceService.updateDevice(this.device.id, this.settingsForm.value.name, this.settingsForm.value.platform, this.settingsForm.value.email).subscribe(() => { this.deviceService.updateDevice(this.device.id, this.settingsForm.value.name, parseInt(this.settingsForm.value.platform, 10), this.settingsForm.value.email).subscribe(() => {
this.settingsForm.reset(); this.settingsForm.reset();
this.toastr.success('Device updated'); this.toastr.success('Device updated');
this.cdRef.markForCheck(); this.cdRef.markForCheck();
@ -70,7 +70,7 @@ export class EditDeviceComponent implements OnInit, OnChanges, OnDestroy {
return; return;
} }
this.deviceService.createDevice(this.settingsForm.value.name, this.settingsForm.value.platform, this.settingsForm.value.email).subscribe(() => { this.deviceService.createDevice(this.settingsForm.value.name, parseInt(this.settingsForm.value.platform, 10), this.settingsForm.value.email).subscribe(() => {
this.settingsForm.reset(); this.settingsForm.reset();
this.toastr.success('Device created'); this.toastr.success('Device created');
this.cdRef.markForCheck(); this.cdRef.markForCheck();