Merge branch 'develop' of https://github.com/Kareadita/Kavita into work/scrobble
This commit is contained in:
commit
19be1193a1
202 changed files with 12917 additions and 2479 deletions
|
|
@ -26,5 +26,10 @@
|
||||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
</Content>
|
</Content>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="Data\AesopsFables.epub">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
BIN
API.Benchmark/Data/AesopsFables.epub
Normal file
BIN
API.Benchmark/Data/AesopsFables.epub
Normal file
Binary file not shown.
41
API.Benchmark/KoreaderHashBenchmark.cs
Normal file
41
API.Benchmark/KoreaderHashBenchmark.cs
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
using API.Helpers.Builders;
|
||||||
|
using BenchmarkDotNet.Attributes;
|
||||||
|
using BenchmarkDotNet.Order;
|
||||||
|
using System;
|
||||||
|
using API.Entities.Enums;
|
||||||
|
|
||||||
|
namespace API.Benchmark
|
||||||
|
{
|
||||||
|
[StopOnFirstError]
|
||||||
|
[MemoryDiagnoser]
|
||||||
|
[RankColumn]
|
||||||
|
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
|
||||||
|
[SimpleJob(launchCount: 1, warmupCount: 5, invocationCount: 20)]
|
||||||
|
public class KoreaderHashBenchmark
|
||||||
|
{
|
||||||
|
private const string sourceEpub = "./Data/AesopsFables.epub";
|
||||||
|
|
||||||
|
[Benchmark(Baseline = true)]
|
||||||
|
public void TestBuildManga_baseline()
|
||||||
|
{
|
||||||
|
var file = new MangaFileBuilder(sourceEpub, MangaFormat.Epub)
|
||||||
|
.Build();
|
||||||
|
if (file == null)
|
||||||
|
{
|
||||||
|
throw new Exception("Failed to build manga file");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Benchmark]
|
||||||
|
public void TestBuildManga_withHash()
|
||||||
|
{
|
||||||
|
var file = new MangaFileBuilder(sourceEpub, MangaFormat.Epub)
|
||||||
|
.WithHash()
|
||||||
|
.Build();
|
||||||
|
if (file == null)
|
||||||
|
{
|
||||||
|
throw new Exception("Failed to build manga file");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -36,4 +36,10 @@
|
||||||
<None Remove="Extensions\Test Data\modified on run.txt" />
|
<None Remove="Extensions\Test Data\modified on run.txt" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="Data\AesopsFables.epub">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|
|
||||||
BIN
API.Tests/Data/AesopsFables.epub
Normal file
BIN
API.Tests/Data/AesopsFables.epub
Normal file
Binary file not shown.
60
API.Tests/Helpers/KoreaderHelperTests.cs
Normal file
60
API.Tests/Helpers/KoreaderHelperTests.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
using API.DTOs.Koreader;
|
||||||
|
using API.DTOs.Progress;
|
||||||
|
using API.Helpers;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace API.Tests.Helpers;
|
||||||
|
|
||||||
|
|
||||||
|
public class KoreaderHelperTests
|
||||||
|
{
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/body/DocFragment[11]/body/div/a", 10, null)]
|
||||||
|
[InlineData("/body/DocFragment[1]/body/div/p[40]", 0, 40)]
|
||||||
|
[InlineData("/body/DocFragment[8]/body/div/p[28]/text().264", 7, 28)]
|
||||||
|
public void GetEpubPositionDto(string koreaderPosition, int page, int? pNumber)
|
||||||
|
{
|
||||||
|
var expected = EmptyProgressDto();
|
||||||
|
expected.BookScrollId = pNumber.HasValue ? $"//html[1]/BODY/APP-ROOT[1]/DIV[1]/DIV[1]/DIV[1]/APP-BOOK-READER[1]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/P[{pNumber}]" : null;
|
||||||
|
expected.PageNum = page;
|
||||||
|
var actual = EmptyProgressDto();
|
||||||
|
|
||||||
|
KoreaderHelper.UpdateProgressDto(actual, koreaderPosition);
|
||||||
|
Assert.Equal(expected.BookScrollId, actual.BookScrollId);
|
||||||
|
Assert.Equal(expected.PageNum, actual.PageNum);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("//html[1]/BODY/APP-ROOT[1]/DIV[1]/DIV[1]/DIV[1]/APP-BOOK-READER[1]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/P[20]", 5, "/body/DocFragment[6]/body/div/p[20]")]
|
||||||
|
[InlineData(null, 10, "/body/DocFragment[11]/body/div/a")]
|
||||||
|
public void GetKoreaderPosition(string scrollId, int page, string koreaderPosition)
|
||||||
|
{
|
||||||
|
var given = EmptyProgressDto();
|
||||||
|
given.BookScrollId = scrollId;
|
||||||
|
given.PageNum = page;
|
||||||
|
|
||||||
|
Assert.Equal(koreaderPosition, KoreaderHelper.GetKoreaderPosition(given));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("./Data/AesopsFables.epub", "8795ACA4BF264B57C1EEDF06A0CEE688")]
|
||||||
|
public void GetKoreaderHash(string filePath, string hash)
|
||||||
|
{
|
||||||
|
Assert.Equal(KoreaderHelper.HashContents(filePath), hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ProgressDto EmptyProgressDto()
|
||||||
|
{
|
||||||
|
return new ProgressDto
|
||||||
|
{
|
||||||
|
ChapterId = 0,
|
||||||
|
PageNum = 0,
|
||||||
|
VolumeId = 0,
|
||||||
|
SeriesId = 0,
|
||||||
|
LibraryId = 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -161,10 +161,10 @@ public class ImageServiceTests
|
||||||
|
|
||||||
private static void GenerateColorImage(string hexColor, string outputPath)
|
private static void GenerateColorImage(string hexColor, string outputPath)
|
||||||
{
|
{
|
||||||
var color = ImageService.HexToRgb(hexColor);
|
var (r, g, b) = ImageService.HexToRgb(hexColor);
|
||||||
using var colorImage = Image.Black(200, 100);
|
using var blackImage = Image.Black(200, 100);
|
||||||
using var output = colorImage + new[] { color.R / 255.0, color.G / 255.0, color.B / 255.0 };
|
using var colorImage = blackImage.NewFromImage(r, g, b);
|
||||||
output.WriteToFile(outputPath);
|
colorImage.WriteToFile(outputPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void GenerateHtmlFileForColorScape()
|
private void GenerateHtmlFileForColorScape()
|
||||||
|
|
|
||||||
|
|
@ -97,9 +97,9 @@
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Filters" Version="8.0.3" />
|
||||||
|
<PackageReference Include="System.Drawing.Common" Version="9.0.5" />
|
||||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.9.0" />
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.9.0" />
|
||||||
<PackageReference Include="System.IO.Abstractions" Version="22.0.14" />
|
<PackageReference Include="System.IO.Abstractions" Version="22.0.14" />
|
||||||
<PackageReference Include="System.Drawing.Common" Version="9.0.4" />
|
|
||||||
<PackageReference Include="VersOne.Epub" Version="3.3.4" />
|
<PackageReference Include="VersOne.Epub" Version="3.3.4" />
|
||||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
|
||||||
118
API/Controllers/KoreaderController.cs
Normal file
118
API/Controllers/KoreaderController.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using API.Data;
|
||||||
|
using API.Data.Repositories;
|
||||||
|
using API.DTOs.Koreader;
|
||||||
|
using API.Entities;
|
||||||
|
using API.Services;
|
||||||
|
using Kavita.Common;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using static System.Net.WebRequestMethods;
|
||||||
|
|
||||||
|
namespace API.Controllers;
|
||||||
|
#nullable enable
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The endpoint to interface with Koreader's Progress Sync plugin.
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Koreader uses a different form of authentication. It stores the username and password in headers.
|
||||||
|
/// https://github.com/koreader/koreader/blob/master/plugins/kosync.koplugin/KOSyncClient.lua
|
||||||
|
/// </remarks>
|
||||||
|
[AllowAnonymous]
|
||||||
|
public class KoreaderController : BaseApiController
|
||||||
|
{
|
||||||
|
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
private readonly ILocalizationService _localizationService;
|
||||||
|
private readonly IKoreaderService _koreaderService;
|
||||||
|
private readonly ILogger<KoreaderController> _logger;
|
||||||
|
|
||||||
|
public KoreaderController(IUnitOfWork unitOfWork, ILocalizationService localizationService,
|
||||||
|
IKoreaderService koreaderService, ILogger<KoreaderController> logger)
|
||||||
|
{
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_localizationService = localizationService;
|
||||||
|
_koreaderService = koreaderService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// We won't allow users to be created from Koreader. Rather, they
|
||||||
|
// must already have an account.
|
||||||
|
/*
|
||||||
|
[HttpPost("/users/create")]
|
||||||
|
public IActionResult CreateUser(CreateUserRequest request)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
[HttpGet("{apiKey}/users/auth")]
|
||||||
|
public async Task<IActionResult> Authenticate(string apiKey)
|
||||||
|
{
|
||||||
|
var userId = await GetUserId(apiKey);
|
||||||
|
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId);
|
||||||
|
if (user == null) return Unauthorized();
|
||||||
|
|
||||||
|
return Ok(new { username = user.UserName });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Syncs book progress with Kavita. Will attempt to save the underlying reader position if possible.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiKey"></param>
|
||||||
|
/// <param name="request"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPut("{apiKey}/syncs/progress")]
|
||||||
|
public async Task<ActionResult<KoreaderProgressUpdateDto>> UpdateProgress(string apiKey, KoreaderBookDto request)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var userId = await GetUserId(apiKey);
|
||||||
|
await _koreaderService.SaveProgress(request, userId);
|
||||||
|
|
||||||
|
return Ok(new KoreaderProgressUpdateDto{ Document = request.Document, Timestamp = DateTime.UtcNow });
|
||||||
|
}
|
||||||
|
catch (KavitaException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets book progress from Kavita, if not found will return a 400
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="apiKey"></param>
|
||||||
|
/// <param name="ebookHash"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpGet("{apiKey}/syncs/progress/{ebookHash}")]
|
||||||
|
public async Task<ActionResult<KoreaderBookDto>> GetProgress(string apiKey, string ebookHash)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var userId = await GetUserId(apiKey);
|
||||||
|
var response = await _koreaderService.GetProgress(ebookHash, userId);
|
||||||
|
_logger.LogDebug("Koreader response progress: {Progress}", response.Progress);
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
catch (KavitaException ex)
|
||||||
|
{
|
||||||
|
return BadRequest(ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<int> GetUserId(string apiKey)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await _unitOfWork.UserRepository.GetUserIdByApiKeyAsync(apiKey);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
throw new KavitaException(await _localizationService.Get("en", "user-doesnt-exist"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,8 +6,10 @@ using System.Threading.Tasks;
|
||||||
using API.Constants;
|
using API.Constants;
|
||||||
using API.Data;
|
using API.Data;
|
||||||
using API.Data.Repositories;
|
using API.Data.Repositories;
|
||||||
|
using API.DTOs;
|
||||||
using API.DTOs.Filtering;
|
using API.DTOs.Filtering;
|
||||||
using API.DTOs.Metadata;
|
using API.DTOs.Metadata;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
using API.DTOs.Person;
|
using API.DTOs.Person;
|
||||||
using API.DTOs.Recommendation;
|
using API.DTOs.Recommendation;
|
||||||
using API.DTOs.SeriesDetail;
|
using API.DTOs.SeriesDetail;
|
||||||
|
|
@ -46,6 +48,22 @@ public class MetadataController(IUnitOfWork unitOfWork, ILocalizationService loc
|
||||||
return Ok(await unitOfWork.GenreRepository.GetAllGenreDtosForLibrariesAsync(User.GetUserId(), ids, context));
|
return Ok(await unitOfWork.GenreRepository.GetAllGenreDtosForLibrariesAsync(User.GetUserId(), ids, context));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a list of Genres with counts for counts when Genre is on Series/Chapter
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("genres-with-counts")]
|
||||||
|
[ResponseCache(CacheProfileName = ResponseCacheProfiles.FiveMinute)]
|
||||||
|
public async Task<ActionResult<PagedList<BrowseGenreDto>>> GetBrowseGenres(UserParams? userParams = null)
|
||||||
|
{
|
||||||
|
userParams ??= UserParams.Default;
|
||||||
|
|
||||||
|
var list = await unitOfWork.GenreRepository.GetBrowseableGenre(User.GetUserId(), userParams);
|
||||||
|
Response.AddPaginationHeader(list.CurrentPage, list.PageSize, list.TotalCount, list.TotalPages);
|
||||||
|
|
||||||
|
return Ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Fetches people from the instance by role
|
/// Fetches people from the instance by role
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
@ -95,6 +113,22 @@ public class MetadataController(IUnitOfWork unitOfWork, ILocalizationService loc
|
||||||
return Ok(await unitOfWork.TagRepository.GetAllTagDtosForLibrariesAsync(User.GetUserId()));
|
return Ok(await unitOfWork.TagRepository.GetAllTagDtosForLibrariesAsync(User.GetUserId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a list of Tags with counts for counts when Tag is on Series/Chapter
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost("tags-with-counts")]
|
||||||
|
[ResponseCache(CacheProfileName = ResponseCacheProfiles.FiveMinute)]
|
||||||
|
public async Task<ActionResult<PagedList<BrowseTagDto>>> GetBrowseTags(UserParams? userParams = null)
|
||||||
|
{
|
||||||
|
userParams ??= UserParams.Default;
|
||||||
|
|
||||||
|
var list = await unitOfWork.TagRepository.GetBrowseableTag(User.GetUserId(), userParams);
|
||||||
|
Response.AddPaginationHeader(list.CurrentPage, list.PageSize, list.TotalCount, list.TotalPages);
|
||||||
|
|
||||||
|
return Ok(list);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Fetches all age ratings from the instance
|
/// Fetches all age ratings from the instance
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,9 @@ using System.Threading.Tasks;
|
||||||
using API.Data;
|
using API.Data;
|
||||||
using API.Data.Repositories;
|
using API.Data.Repositories;
|
||||||
using API.DTOs;
|
using API.DTOs;
|
||||||
|
using API.DTOs.Filtering.v2;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
|
using API.DTOs.Metadata.Browse.Requests;
|
||||||
using API.DTOs.Person;
|
using API.DTOs.Person;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
using API.Extensions;
|
using API.Extensions;
|
||||||
|
|
@ -77,11 +80,13 @@ public class PersonController : BaseApiController
|
||||||
/// <param name="userParams"></param>
|
/// <param name="userParams"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("all")]
|
[HttpPost("all")]
|
||||||
public async Task<ActionResult<PagedList<BrowsePersonDto>>> GetAuthorsForBrowse([FromQuery] UserParams? userParams)
|
public async Task<ActionResult<PagedList<BrowsePersonDto>>> GetPeopleForBrowse(BrowsePersonFilterDto filter, [FromQuery] UserParams? userParams)
|
||||||
{
|
{
|
||||||
userParams ??= UserParams.Default;
|
userParams ??= UserParams.Default;
|
||||||
var list = await _unitOfWork.PersonRepository.GetAllWritersAndSeriesCount(User.GetUserId(), userParams);
|
|
||||||
|
var list = await _unitOfWork.PersonRepository.GetBrowsePersonDtos(User.GetUserId(), filter, userParams);
|
||||||
Response.AddPaginationHeader(list.CurrentPage, list.PageSize, list.TotalCount, list.TotalPages);
|
Response.AddPaginationHeader(list.CurrentPage, list.PageSize, list.TotalCount, list.TotalPages);
|
||||||
|
|
||||||
return Ok(list);
|
return Ok(list);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -112,6 +117,7 @@ public class PersonController : BaseApiController
|
||||||
|
|
||||||
|
|
||||||
person.Name = dto.Name?.Trim();
|
person.Name = dto.Name?.Trim();
|
||||||
|
person.NormalizedName = person.Name.ToNormalized();
|
||||||
person.Description = dto.Description ?? string.Empty;
|
person.Description = dto.Description ?? string.Empty;
|
||||||
person.CoverImageLocked = dto.CoverImageLocked;
|
person.CoverImageLocked = dto.CoverImageLocked;
|
||||||
|
|
||||||
|
|
|
||||||
8
API/DTOs/Filtering/PersonSortField.cs
Normal file
8
API/DTOs/Filtering/PersonSortField.cs
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
namespace API.DTOs.Filtering;
|
||||||
|
|
||||||
|
public enum PersonSortField
|
||||||
|
{
|
||||||
|
Name = 1,
|
||||||
|
SeriesCount = 2,
|
||||||
|
ChapterCount = 3
|
||||||
|
}
|
||||||
|
|
@ -8,3 +8,12 @@ public sealed record SortOptions
|
||||||
public SortField SortField { get; set; }
|
public SortField SortField { get; set; }
|
||||||
public bool IsAscending { get; set; } = true;
|
public bool IsAscending { get; set; } = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// All Sorting Options for a query related to Person Entity
|
||||||
|
/// </summary>
|
||||||
|
public sealed record PersonSortOptions
|
||||||
|
{
|
||||||
|
public PersonSortField SortField { get; set; }
|
||||||
|
public bool IsAscending { get; set; } = true;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -56,5 +56,12 @@ public enum FilterField
|
||||||
/// Last time User Read
|
/// Last time User Read
|
||||||
/// </summary>
|
/// </summary>
|
||||||
ReadLast = 32,
|
ReadLast = 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum PersonFilterField
|
||||||
|
{
|
||||||
|
Role = 1,
|
||||||
|
Name = 2,
|
||||||
|
SeriesCount = 3,
|
||||||
|
ChapterCount = 4,
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
namespace API.DTOs.Filtering.v2;
|
using API.DTOs.Metadata.Browse.Requests;
|
||||||
|
|
||||||
|
namespace API.DTOs.Filtering.v2;
|
||||||
|
|
||||||
public sealed record FilterStatementDto
|
public sealed record FilterStatementDto
|
||||||
{
|
{
|
||||||
|
|
@ -6,3 +8,10 @@ public sealed record FilterStatementDto
|
||||||
public FilterField Field { get; set; }
|
public FilterField Field { get; set; }
|
||||||
public string Value { get; set; }
|
public string Value { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public sealed record PersonFilterStatementDto
|
||||||
|
{
|
||||||
|
public FilterComparison Comparison { get; set; }
|
||||||
|
public PersonFilterField Field { get; set; }
|
||||||
|
public string Value { get; set; }
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ public sealed record FilterV2Dto
|
||||||
/// The name of the filter
|
/// The name of the filter
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string? Name { get; set; }
|
public string? Name { get; set; }
|
||||||
public ICollection<FilterStatementDto> Statements { get; set; } = new List<FilterStatementDto>();
|
public ICollection<FilterStatementDto> Statements { get; set; } = [];
|
||||||
public FilterCombination Combination { get; set; } = FilterCombination.And;
|
public FilterCombination Combination { get; set; } = FilterCombination.And;
|
||||||
public SortOptions? SortOptions { get; set; }
|
public SortOptions? SortOptions { get; set; }
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,5 +15,9 @@ public enum MatchStateOption
|
||||||
public sealed record ManageMatchFilterDto
|
public sealed record ManageMatchFilterDto
|
||||||
{
|
{
|
||||||
public MatchStateOption MatchStateOption { get; set; } = MatchStateOption.All;
|
public MatchStateOption MatchStateOption { get; set; } = MatchStateOption.All;
|
||||||
|
/// <summary>
|
||||||
|
/// Library Type in int form. -1 indicates to ignore the field.
|
||||||
|
/// </summary>
|
||||||
|
public int LibraryType { get; set; } = -1;
|
||||||
public string SearchTerm { get; set; } = string.Empty;
|
public string SearchTerm { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
33
API/DTOs/Koreader/KoreaderBookDto.cs
Normal file
33
API/DTOs/Koreader/KoreaderBookDto.cs
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
using API.DTOs.Progress;
|
||||||
|
|
||||||
|
namespace API.DTOs.Koreader;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// This is the interface for receiving and sending updates to Koreader. The only fields
|
||||||
|
/// that are actually used are the Document and Progress fields.
|
||||||
|
/// </summary>
|
||||||
|
public class KoreaderBookDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// This is the Koreader hash of the book. It is used to identify the book.
|
||||||
|
/// </summary>
|
||||||
|
public string Document { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// A randomly generated id from the koreader device. Only used to maintain the Koreader interface.
|
||||||
|
/// </summary>
|
||||||
|
public string Device_id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// The Koreader device name. Only used to maintain the Koreader interface.
|
||||||
|
/// </summary>
|
||||||
|
public string Device { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Percent progress of the book. Only used to maintain the Koreader interface.
|
||||||
|
/// </summary>
|
||||||
|
public float Percentage { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// An XPath string read by Koreader to determine the location within the epub.
|
||||||
|
/// Essentially, it is Koreader's equivalent to ProgressDto.BookScrollId.
|
||||||
|
/// </summary>
|
||||||
|
/// <seealso cref="ProgressDto.BookScrollId"/>
|
||||||
|
public string Progress { get; set; }
|
||||||
|
}
|
||||||
15
API/DTOs/Koreader/KoreaderProgressUpdateDto.cs
Normal file
15
API/DTOs/Koreader/KoreaderProgressUpdateDto.cs
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace API.DTOs.Koreader;
|
||||||
|
|
||||||
|
public class KoreaderProgressUpdateDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// This is the Koreader hash of the book. It is used to identify the book.
|
||||||
|
/// </summary>
|
||||||
|
public string Document { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// UTC Timestamp to return to KOReader
|
||||||
|
/// </summary>
|
||||||
|
public DateTime Timestamp { get; set; }
|
||||||
|
}
|
||||||
13
API/DTOs/Metadata/Browse/BrowseGenreDto.cs
Normal file
13
API/DTOs/Metadata/Browse/BrowseGenreDto.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
namespace API.DTOs.Metadata.Browse;
|
||||||
|
|
||||||
|
public sealed record BrowseGenreDto : GenreTagDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Number of Series this Entity is on
|
||||||
|
/// </summary>
|
||||||
|
public int SeriesCount { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Number of Chapters this Entity is on
|
||||||
|
/// </summary>
|
||||||
|
public int ChapterCount { get; set; }
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
using API.DTOs.Person;
|
using API.DTOs.Person;
|
||||||
|
|
||||||
namespace API.DTOs;
|
namespace API.DTOs.Metadata.Browse;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Used to browse writers and click in to see their series
|
/// Used to browse writers and click in to see their series
|
||||||
|
|
@ -12,7 +12,7 @@ public class BrowsePersonDto : PersonDto
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int SeriesCount { get; set; }
|
public int SeriesCount { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Number or Issues this Person is the Writer for
|
/// Number of Issues this Person is the Writer for
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int IssueCount { get; set; }
|
public int ChapterCount { get; set; }
|
||||||
}
|
}
|
||||||
13
API/DTOs/Metadata/Browse/BrowseTagDto.cs
Normal file
13
API/DTOs/Metadata/Browse/BrowseTagDto.cs
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
namespace API.DTOs.Metadata.Browse;
|
||||||
|
|
||||||
|
public sealed record BrowseTagDto : TagDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Number of Series this Entity is on
|
||||||
|
/// </summary>
|
||||||
|
public int SeriesCount { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Number of Chapters this Entity is on
|
||||||
|
/// </summary>
|
||||||
|
public int ChapterCount { get; set; }
|
||||||
|
}
|
||||||
27
API/DTOs/Metadata/Browse/Requests/BrowsePersonFilterDto.cs
Normal file
27
API/DTOs/Metadata/Browse/Requests/BrowsePersonFilterDto.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using API.DTOs.Filtering;
|
||||||
|
using API.DTOs.Filtering.v2;
|
||||||
|
using API.Entities.Enums;
|
||||||
|
|
||||||
|
namespace API.DTOs.Metadata.Browse.Requests;
|
||||||
|
#nullable enable
|
||||||
|
|
||||||
|
public sealed record BrowsePersonFilterDto
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Not used - For parity with Series Filter
|
||||||
|
/// </summary>
|
||||||
|
public int Id { get; set; }
|
||||||
|
/// <summary>
|
||||||
|
/// Not used - For parity with Series Filter
|
||||||
|
/// </summary>
|
||||||
|
public string? Name { get; set; }
|
||||||
|
public ICollection<PersonFilterStatementDto> Statements { get; set; } = [];
|
||||||
|
public FilterCombination Combination { get; set; } = FilterCombination.And;
|
||||||
|
public PersonSortOptions? SortOptions { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Limit the number of rows returned. Defaults to not applying a limit (aka 0)
|
||||||
|
/// </summary>
|
||||||
|
public int LimitTo { get; set; } = 0;
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
namespace API.DTOs.Metadata;
|
namespace API.DTOs.Metadata;
|
||||||
|
|
||||||
public sealed record GenreTagDto
|
public record GenreTagDto
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public required string Title { get; set; }
|
public required string Title { get; set; }
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
namespace API.DTOs.Metadata;
|
namespace API.DTOs.Metadata;
|
||||||
|
|
||||||
public sealed record TagDto
|
public record TagDto
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public required string Title { get; set; }
|
public required string Title { get; set; }
|
||||||
|
|
|
||||||
|
|
@ -49,6 +49,11 @@ public sealed record ReadingListDto : IHasCoverImage
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required AgeRating AgeRating { get; set; } = AgeRating.Unknown;
|
public required AgeRating AgeRating { get; set; } = AgeRating.Unknown;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Username of the User that owns (in the case of a promoted list)
|
||||||
|
/// </summary>
|
||||||
|
public string OwnerUserName { get; set; }
|
||||||
|
|
||||||
public void ResetColorScape()
|
public void ResetColorScape()
|
||||||
{
|
{
|
||||||
PrimaryColor = string.Empty;
|
PrimaryColor = string.Empty;
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,9 @@ public sealed record UserReadingProfileDto
|
||||||
/// <inheritdoc cref="AppUserReadingProfile.WidthOverride"/>
|
/// <inheritdoc cref="AppUserReadingProfile.WidthOverride"/>
|
||||||
public int? WidthOverride { get; set; }
|
public int? WidthOverride { get; set; }
|
||||||
|
|
||||||
|
/// <inheritdoc cref="AppUserReadingProfile.DisableWidthOverride"/>
|
||||||
|
public BreakPoint DisableWidthOverride { get; set; } = BreakPoint.Never;
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region EpubReader
|
#region EpubReader
|
||||||
|
|
|
||||||
3574
API/Data/Migrations/20250519151126_KoreaderHash.Designer.cs
generated
Normal file
3574
API/Data/Migrations/20250519151126_KoreaderHash.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
28
API/Data/Migrations/20250519151126_KoreaderHash.cs
Normal file
28
API/Data/Migrations/20250519151126_KoreaderHash.cs
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace API.Data.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class KoreaderHash : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<string>(
|
||||||
|
name: "KoreaderHash",
|
||||||
|
table: "MangaFile",
|
||||||
|
type: "TEXT",
|
||||||
|
nullable: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "KoreaderHash",
|
||||||
|
table: "MangaFile");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
3701
API/Data/Migrations/20250610210618_AppUserReadingProfileDisableWidthOverrideBreakPoint.Designer.cs
generated
Normal file
3701
API/Data/Migrations/20250610210618_AppUserReadingProfileDisableWidthOverrideBreakPoint.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,29 @@
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace API.Data.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AppUserReadingProfileDisableWidthOverrideBreakPoint : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.AddColumn<int>(
|
||||||
|
name: "DisableWidthOverride",
|
||||||
|
table: "AppUserReadingProfiles",
|
||||||
|
type: "INTEGER",
|
||||||
|
nullable: false,
|
||||||
|
defaultValue: 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropColumn(
|
||||||
|
name: "DisableWidthOverride",
|
||||||
|
table: "AppUserReadingProfiles");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -665,6 +665,9 @@ namespace API.Data.Migrations
|
||||||
.HasColumnType("TEXT")
|
.HasColumnType("TEXT")
|
||||||
.HasDefaultValue("Dark");
|
.HasDefaultValue("Dark");
|
||||||
|
|
||||||
|
b.Property<int>("DisableWidthOverride")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
b.Property<bool>("EmulateBook")
|
b.Property<bool>("EmulateBook")
|
||||||
.HasColumnType("INTEGER");
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
|
@ -704,7 +707,7 @@ namespace API.Data.Migrations
|
||||||
b.Property<int>("ScalingOption")
|
b.Property<int>("ScalingOption")
|
||||||
.HasColumnType("INTEGER");
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
b.PrimitiveCollection<string>("SeriesIds")
|
b.Property<string>("SeriesIds")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
b.Property<bool>("ShowScreenHints")
|
b.Property<bool>("ShowScreenHints")
|
||||||
|
|
@ -1405,6 +1408,9 @@ namespace API.Data.Migrations
|
||||||
b.Property<int>("Format")
|
b.Property<int>("Format")
|
||||||
.HasColumnType("INTEGER");
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("KoreaderHash")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
b.Property<DateTime>("LastFileAnalysis")
|
b.Property<DateTime>("LastFileAnalysis")
|
||||||
.HasColumnType("TEXT");
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -108,14 +108,17 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
||||||
|
|
||||||
public async Task<bool> NeedsDataRefresh(int seriesId)
|
public async Task<bool> NeedsDataRefresh(int seriesId)
|
||||||
{
|
{
|
||||||
|
// TODO: Add unit test
|
||||||
var row = await _context.ExternalSeriesMetadata
|
var row = await _context.ExternalSeriesMetadata
|
||||||
.Where(s => s.SeriesId == seriesId)
|
.Where(s => s.SeriesId == seriesId)
|
||||||
.FirstOrDefaultAsync();
|
.FirstOrDefaultAsync();
|
||||||
|
|
||||||
return row == null || row.ValidUntilUtc <= DateTime.UtcNow;
|
return row == null || row.ValidUntilUtc <= DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<SeriesDetailPlusDto?> GetSeriesDetailPlusDto(int seriesId)
|
public async Task<SeriesDetailPlusDto?> GetSeriesDetailPlusDto(int seriesId)
|
||||||
{
|
{
|
||||||
|
// TODO: Add unit test
|
||||||
var seriesDetailDto = await _context.ExternalSeriesMetadata
|
var seriesDetailDto = await _context.ExternalSeriesMetadata
|
||||||
.Where(m => m.SeriesId == seriesId)
|
.Where(m => m.SeriesId == seriesId)
|
||||||
.Include(m => m.ExternalRatings)
|
.Include(m => m.ExternalRatings)
|
||||||
|
|
@ -144,7 +147,7 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
||||||
.ProjectTo<SeriesDto>(_mapper.ConfigurationProvider)
|
.ProjectTo<SeriesDto>(_mapper.ConfigurationProvider)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
IEnumerable<UserReviewDto> reviews = new List<UserReviewDto>();
|
IEnumerable<UserReviewDto> reviews = [];
|
||||||
if (seriesDetailDto.ExternalReviews != null && seriesDetailDto.ExternalReviews.Any())
|
if (seriesDetailDto.ExternalReviews != null && seriesDetailDto.ExternalReviews.Any())
|
||||||
{
|
{
|
||||||
reviews = seriesDetailDto.ExternalReviews
|
reviews = seriesDetailDto.ExternalReviews
|
||||||
|
|
@ -231,6 +234,7 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
||||||
.Include(s => s.ExternalSeriesMetadata)
|
.Include(s => s.ExternalSeriesMetadata)
|
||||||
.Where(s => !ExternalMetadataService.NonEligibleLibraryTypes.Contains(s.Library.Type))
|
.Where(s => !ExternalMetadataService.NonEligibleLibraryTypes.Contains(s.Library.Type))
|
||||||
.Where(s => s.Library.AllowMetadataMatching)
|
.Where(s => s.Library.AllowMetadataMatching)
|
||||||
|
.WhereIf(filter.LibraryType >= 0, s => s.Library.Type == (LibraryType) filter.LibraryType)
|
||||||
.FilterMatchState(filter.MatchStateOption)
|
.FilterMatchState(filter.MatchStateOption)
|
||||||
.OrderBy(s => s.NormalizedName)
|
.OrderBy(s => s.NormalizedName)
|
||||||
.ProjectTo<ManageMatchSeriesDto>(_mapper.ConfigurationProvider)
|
.ProjectTo<ManageMatchSeriesDto>(_mapper.ConfigurationProvider)
|
||||||
|
|
|
||||||
|
|
@ -3,9 +3,11 @@ using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using API.DTOs.Metadata;
|
using API.DTOs.Metadata;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
using API.Entities;
|
using API.Entities;
|
||||||
using API.Extensions;
|
using API.Extensions;
|
||||||
using API.Extensions.QueryExtensions;
|
using API.Extensions.QueryExtensions;
|
||||||
|
using API.Helpers;
|
||||||
using API.Services.Tasks.Scanner.Parser;
|
using API.Services.Tasks.Scanner.Parser;
|
||||||
using AutoMapper;
|
using AutoMapper;
|
||||||
using AutoMapper.QueryableExtensions;
|
using AutoMapper.QueryableExtensions;
|
||||||
|
|
@ -27,6 +29,7 @@ public interface IGenreRepository
|
||||||
Task<GenreTagDto> GetRandomGenre();
|
Task<GenreTagDto> GetRandomGenre();
|
||||||
Task<GenreTagDto> GetGenreById(int id);
|
Task<GenreTagDto> GetGenreById(int id);
|
||||||
Task<List<string>> GetAllGenresNotInListAsync(ICollection<string> genreNames);
|
Task<List<string>> GetAllGenresNotInListAsync(ICollection<string> genreNames);
|
||||||
|
Task<PagedList<BrowseGenreDto>> GetBrowseableGenre(int userId, UserParams userParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class GenreRepository : IGenreRepository
|
public class GenreRepository : IGenreRepository
|
||||||
|
|
@ -165,4 +168,28 @@ public class GenreRepository : IGenreRepository
|
||||||
// Return the original non-normalized genres for the missing ones
|
// Return the original non-normalized genres for the missing ones
|
||||||
return missingGenres.Select(normalizedName => normalizedToOriginalMap[normalizedName]).ToList();
|
return missingGenres.Select(normalizedName => normalizedToOriginalMap[normalizedName]).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<PagedList<BrowseGenreDto>> GetBrowseableGenre(int userId, UserParams userParams)
|
||||||
|
{
|
||||||
|
var ageRating = await _context.AppUser.GetUserAgeRestriction(userId);
|
||||||
|
|
||||||
|
var query = _context.Genre
|
||||||
|
.RestrictAgainstAgeRestriction(ageRating)
|
||||||
|
.Select(g => new BrowseGenreDto
|
||||||
|
{
|
||||||
|
Id = g.Id,
|
||||||
|
Title = g.Title,
|
||||||
|
SeriesCount = g.SeriesMetadatas
|
||||||
|
.Select(sm => sm.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count(),
|
||||||
|
ChapterCount = g.Chapters
|
||||||
|
.Select(ch => ch.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count()
|
||||||
|
})
|
||||||
|
.OrderBy(g => g.Title);
|
||||||
|
|
||||||
|
return await PagedList<BrowseGenreDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,11 +5,13 @@ using API.Entities;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace API.Data.Repositories;
|
namespace API.Data.Repositories;
|
||||||
|
#nullable enable
|
||||||
|
|
||||||
public interface IMangaFileRepository
|
public interface IMangaFileRepository
|
||||||
{
|
{
|
||||||
void Update(MangaFile file);
|
void Update(MangaFile file);
|
||||||
Task<IList<MangaFile>> GetAllWithMissingExtension();
|
Task<IList<MangaFile>> GetAllWithMissingExtension();
|
||||||
|
Task<MangaFile?> GetByKoreaderHash(string hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class MangaFileRepository : IMangaFileRepository
|
public class MangaFileRepository : IMangaFileRepository
|
||||||
|
|
@ -32,4 +34,13 @@ public class MangaFileRepository : IMangaFileRepository
|
||||||
.Where(f => string.IsNullOrEmpty(f.Extension))
|
.Where(f => string.IsNullOrEmpty(f.Extension))
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<MangaFile?> GetByKoreaderHash(string hash)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(hash)) return null;
|
||||||
|
|
||||||
|
return await _context.MangaFile
|
||||||
|
.FirstOrDefaultAsync(f => f.KoreaderHash != null &&
|
||||||
|
f.KoreaderHash.Equals(hash.ToUpper()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,19 @@ using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using API.Data.Misc;
|
||||||
using API.DTOs;
|
using API.DTOs;
|
||||||
|
using API.DTOs.Filtering.v2;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
|
using API.DTOs.Metadata.Browse.Requests;
|
||||||
using API.DTOs.Person;
|
using API.DTOs.Person;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
using API.Entities.Person;
|
using API.Entities.Person;
|
||||||
using API.Extensions;
|
using API.Extensions;
|
||||||
using API.Extensions.QueryExtensions;
|
using API.Extensions.QueryExtensions;
|
||||||
|
using API.Extensions.QueryExtensions.Filtering;
|
||||||
using API.Helpers;
|
using API.Helpers;
|
||||||
|
using API.Helpers.Converters;
|
||||||
using AutoMapper;
|
using AutoMapper;
|
||||||
using AutoMapper.QueryableExtensions;
|
using AutoMapper.QueryableExtensions;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
@ -45,7 +51,7 @@ public interface IPersonRepository
|
||||||
Task<string?> GetCoverImageAsync(int personId);
|
Task<string?> GetCoverImageAsync(int personId);
|
||||||
Task<string?> GetCoverImageByNameAsync(string name);
|
Task<string?> GetCoverImageByNameAsync(string name);
|
||||||
Task<IEnumerable<PersonRole>> GetRolesForPersonByName(int personId, int userId);
|
Task<IEnumerable<PersonRole>> GetRolesForPersonByName(int personId, int userId);
|
||||||
Task<PagedList<BrowsePersonDto>> GetAllWritersAndSeriesCount(int userId, UserParams userParams);
|
Task<PagedList<BrowsePersonDto>> GetBrowsePersonDtos(int userId, BrowsePersonFilterDto filter, UserParams userParams);
|
||||||
Task<Person?> GetPersonById(int personId, PersonIncludes includes = PersonIncludes.None);
|
Task<Person?> GetPersonById(int personId, PersonIncludes includes = PersonIncludes.None);
|
||||||
Task<PersonDto?> GetPersonDtoByName(string name, int userId, PersonIncludes includes = PersonIncludes.Aliases);
|
Task<PersonDto?> GetPersonDtoByName(string name, int userId, PersonIncludes includes = PersonIncludes.Aliases);
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
@ -194,36 +200,82 @@ public class PersonRepository : IPersonRepository
|
||||||
return chapterRoles.Union(seriesRoles).Distinct();
|
return chapterRoles.Union(seriesRoles).Distinct();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PagedList<BrowsePersonDto>> GetAllWritersAndSeriesCount(int userId, UserParams userParams)
|
public async Task<PagedList<BrowsePersonDto>> GetBrowsePersonDtos(int userId, BrowsePersonFilterDto filter, UserParams userParams)
|
||||||
{
|
{
|
||||||
List<PersonRole> roles = [PersonRole.Writer, PersonRole.CoverArtist];
|
|
||||||
var ageRating = await _context.AppUser.GetUserAgeRestriction(userId);
|
var ageRating = await _context.AppUser.GetUserAgeRestriction(userId);
|
||||||
|
|
||||||
var query = _context.Person
|
var query = CreateFilteredPersonQueryable(userId, filter, ageRating);
|
||||||
.Where(p => p.SeriesMetadataPeople.Any(smp => roles.Contains(smp.Role)) || p.ChapterPeople.Any(cmp => roles.Contains(cmp.Role)))
|
|
||||||
.RestrictAgainstAgeRestriction(ageRating)
|
|
||||||
.Select(p => new BrowsePersonDto
|
|
||||||
{
|
|
||||||
Id = p.Id,
|
|
||||||
Name = p.Name,
|
|
||||||
Description = p.Description,
|
|
||||||
CoverImage = p.CoverImage,
|
|
||||||
SeriesCount = p.SeriesMetadataPeople
|
|
||||||
.Where(smp => roles.Contains(smp.Role))
|
|
||||||
.Select(smp => smp.SeriesMetadata.SeriesId)
|
|
||||||
.Distinct()
|
|
||||||
.Count(),
|
|
||||||
IssueCount = p.ChapterPeople
|
|
||||||
.Where(cp => roles.Contains(cp.Role))
|
|
||||||
.Select(cp => cp.Chapter.Id)
|
|
||||||
.Distinct()
|
|
||||||
.Count()
|
|
||||||
})
|
|
||||||
.OrderBy(p => p.Name);
|
|
||||||
|
|
||||||
return await PagedList<BrowsePersonDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
|
return await PagedList<BrowsePersonDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private IQueryable<BrowsePersonDto> CreateFilteredPersonQueryable(int userId, BrowsePersonFilterDto filter, AgeRestriction ageRating)
|
||||||
|
{
|
||||||
|
var query = _context.Person.AsNoTracking();
|
||||||
|
|
||||||
|
// Apply filtering based on statements
|
||||||
|
query = BuildPersonFilterQuery(userId, filter, query);
|
||||||
|
|
||||||
|
// Apply age restriction
|
||||||
|
query = query.RestrictAgainstAgeRestriction(ageRating);
|
||||||
|
|
||||||
|
// Apply sorting and limiting
|
||||||
|
var sortedQuery = query.SortBy(filter.SortOptions);
|
||||||
|
|
||||||
|
var limitedQuery = ApplyPersonLimit(sortedQuery, filter.LimitTo);
|
||||||
|
|
||||||
|
// Project to DTO
|
||||||
|
var projectedQuery = limitedQuery.Select(p => new BrowsePersonDto
|
||||||
|
{
|
||||||
|
Id = p.Id,
|
||||||
|
Name = p.Name,
|
||||||
|
Description = p.Description,
|
||||||
|
CoverImage = p.CoverImage,
|
||||||
|
SeriesCount = p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count(),
|
||||||
|
ChapterCount = p.ChapterPeople
|
||||||
|
.Select(cp => cp.Chapter.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count()
|
||||||
|
});
|
||||||
|
|
||||||
|
return projectedQuery;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IQueryable<Person> BuildPersonFilterQuery(int userId, BrowsePersonFilterDto filterDto, IQueryable<Person> query)
|
||||||
|
{
|
||||||
|
if (filterDto.Statements == null || filterDto.Statements.Count == 0) return query;
|
||||||
|
|
||||||
|
var queries = filterDto.Statements
|
||||||
|
.Select(statement => BuildPersonFilterGroup(userId, statement, query))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
return filterDto.Combination == FilterCombination.And
|
||||||
|
? queries.Aggregate((q1, q2) => q1.Intersect(q2))
|
||||||
|
: queries.Aggregate((q1, q2) => q1.Union(q2));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IQueryable<Person> BuildPersonFilterGroup(int userId, PersonFilterStatementDto statement, IQueryable<Person> query)
|
||||||
|
{
|
||||||
|
var value = PersonFilterFieldValueConverter.ConvertValue(statement.Field, statement.Value);
|
||||||
|
|
||||||
|
return statement.Field switch
|
||||||
|
{
|
||||||
|
PersonFilterField.Name => query.HasPersonName(true, statement.Comparison, (string)value),
|
||||||
|
PersonFilterField.Role => query.HasPersonRole(true, statement.Comparison, (IList<PersonRole>)value),
|
||||||
|
PersonFilterField.SeriesCount => query.HasPersonSeriesCount(true, statement.Comparison, (int)value),
|
||||||
|
PersonFilterField.ChapterCount => query.HasPersonChapterCount(true, statement.Comparison, (int)value),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(statement.Field), $"Unexpected value for field: {statement.Field}")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IQueryable<Person> ApplyPersonLimit(IQueryable<Person> query, int limit)
|
||||||
|
{
|
||||||
|
return limit <= 0 ? query : query.Take(limit);
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<Person?> GetPersonById(int personId, PersonIncludes includes = PersonIncludes.None)
|
public async Task<Person?> GetPersonById(int personId, PersonIncludes includes = PersonIncludes.None)
|
||||||
{
|
{
|
||||||
return await _context.Person.Where(p => p.Id == personId)
|
return await _context.Person.Where(p => p.Id == personId)
|
||||||
|
|
|
||||||
|
|
@ -735,6 +735,7 @@ public class SeriesRepository : ISeriesRepository
|
||||||
{
|
{
|
||||||
return await _context.Series
|
return await _context.Series
|
||||||
.Where(s => s.Id == seriesId)
|
.Where(s => s.Id == seriesId)
|
||||||
|
.Include(s => s.ExternalSeriesMetadata)
|
||||||
.Select(series => new PlusSeriesRequestDto()
|
.Select(series => new PlusSeriesRequestDto()
|
||||||
{
|
{
|
||||||
MediaFormat = series.Library.Type.ConvertToPlusMediaFormat(series.Format),
|
MediaFormat = series.Library.Type.ConvertToPlusMediaFormat(series.Format),
|
||||||
|
|
@ -744,6 +745,7 @@ public class SeriesRepository : ISeriesRepository
|
||||||
ScrobblingService.AniListWeblinkWebsite),
|
ScrobblingService.AniListWeblinkWebsite),
|
||||||
MalId = ScrobblingService.ExtractId<long?>(series.Metadata.WebLinks,
|
MalId = ScrobblingService.ExtractId<long?>(series.Metadata.WebLinks,
|
||||||
ScrobblingService.MalWeblinkWebsite),
|
ScrobblingService.MalWeblinkWebsite),
|
||||||
|
CbrId = series.ExternalSeriesMetadata.CbrId,
|
||||||
GoogleBooksId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
GoogleBooksId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
||||||
ScrobblingService.GoogleBooksWeblinkWebsite),
|
ScrobblingService.GoogleBooksWeblinkWebsite),
|
||||||
MangaDexId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
MangaDexId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
||||||
|
|
@ -1088,8 +1090,6 @@ public class SeriesRepository : ISeriesRepository
|
||||||
return query.Where(s => false);
|
return query.Where(s => false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// First setup any FilterField.Libraries in the statements, as these don't have any traditional query statements applied here
|
// First setup any FilterField.Libraries in the statements, as these don't have any traditional query statements applied here
|
||||||
query = ApplyLibraryFilter(filter, query);
|
query = ApplyLibraryFilter(filter, query);
|
||||||
|
|
||||||
|
|
@ -1290,7 +1290,7 @@ public class SeriesRepository : ISeriesRepository
|
||||||
FilterField.ReadingDate => query.HasReadingDate(true, statement.Comparison, (DateTime) value, userId),
|
FilterField.ReadingDate => query.HasReadingDate(true, statement.Comparison, (DateTime) value, userId),
|
||||||
FilterField.ReadLast => query.HasReadLast(true, statement.Comparison, (int) value, userId),
|
FilterField.ReadLast => query.HasReadLast(true, statement.Comparison, (int) value, userId),
|
||||||
FilterField.AverageRating => query.HasAverageRating(true, statement.Comparison, (float) value),
|
FilterField.AverageRating => query.HasAverageRating(true, statement.Comparison, (float) value),
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
_ => throw new ArgumentOutOfRangeException(nameof(statement.Field), $"Unexpected value for field: {statement.Field}")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,11 @@
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using API.DTOs.Metadata;
|
using API.DTOs.Metadata;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
using API.Entities;
|
using API.Entities;
|
||||||
using API.Extensions;
|
using API.Extensions;
|
||||||
using API.Extensions.QueryExtensions;
|
using API.Extensions.QueryExtensions;
|
||||||
|
using API.Helpers;
|
||||||
using API.Services.Tasks.Scanner.Parser;
|
using API.Services.Tasks.Scanner.Parser;
|
||||||
using AutoMapper;
|
using AutoMapper;
|
||||||
using AutoMapper.QueryableExtensions;
|
using AutoMapper.QueryableExtensions;
|
||||||
|
|
@ -23,6 +25,7 @@ public interface ITagRepository
|
||||||
Task RemoveAllTagNoLongerAssociated();
|
Task RemoveAllTagNoLongerAssociated();
|
||||||
Task<IList<TagDto>> GetAllTagDtosForLibrariesAsync(int userId, IList<int>? libraryIds = null);
|
Task<IList<TagDto>> GetAllTagDtosForLibrariesAsync(int userId, IList<int>? libraryIds = null);
|
||||||
Task<List<string>> GetAllTagsNotInListAsync(ICollection<string> tags);
|
Task<List<string>> GetAllTagsNotInListAsync(ICollection<string> tags);
|
||||||
|
Task<PagedList<BrowseTagDto>> GetBrowseableTag(int userId, UserParams userParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
public class TagRepository : ITagRepository
|
public class TagRepository : ITagRepository
|
||||||
|
|
@ -104,6 +107,30 @@ public class TagRepository : ITagRepository
|
||||||
return missingTags.Select(normalizedName => normalizedToOriginalMap[normalizedName]).ToList();
|
return missingTags.Select(normalizedName => normalizedToOriginalMap[normalizedName]).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<PagedList<BrowseTagDto>> GetBrowseableTag(int userId, UserParams userParams)
|
||||||
|
{
|
||||||
|
var ageRating = await _context.AppUser.GetUserAgeRestriction(userId);
|
||||||
|
|
||||||
|
var query = _context.Tag
|
||||||
|
.RestrictAgainstAgeRestriction(ageRating)
|
||||||
|
.Select(g => new BrowseTagDto
|
||||||
|
{
|
||||||
|
Id = g.Id,
|
||||||
|
Title = g.Title,
|
||||||
|
SeriesCount = g.SeriesMetadatas
|
||||||
|
.Select(sm => sm.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count(),
|
||||||
|
ChapterCount = g.Chapters
|
||||||
|
.Select(ch => ch.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count()
|
||||||
|
})
|
||||||
|
.OrderBy(g => g.Title);
|
||||||
|
|
||||||
|
return await PagedList<BrowseTagDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<IList<Tag>> GetAllTagsAsync()
|
public async Task<IList<Tag>> GetAllTagsAsync()
|
||||||
{
|
{
|
||||||
return await _context.Tag.ToListAsync();
|
return await _context.Tag.ToListAsync();
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ public static class Seed
|
||||||
new AppUserSideNavStream()
|
new AppUserSideNavStream()
|
||||||
{
|
{
|
||||||
Name = "browse-authors",
|
Name = "browse-authors",
|
||||||
StreamType = SideNavStreamType.BrowseAuthors,
|
StreamType = SideNavStreamType.BrowsePeople,
|
||||||
Order = 6,
|
Order = 6,
|
||||||
IsProvided = true,
|
IsProvided = true,
|
||||||
Visible = true
|
Visible = true
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,22 @@
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.ComponentModel;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
using API.Entities.Enums.UserPreferences;
|
using API.Entities.Enums.UserPreferences;
|
||||||
|
|
||||||
namespace API.Entities;
|
namespace API.Entities;
|
||||||
|
|
||||||
|
public enum BreakPoint
|
||||||
|
{
|
||||||
|
[Description("Never")]
|
||||||
|
Never = 0,
|
||||||
|
[Description("Mobile")]
|
||||||
|
Mobile = 1,
|
||||||
|
[Description("Tablet")]
|
||||||
|
Tablet = 2,
|
||||||
|
[Description("Desktop")]
|
||||||
|
Desktop = 3,
|
||||||
|
}
|
||||||
|
|
||||||
public class AppUserReadingProfile
|
public class AppUserReadingProfile
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
|
@ -72,6 +85,10 @@ public class AppUserReadingProfile
|
||||||
/// Manga Reader Option: Optional fixed width override
|
/// Manga Reader Option: Optional fixed width override
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int? WidthOverride { get; set; } = null;
|
public int? WidthOverride { get; set; } = null;
|
||||||
|
/// <summary>
|
||||||
|
/// Manga Reader Option: Disable the width override if the screen is past the breakpoint
|
||||||
|
/// </summary>
|
||||||
|
public BreakPoint DisableWidthOverride { get; set; } = BreakPoint.Never;
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,11 @@ public class MangaFile : IEntityDate
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public required string FilePath { get; set; }
|
public required string FilePath { get; set; }
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// A hash of the document using Koreader's unique hashing algorithm
|
||||||
|
/// </summary>
|
||||||
|
/// <remark> KoreaderHash is only available for epub types </remark>
|
||||||
|
public string? KoreaderHash { get; set; }
|
||||||
|
/// <summary>
|
||||||
/// Number of pages for the given file
|
/// Number of pages for the given file
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int Pages { get; set; }
|
public int Pages { get; set; }
|
||||||
|
|
|
||||||
|
|
@ -10,5 +10,5 @@ public enum SideNavStreamType
|
||||||
ExternalSource = 6,
|
ExternalSource = 6,
|
||||||
AllSeries = 7,
|
AllSeries = 7,
|
||||||
WantToRead = 8,
|
WantToRead = 8,
|
||||||
BrowseAuthors = 9
|
BrowsePeople = 9
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,7 @@ public static class ApplicationServiceExtensions
|
||||||
services.AddScoped<IRatingService, RatingService>();
|
services.AddScoped<IRatingService, RatingService>();
|
||||||
services.AddScoped<IPersonService, PersonService>();
|
services.AddScoped<IPersonService, PersonService>();
|
||||||
services.AddScoped<IReadingProfileService, ReadingProfileService>();
|
services.AddScoped<IReadingProfileService, ReadingProfileService>();
|
||||||
|
services.AddScoped<IKoreaderService, KoreaderService>();
|
||||||
|
|
||||||
services.AddScoped<IScannerService, ScannerService>();
|
services.AddScoped<IScannerService, ScannerService>();
|
||||||
services.AddScoped<IProcessSeries, ProcessSeries>();
|
services.AddScoped<IProcessSeries, ProcessSeries>();
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ using System.Linq;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using API.Data.Misc;
|
using API.Data.Misc;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
|
using API.Entities.Metadata;
|
||||||
|
|
||||||
namespace API.Extensions;
|
namespace API.Extensions;
|
||||||
#nullable enable
|
#nullable enable
|
||||||
|
|
@ -42,4 +43,16 @@ public static class EnumerableExtensions
|
||||||
|
|
||||||
return q;
|
return q;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<SeriesMetadata> RestrictAgainstAgeRestriction(this IEnumerable<SeriesMetadata> items, AgeRestriction restriction)
|
||||||
|
{
|
||||||
|
if (restriction.AgeRating == AgeRating.NotApplicable) return items;
|
||||||
|
var q = items.Where(s => s.AgeRating <= restriction.AgeRating);
|
||||||
|
if (!restriction.IncludeUnknowns)
|
||||||
|
{
|
||||||
|
return q.Where(s => s.AgeRating != AgeRating.Unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
return q;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
136
API/Extensions/QueryExtensions/Filtering/PersonFilter.cs
Normal file
136
API/Extensions/QueryExtensions/Filtering/PersonFilter.cs
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using API.DTOs.Filtering.v2;
|
||||||
|
using API.Entities.Enums;
|
||||||
|
using API.Entities.Person;
|
||||||
|
using Kavita.Common;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace API.Extensions.QueryExtensions.Filtering;
|
||||||
|
|
||||||
|
public static class PersonFilter
|
||||||
|
{
|
||||||
|
public static IQueryable<Person> HasPersonName(this IQueryable<Person> queryable, bool condition,
|
||||||
|
FilterComparison comparison, string queryString)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(queryString) || !condition) return queryable;
|
||||||
|
|
||||||
|
return comparison switch
|
||||||
|
{
|
||||||
|
FilterComparison.Equal => queryable.Where(p => p.Name.Equals(queryString)),
|
||||||
|
FilterComparison.BeginsWith => queryable.Where(p => EF.Functions.Like(p.Name, $"{queryString}%")),
|
||||||
|
FilterComparison.EndsWith => queryable.Where(p => EF.Functions.Like(p.Name, $"%{queryString}")),
|
||||||
|
FilterComparison.Matches => queryable.Where(p => EF.Functions.Like(p.Name, $"%{queryString}%")),
|
||||||
|
FilterComparison.NotEqual => queryable.Where(p => p.Name != queryString),
|
||||||
|
FilterComparison.NotContains or FilterComparison.GreaterThan or FilterComparison.GreaterThanEqual
|
||||||
|
or FilterComparison.LessThan or FilterComparison.LessThanEqual or FilterComparison.Contains
|
||||||
|
or FilterComparison.IsBefore or FilterComparison.IsAfter or FilterComparison.IsInLast
|
||||||
|
or FilterComparison.IsNotInLast or FilterComparison.MustContains
|
||||||
|
or FilterComparison.IsEmpty =>
|
||||||
|
throw new KavitaException($"{comparison} not applicable for Person.Name"),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison,
|
||||||
|
"Filter Comparison is not supported")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static IQueryable<Person> HasPersonRole(this IQueryable<Person> queryable, bool condition,
|
||||||
|
FilterComparison comparison, IList<PersonRole> roles)
|
||||||
|
{
|
||||||
|
if (roles == null || roles.Count == 0 || !condition) return queryable;
|
||||||
|
|
||||||
|
return comparison switch
|
||||||
|
{
|
||||||
|
FilterComparison.Contains or FilterComparison.MustContains => queryable.Where(p =>
|
||||||
|
p.SeriesMetadataPeople.Any(smp => roles.Contains(smp.Role)) ||
|
||||||
|
p.ChapterPeople.Any(cmp => roles.Contains(cmp.Role))),
|
||||||
|
FilterComparison.NotContains => queryable.Where(p =>
|
||||||
|
!p.SeriesMetadataPeople.Any(smp => roles.Contains(smp.Role)) &&
|
||||||
|
!p.ChapterPeople.Any(cmp => roles.Contains(cmp.Role))),
|
||||||
|
FilterComparison.Equal or FilterComparison.NotEqual or FilterComparison.BeginsWith
|
||||||
|
or FilterComparison.EndsWith or FilterComparison.Matches or FilterComparison.GreaterThan
|
||||||
|
or FilterComparison.GreaterThanEqual or FilterComparison.LessThan or FilterComparison.LessThanEqual
|
||||||
|
or FilterComparison.IsBefore or FilterComparison.IsAfter or FilterComparison.IsInLast
|
||||||
|
or FilterComparison.IsNotInLast
|
||||||
|
or FilterComparison.IsEmpty =>
|
||||||
|
throw new KavitaException($"{comparison} not applicable for Person.Role"),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison,
|
||||||
|
"Filter Comparison is not supported")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IQueryable<Person> HasPersonSeriesCount(this IQueryable<Person> queryable, bool condition,
|
||||||
|
FilterComparison comparison, int count)
|
||||||
|
{
|
||||||
|
if (!condition) return queryable;
|
||||||
|
|
||||||
|
return comparison switch
|
||||||
|
{
|
||||||
|
FilterComparison.Equal => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() == count),
|
||||||
|
FilterComparison.GreaterThan => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() > count),
|
||||||
|
FilterComparison.GreaterThanEqual => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() >= count),
|
||||||
|
FilterComparison.LessThan => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() < count),
|
||||||
|
FilterComparison.LessThanEqual => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() <= count),
|
||||||
|
FilterComparison.NotEqual => queryable.Where(p => p.SeriesMetadataPeople
|
||||||
|
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||||
|
.Distinct()
|
||||||
|
.Count() != count),
|
||||||
|
FilterComparison.BeginsWith or FilterComparison.EndsWith or FilterComparison.Matches
|
||||||
|
or FilterComparison.Contains or FilterComparison.NotContains or FilterComparison.IsBefore
|
||||||
|
or FilterComparison.IsAfter or FilterComparison.IsInLast or FilterComparison.IsNotInLast
|
||||||
|
or FilterComparison.MustContains
|
||||||
|
or FilterComparison.IsEmpty => throw new KavitaException(
|
||||||
|
$"{comparison} not applicable for Person.SeriesCount"),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "Filter Comparison is not supported")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IQueryable<Person> HasPersonChapterCount(this IQueryable<Person> queryable, bool condition,
|
||||||
|
FilterComparison comparison, int count)
|
||||||
|
{
|
||||||
|
if (!condition) return queryable;
|
||||||
|
|
||||||
|
return comparison switch
|
||||||
|
{
|
||||||
|
FilterComparison.Equal => queryable.Where(p =>
|
||||||
|
p.ChapterPeople.Select(cp => cp.Chapter.Id).Distinct().Count() == count),
|
||||||
|
FilterComparison.GreaterThan => queryable.Where(p => p.ChapterPeople
|
||||||
|
.Select(cp => cp.Chapter.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count() > count),
|
||||||
|
FilterComparison.GreaterThanEqual => queryable.Where(p => p.ChapterPeople
|
||||||
|
.Select(cp => cp.Chapter.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count() >= count),
|
||||||
|
FilterComparison.LessThan => queryable.Where(p =>
|
||||||
|
p.ChapterPeople.Select(cp => cp.Chapter.Id).Distinct().Count() < count),
|
||||||
|
FilterComparison.LessThanEqual => queryable.Where(p => p.ChapterPeople
|
||||||
|
.Select(cp => cp.Chapter.Id)
|
||||||
|
.Distinct()
|
||||||
|
.Count() <= count),
|
||||||
|
FilterComparison.NotEqual => queryable.Where(p =>
|
||||||
|
p.ChapterPeople.Select(cp => cp.Chapter.Id).Distinct().Count() != count),
|
||||||
|
FilterComparison.BeginsWith or FilterComparison.EndsWith or FilterComparison.Matches
|
||||||
|
or FilterComparison.Contains or FilterComparison.NotContains or FilterComparison.IsBefore
|
||||||
|
or FilterComparison.IsAfter or FilterComparison.IsInLast or FilterComparison.IsNotInLast
|
||||||
|
or FilterComparison.MustContains
|
||||||
|
or FilterComparison.IsEmpty => throw new KavitaException(
|
||||||
|
$"{comparison} not applicable for Person.ChapterCount"),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "Filter Comparison is not supported")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -5,10 +5,13 @@ using System.Linq.Expressions;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using API.Data.Misc;
|
using API.Data.Misc;
|
||||||
using API.Data.Repositories;
|
using API.Data.Repositories;
|
||||||
|
using API.DTOs;
|
||||||
using API.DTOs.Filtering;
|
using API.DTOs.Filtering;
|
||||||
using API.DTOs.KavitaPlus.Manage;
|
using API.DTOs.KavitaPlus.Manage;
|
||||||
|
using API.DTOs.Metadata.Browse;
|
||||||
using API.Entities;
|
using API.Entities;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
|
using API.Entities.Person;
|
||||||
using API.Entities.Scrobble;
|
using API.Entities.Scrobble;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
|
@ -273,6 +276,27 @@ public static class QueryableExtensions
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static IQueryable<Person> SortBy(this IQueryable<Person> query, PersonSortOptions? sort)
|
||||||
|
{
|
||||||
|
if (sort == null)
|
||||||
|
{
|
||||||
|
return query.OrderBy(p => p.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sort.SortField switch
|
||||||
|
{
|
||||||
|
PersonSortField.Name when sort.IsAscending => query.OrderBy(p => p.Name),
|
||||||
|
PersonSortField.Name => query.OrderByDescending(p => p.Name),
|
||||||
|
PersonSortField.SeriesCount when sort.IsAscending => query.OrderBy(p => p.SeriesMetadataPeople.Count),
|
||||||
|
PersonSortField.SeriesCount => query.OrderByDescending(p => p.SeriesMetadataPeople.Count),
|
||||||
|
PersonSortField.ChapterCount when sort.IsAscending => query.OrderBy(p => p.ChapterPeople.Count),
|
||||||
|
PersonSortField.ChapterCount => query.OrderByDescending(p => p.ChapterPeople.Count),
|
||||||
|
_ => query.OrderBy(p => p.Name)
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Performs either OrderBy or OrderByDescending on the given query based on the value of SortOptions.IsAscending.
|
/// Performs either OrderBy or OrderByDescending on the given query based on the value of SortOptions.IsAscending.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ using System.Linq;
|
||||||
using API.Data.Misc;
|
using API.Data.Misc;
|
||||||
using API.Entities;
|
using API.Entities;
|
||||||
using API.Entities.Enums;
|
using API.Entities.Enums;
|
||||||
|
using API.Entities.Metadata;
|
||||||
using API.Entities.Person;
|
using API.Entities.Person;
|
||||||
|
|
||||||
namespace API.Extensions.QueryExtensions;
|
namespace API.Extensions.QueryExtensions;
|
||||||
|
|
@ -26,6 +27,7 @@ public static class RestrictByAgeExtensions
|
||||||
return q;
|
return q;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static IQueryable<Chapter> RestrictAgainstAgeRestriction(this IQueryable<Chapter> queryable, AgeRestriction restriction)
|
public static IQueryable<Chapter> RestrictAgainstAgeRestriction(this IQueryable<Chapter> queryable, AgeRestriction restriction)
|
||||||
{
|
{
|
||||||
if (restriction.AgeRating == AgeRating.NotApplicable) return queryable;
|
if (restriction.AgeRating == AgeRating.NotApplicable) return queryable;
|
||||||
|
|
@ -39,20 +41,6 @@ public static class RestrictByAgeExtensions
|
||||||
return q;
|
return q;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Obsolete]
|
|
||||||
public static IQueryable<CollectionTag> RestrictAgainstAgeRestriction(this IQueryable<CollectionTag> queryable, AgeRestriction restriction)
|
|
||||||
{
|
|
||||||
if (restriction.AgeRating == AgeRating.NotApplicable) return queryable;
|
|
||||||
|
|
||||||
if (restriction.IncludeUnknowns)
|
|
||||||
{
|
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
|
||||||
sm.AgeRating <= restriction.AgeRating));
|
|
||||||
}
|
|
||||||
|
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
|
||||||
sm.AgeRating <= restriction.AgeRating && sm.AgeRating > AgeRating.Unknown));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IQueryable<AppUserCollection> RestrictAgainstAgeRestriction(this IQueryable<AppUserCollection> queryable, AgeRestriction restriction)
|
public static IQueryable<AppUserCollection> RestrictAgainstAgeRestriction(this IQueryable<AppUserCollection> queryable, AgeRestriction restriction)
|
||||||
{
|
{
|
||||||
|
|
@ -74,12 +62,15 @@ public static class RestrictByAgeExtensions
|
||||||
|
|
||||||
if (restriction.IncludeUnknowns)
|
if (restriction.IncludeUnknowns)
|
||||||
{
|
{
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
return queryable.Where(c =>
|
||||||
sm.AgeRating <= restriction.AgeRating));
|
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating) ||
|
||||||
|
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating));
|
||||||
}
|
}
|
||||||
|
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
return queryable.Where(c =>
|
||||||
sm.AgeRating <= restriction.AgeRating && sm.AgeRating > AgeRating.Unknown));
|
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating && sm.AgeRating != AgeRating.Unknown) ||
|
||||||
|
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating && cp.AgeRating != AgeRating.Unknown)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IQueryable<Tag> RestrictAgainstAgeRestriction(this IQueryable<Tag> queryable, AgeRestriction restriction)
|
public static IQueryable<Tag> RestrictAgainstAgeRestriction(this IQueryable<Tag> queryable, AgeRestriction restriction)
|
||||||
|
|
@ -88,12 +79,15 @@ public static class RestrictByAgeExtensions
|
||||||
|
|
||||||
if (restriction.IncludeUnknowns)
|
if (restriction.IncludeUnknowns)
|
||||||
{
|
{
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
return queryable.Where(c =>
|
||||||
sm.AgeRating <= restriction.AgeRating));
|
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating) ||
|
||||||
|
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating));
|
||||||
}
|
}
|
||||||
|
|
||||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
return queryable.Where(c =>
|
||||||
sm.AgeRating <= restriction.AgeRating && sm.AgeRating > AgeRating.Unknown));
|
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating && sm.AgeRating != AgeRating.Unknown) ||
|
||||||
|
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating && cp.AgeRating != AgeRating.Unknown)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IQueryable<Person> RestrictAgainstAgeRestriction(this IQueryable<Person> queryable, AgeRestriction restriction)
|
public static IQueryable<Person> RestrictAgainstAgeRestriction(this IQueryable<Person> queryable, AgeRestriction restriction)
|
||||||
|
|
|
||||||
|
|
@ -286,7 +286,8 @@ public class AutoMapperProfiles : Profile
|
||||||
CreateMap<AppUserBookmark, BookmarkDto>();
|
CreateMap<AppUserBookmark, BookmarkDto>();
|
||||||
|
|
||||||
CreateMap<ReadingList, ReadingListDto>()
|
CreateMap<ReadingList, ReadingListDto>()
|
||||||
.ForMember(dest => dest.ItemCount, opt => opt.MapFrom(src => src.Items.Count));
|
.ForMember(dest => dest.ItemCount, opt => opt.MapFrom(src => src.Items.Count))
|
||||||
|
.ForMember(dest => dest.OwnerUserName, opt => opt.MapFrom(src => src.AppUser.UserName));
|
||||||
CreateMap<ReadingListItem, ReadingListItemDto>();
|
CreateMap<ReadingListItem, ReadingListItemDto>();
|
||||||
CreateMap<ScrobbleError, ScrobbleErrorDto>();
|
CreateMap<ScrobbleError, ScrobbleErrorDto>();
|
||||||
CreateMap<ChapterDto, TachiyomiChapterDto>();
|
CreateMap<ChapterDto, TachiyomiChapterDto>();
|
||||||
|
|
|
||||||
46
API/Helpers/Builders/KoreaderBookDtoBuilder.cs
Normal file
46
API/Helpers/Builders/KoreaderBookDtoBuilder.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
using System;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using API.DTOs.Koreader;
|
||||||
|
|
||||||
|
namespace API.Helpers.Builders;
|
||||||
|
|
||||||
|
public class KoreaderBookDtoBuilder : IEntityBuilder<KoreaderBookDto>
|
||||||
|
{
|
||||||
|
private readonly KoreaderBookDto _dto;
|
||||||
|
public KoreaderBookDto Build() => _dto;
|
||||||
|
|
||||||
|
public KoreaderBookDtoBuilder(string documentHash)
|
||||||
|
{
|
||||||
|
_dto = new KoreaderBookDto()
|
||||||
|
{
|
||||||
|
Document = documentHash,
|
||||||
|
Device = "Kavita"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public KoreaderBookDtoBuilder WithDocument(string documentHash)
|
||||||
|
{
|
||||||
|
_dto.Document = documentHash;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KoreaderBookDtoBuilder WithProgress(string progress)
|
||||||
|
{
|
||||||
|
_dto.Progress = progress;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KoreaderBookDtoBuilder WithPercentage(int? pageNum, int pages)
|
||||||
|
{
|
||||||
|
_dto.Percentage = (pageNum ?? 0) / (float) pages;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KoreaderBookDtoBuilder WithDeviceId(string installId, int userId)
|
||||||
|
{
|
||||||
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(installId + userId));
|
||||||
|
_dto.Device_id = Convert.ToHexString(hash);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -60,4 +60,17 @@ public class MangaFileBuilder : IEntityBuilder<MangaFile>
|
||||||
_mangaFile.Id = Math.Max(id, 0);
|
_mangaFile.Id = Math.Max(id, 0);
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generate the Hash on the underlying file
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>Only applicable to Epubs</remarks>
|
||||||
|
public MangaFileBuilder WithHash()
|
||||||
|
{
|
||||||
|
if (_mangaFile.Format != MangaFormat.Epub) return this;
|
||||||
|
|
||||||
|
_mangaFile.KoreaderHash = KoreaderHelper.HashContents(_mangaFile.FilePath);
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
31
API/Helpers/Converters/PersonFilterFieldValueConverter.cs
Normal file
31
API/Helpers/Converters/PersonFilterFieldValueConverter.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using API.DTOs.Filtering.v2;
|
||||||
|
using API.Entities.Enums;
|
||||||
|
|
||||||
|
namespace API.Helpers.Converters;
|
||||||
|
|
||||||
|
public static class PersonFilterFieldValueConverter
|
||||||
|
{
|
||||||
|
public static object ConvertValue(PersonFilterField field, string value)
|
||||||
|
{
|
||||||
|
return field switch
|
||||||
|
{
|
||||||
|
PersonFilterField.Name => value,
|
||||||
|
PersonFilterField.Role => ParsePersonRoles(value),
|
||||||
|
PersonFilterField.SeriesCount => int.Parse(value),
|
||||||
|
PersonFilterField.ChapterCount => int.Parse(value),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Field is not supported")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IList<PersonRole> ParsePersonRoles(string value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(value)) return [];
|
||||||
|
|
||||||
|
return value.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||||
|
.Select(v => Enum.Parse<PersonRole>(v.Trim()))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
113
API/Helpers/KoreaderHelper.cs
Normal file
113
API/Helpers/KoreaderHelper.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
using API.DTOs.Progress;
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using API.Services.Tasks.Scanner.Parser;
|
||||||
|
|
||||||
|
namespace API.Helpers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// All things related to Koreader
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>Original developer: https://github.com/MFDeAngelo</remarks>
|
||||||
|
public static class KoreaderHelper
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Hashes the document according to a custom Koreader hashing algorithm.
|
||||||
|
/// Look at the util.partialMD5 method in the attached link.
|
||||||
|
/// Note: Only applies to epub files
|
||||||
|
/// </summary>
|
||||||
|
/// <remarks>The hashing algorithm is relatively quick as it only hashes ~10,000 bytes for the biggest of files.</remarks>
|
||||||
|
/// <see href="https://github.com/koreader/koreader/blob/master/frontend/util.lua#L1040"/>
|
||||||
|
/// <param name="filePath">The path to the file to hash</param>
|
||||||
|
public static string HashContents(string filePath)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath) || !Parser.IsEpub(filePath))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var file = File.OpenRead(filePath);
|
||||||
|
|
||||||
|
const int step = 1024;
|
||||||
|
const int size = 1024;
|
||||||
|
var md5 = MD5.Create();
|
||||||
|
var buffer = new byte[size];
|
||||||
|
|
||||||
|
for (var i = -1; i < 10; i++)
|
||||||
|
{
|
||||||
|
file.Position = step << 2 * i;
|
||||||
|
var bytesRead = file.Read(buffer, 0, size);
|
||||||
|
if (bytesRead > 0)
|
||||||
|
{
|
||||||
|
md5.TransformBlock(buffer, 0, bytesRead, buffer, 0);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
file.Close();
|
||||||
|
md5.TransformFinalBlock([], 0, 0);
|
||||||
|
|
||||||
|
return md5.Hash == null ? null : Convert.ToHexString(md5.Hash).ToUpper();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Koreader can identify documents based on contents or title.
|
||||||
|
/// For now, we only support by contents.
|
||||||
|
/// </summary>
|
||||||
|
public static string HashTitle(string filePath)
|
||||||
|
{
|
||||||
|
var fileName = Path.GetFileName(filePath);
|
||||||
|
var fileNameBytes = Encoding.ASCII.GetBytes(fileName);
|
||||||
|
var bytes = MD5.HashData(fileNameBytes);
|
||||||
|
|
||||||
|
return Convert.ToHexString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void UpdateProgressDto(ProgressDto progress, string koreaderPosition)
|
||||||
|
{
|
||||||
|
var path = koreaderPosition.Split('/');
|
||||||
|
if (path.Length < 6)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var docNumber = path[2].Replace("DocFragment[", string.Empty).Replace("]", string.Empty);
|
||||||
|
progress.PageNum = int.Parse(docNumber) - 1;
|
||||||
|
var lastTag = path[5].ToUpper();
|
||||||
|
|
||||||
|
if (lastTag == "A")
|
||||||
|
{
|
||||||
|
progress.BookScrollId = null;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// The format that Kavita accepts as a progress string. It tells Kavita where Koreader last left off.
|
||||||
|
progress.BookScrollId = $"//html[1]/BODY/APP-ROOT[1]/DIV[1]/DIV[1]/DIV[1]/APP-BOOK-READER[1]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/{lastTag}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static string GetKoreaderPosition(ProgressDto progressDto)
|
||||||
|
{
|
||||||
|
string lastTag;
|
||||||
|
var koreaderPageNumber = progressDto.PageNum + 1;
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(progressDto.BookScrollId))
|
||||||
|
{
|
||||||
|
lastTag = "a";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var tokens = progressDto.BookScrollId.Split('/');
|
||||||
|
lastTag = tokens[^1].ToLower();
|
||||||
|
}
|
||||||
|
|
||||||
|
// The format that Koreader accepts as a progress string. It tells Koreader where Kavita last left off.
|
||||||
|
return $"/body/DocFragment[{koreaderPageNumber}]/body/div/{lastTag}";
|
||||||
|
}
|
||||||
|
}
|
||||||
1
API/I18N/as.json
Normal file
1
API/I18N/as.json
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
{}
|
||||||
|
|
@ -208,5 +208,6 @@
|
||||||
"smart-filter-name-required": "Vyžaduje se název chytrého filtru",
|
"smart-filter-name-required": "Vyžaduje se název chytrého filtru",
|
||||||
"smart-filter-system-name": "Nelze použít název streamu poskytovaného systémem",
|
"smart-filter-system-name": "Nelze použít název streamu poskytovaného systémem",
|
||||||
"sidenav-stream-only-delete-smart-filter": "Z postranní navigace lze odstranit pouze streamy chytrých filtrů",
|
"sidenav-stream-only-delete-smart-filter": "Z postranní navigace lze odstranit pouze streamy chytrých filtrů",
|
||||||
"aliases-have-overlap": "Jeden nebo více aliasů se překrývají s jinými osobami, nelze je aktualizovat"
|
"aliases-have-overlap": "Jeden nebo více aliasů se překrývají s jinými osobami, nelze je aktualizovat",
|
||||||
|
"generated-reading-profile-name": "Generováno z {0}"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -208,5 +208,6 @@
|
||||||
"sidenav-stream-only-delete-smart-filter": "Ní féidir ach sruthanna cliste scagaire a scriosadh as an SideNav",
|
"sidenav-stream-only-delete-smart-filter": "Ní féidir ach sruthanna cliste scagaire a scriosadh as an SideNav",
|
||||||
"dashboard-stream-only-delete-smart-filter": "Ní féidir ach sruthanna cliste scagaire a scriosadh ón deais",
|
"dashboard-stream-only-delete-smart-filter": "Ní féidir ach sruthanna cliste scagaire a scriosadh ón deais",
|
||||||
"smart-filter-name-required": "Ainm Scagaire Cliste ag teastáil",
|
"smart-filter-name-required": "Ainm Scagaire Cliste ag teastáil",
|
||||||
"aliases-have-overlap": "Tá forluí idir ceann amháin nó níos mó de na leasainmneacha agus daoine eile, ní féidir iad a nuashonrú"
|
"aliases-have-overlap": "Tá forluí idir ceann amháin nó níos mó de na leasainmneacha agus daoine eile, ní féidir iad a nuashonrú",
|
||||||
|
"generated-reading-profile-name": "Gineadh ó {0}"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,5 +21,6 @@
|
||||||
"age-restriction-update": "אירעה תקלה בעת עדכון הגבלת גיל",
|
"age-restriction-update": "אירעה תקלה בעת עדכון הגבלת גיל",
|
||||||
"generic-user-update": "אירעה תקלה בעת עדכון משתמש",
|
"generic-user-update": "אירעה תקלה בעת עדכון משתמש",
|
||||||
"user-already-registered": "משתמש רשום כבר בתור {0}",
|
"user-already-registered": "משתמש רשום כבר בתור {0}",
|
||||||
"manual-setup-fail": "לא מתאפשר להשלים הגדרה ידנית. יש לבטל וליצור מחדש את ההזמנה"
|
"manual-setup-fail": "לא מתאפשר להשלים הגדרה ידנית. יש לבטל וליצור מחדש את ההזמנה",
|
||||||
|
"email-taken": "דואר אלקטרוני כבר בשימוש"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -208,5 +208,6 @@
|
||||||
"dashboard-stream-only-delete-smart-filter": "Somente fluxos de filtros inteligentes podem ser excluídos do painel",
|
"dashboard-stream-only-delete-smart-filter": "Somente fluxos de filtros inteligentes podem ser excluídos do painel",
|
||||||
"smart-filter-system-name": "Você não pode usar o nome de um fluxo fornecido pelo sistema",
|
"smart-filter-system-name": "Você não pode usar o nome de um fluxo fornecido pelo sistema",
|
||||||
"sidenav-stream-only-delete-smart-filter": "Somente fluxos de filtros inteligentes podem ser excluídos do Navegador Lateral",
|
"sidenav-stream-only-delete-smart-filter": "Somente fluxos de filtros inteligentes podem ser excluídos do Navegador Lateral",
|
||||||
"aliases-have-overlap": "Um ou mais dos pseudônimos se sobrepõem a outras pessoas, não pode atualizar"
|
"aliases-have-overlap": "Um ou mais dos pseudônimos se sobrepõem a outras pessoas, não pode atualizar",
|
||||||
|
"generated-reading-profile-name": "Gerado a partir de {0}"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
{
|
{
|
||||||
"confirm-email": "Вы обязаны сначала подтвердить свою почту",
|
"confirm-email": "Сначала Вы обязаны подтвердить свою электронную почту",
|
||||||
"generate-token": "Возникла проблема с генерацией токена подтверждения электронной почты. Смотрите журналы",
|
"generate-token": "Возникла проблема с генерацией токена подтверждения электронной почты. Смотрите журналы",
|
||||||
"invalid-password": "Неверный пароль",
|
"invalid-password": "Неверный пароль",
|
||||||
"invalid-email-confirmation": "Неверное подтверждение электронной почты",
|
"invalid-email-confirmation": "Неверное подтверждение электронной почты",
|
||||||
|
|
@ -35,15 +35,15 @@
|
||||||
"no-user": "Пользователь не существует",
|
"no-user": "Пользователь не существует",
|
||||||
"generic-invite-user": "Возникла проблема с приглашением пользователя. Пожалуйста, проверьте журналы.",
|
"generic-invite-user": "Возникла проблема с приглашением пользователя. Пожалуйста, проверьте журналы.",
|
||||||
"permission-denied": "Вам запрещено выполнять эту операцию",
|
"permission-denied": "Вам запрещено выполнять эту операцию",
|
||||||
"invalid-access": "Недопустимый доступ",
|
"invalid-access": "В доступе отказано",
|
||||||
"reading-list-name-exists": "Такой список для чтения уже существует",
|
"reading-list-name-exists": "Такой список для чтения уже существует",
|
||||||
"perform-scan": "Пожалуйста, выполните сканирование этой серии или библиотеки и повторите попытку",
|
"perform-scan": "Пожалуйста, выполните сканирование этой серии или библиотеки и повторите попытку",
|
||||||
"generic-device-create": "При создании устройства возникла ошибка",
|
"generic-device-create": "При создании устройства возникла ошибка",
|
||||||
"generic-read-progress": "Возникла проблема с сохранением прогресса",
|
"generic-read-progress": "Возникла проблема с сохранением прогресса",
|
||||||
"file-doesnt-exist": "Файл не существует",
|
"file-doesnt-exist": "Файл не существует",
|
||||||
"admin-already-exists": "Администратор уже существует",
|
"admin-already-exists": "Администратор уже существует",
|
||||||
"send-to-kavita-email": "Отправка на устройство не может быть использована с почтовым сервисом Kavita. Пожалуйста, настройте свой собственный.",
|
"send-to-kavita-email": "Отправка на устройство не может быть использована без настройки электронной почты",
|
||||||
"no-image-for-page": "Нет такого изображения для страницы {0}. Попробуйте обновить, чтобы обновить кэш.",
|
"no-image-for-page": "Нет такого изображения для страницы {0}. Попробуйте обновить, для повторного кеширования.",
|
||||||
"reading-list-permission": "У вас нет прав на этот список чтения или список не существует",
|
"reading-list-permission": "У вас нет прав на этот список чтения или список не существует",
|
||||||
"volume-doesnt-exist": "Том не существует",
|
"volume-doesnt-exist": "Том не существует",
|
||||||
"generic-library": "Возникла критическая проблема. Пожалуйста, попробуйте еще раз.",
|
"generic-library": "Возникла критическая проблема. Пожалуйста, попробуйте еще раз.",
|
||||||
|
|
@ -57,7 +57,7 @@
|
||||||
"generic-reading-list-create": "Возникла проблема с созданием списка для чтения",
|
"generic-reading-list-create": "Возникла проблема с созданием списка для чтения",
|
||||||
"no-cover-image": "Изображение на обложке отсутствует",
|
"no-cover-image": "Изображение на обложке отсутствует",
|
||||||
"collection-updated": "Коллекция успешно обновлена",
|
"collection-updated": "Коллекция успешно обновлена",
|
||||||
"critical-email-migration": "Возникла проблема при переносе электронной почты. Обратитесь в службу поддержки",
|
"critical-email-migration": "Возникла проблема при смене электронной почты. Обратитесь в службу поддержки",
|
||||||
"cache-file-find": "Не удалось найти изображение в кэше. Перезагрузитесь и попробуйте снова.",
|
"cache-file-find": "Не удалось найти изображение в кэше. Перезагрузитесь и попробуйте снова.",
|
||||||
"duplicate-bookmark": "Дублирующая закладка уже существует",
|
"duplicate-bookmark": "Дублирующая закладка уже существует",
|
||||||
"collection-tag-duplicate": "Такая коллекция уже существует",
|
"collection-tag-duplicate": "Такая коллекция уже существует",
|
||||||
|
|
@ -72,7 +72,7 @@
|
||||||
"pdf-doesnt-exist": "PDF не существует, когда он должен существовать",
|
"pdf-doesnt-exist": "PDF не существует, когда он должен существовать",
|
||||||
"generic-device-delete": "При удалении устройства возникла ошибка",
|
"generic-device-delete": "При удалении устройства возникла ошибка",
|
||||||
"bookmarks-empty": "Закладки не могут быть пустыми",
|
"bookmarks-empty": "Закладки не могут быть пустыми",
|
||||||
"valid-number": "Должен быть действительный номер страницы",
|
"valid-number": "Номер страницы должен быть действительным",
|
||||||
"series-doesnt-exist": "Серия не существует",
|
"series-doesnt-exist": "Серия не существует",
|
||||||
"no-library-access": "Пользователь не имеет доступа к этой библиотеке",
|
"no-library-access": "Пользователь не имеет доступа к этой библиотеке",
|
||||||
"reading-list-item-delete": "Не удалось удалить элемент(ы)",
|
"reading-list-item-delete": "Не удалось удалить элемент(ы)",
|
||||||
|
|
@ -155,7 +155,7 @@
|
||||||
"generic-user-delete": "Не удалось удалить пользователя",
|
"generic-user-delete": "Не удалось удалить пользователя",
|
||||||
"generic-cover-reading-list-save": "Невозможно сохранить изображение обложки в списке для чтения",
|
"generic-cover-reading-list-save": "Невозможно сохранить изображение обложки в списке для чтения",
|
||||||
"unable-to-register-k+": "Невозможно зарегистрировать лицензию из-за ошибки. Обратитесь в службу поддержки Кавита+",
|
"unable-to-register-k+": "Невозможно зарегистрировать лицензию из-за ошибки. Обратитесь в службу поддержки Кавита+",
|
||||||
"encode-as-warning": "Конвертировать в PNG невозможно. Для обложек используйте Обновить Обложки. Закладки и фавиконки нельзя закодировать обратно.",
|
"encode-as-warning": "Вы не можете конвертировать в формат PNG. Для обновления обложек используйте команду \"Обновить обложку\". Закладки и значки не могут быть закодированы обратно.",
|
||||||
"want-to-read": "Хотите прочитать",
|
"want-to-read": "Хотите прочитать",
|
||||||
"generic-user-pref": "Возникла проблема с сохранением предпочтений",
|
"generic-user-pref": "Возникла проблема с сохранением предпочтений",
|
||||||
"external-sources": "Внешние источники",
|
"external-sources": "Внешние источники",
|
||||||
|
|
@ -197,7 +197,7 @@
|
||||||
"kavita+-data-refresh": "Обновление данных Kavita+",
|
"kavita+-data-refresh": "Обновление данных Kavita+",
|
||||||
"kavitaplus-restricted": "Это доступно только для Kavita+",
|
"kavitaplus-restricted": "Это доступно только для Kavita+",
|
||||||
"person-doesnt-exist": "Персона не существует",
|
"person-doesnt-exist": "Персона не существует",
|
||||||
"generic-cover-volume-save": "Не удается сохранить обложку для раздела",
|
"generic-cover-volume-save": "Не удается сохранить обложку для тома",
|
||||||
"generic-cover-person-save": "Не удается сохранить изображение обложки для Персоны",
|
"generic-cover-person-save": "Не удается сохранить изображение обложки для Персоны",
|
||||||
"person-name-unique": "Имя персоны должно быть уникальным",
|
"person-name-unique": "Имя персоны должно быть уникальным",
|
||||||
"person-image-doesnt-exist": "Персона не существует в CoversDB",
|
"person-image-doesnt-exist": "Персона не существует в CoversDB",
|
||||||
|
|
|
||||||
|
|
@ -1 +1,92 @@
|
||||||
{}
|
{
|
||||||
|
"disabled-account": "Váš účet je zakázaný. Kontaktujte správcu servera.",
|
||||||
|
"register-user": "Niečo sa pokazilo pri registrácii užívateľa",
|
||||||
|
"confirm-email": "Najprv musíte potvrdiť svoj e-mail",
|
||||||
|
"locked-out": "Boli ste zamknutí z dôvodu veľkého počtu neúspešných pokusov o prihlásenie. Počkajte 10 minút.",
|
||||||
|
"validate-email": "Pri validácii vášho e-mailu sa vyskytla chyba: {0}",
|
||||||
|
"confirm-token-gen": "Pri vytváraní potvrdzovacieho tokenu sa vyskytla chyba",
|
||||||
|
"permission-denied": "Na vykonanie tejto úlohy nemáte oprávnenie",
|
||||||
|
"password-required": "Ak nie ste administrátor, musíte na vykonanie zmien vo vašom profile zadať vaše aktuálne heslo",
|
||||||
|
"invalid-password": "Nesprávne heslo",
|
||||||
|
"invalid-token": "Nesprávny token",
|
||||||
|
"unable-to-reset-key": "Niečo sa pokazilo, kľúč nie je možné resetovať",
|
||||||
|
"invalid-payload": "Nesprávny payload",
|
||||||
|
"nothing-to-do": "Nič na vykonanie",
|
||||||
|
"share-multiple-emails": "Nemôžete zdielať e-maily medzi rôznymi účtami",
|
||||||
|
"generate-token": "Pri generovaní potvrdzovacieho tokenu e-mailu sa vyskytla chyba. Pozrite záznamy udalostí",
|
||||||
|
"age-restriction-update": "Pri aktualizovaní vekového obmedzenia sa vyskytla chyba",
|
||||||
|
"no-user": "Používateľ neexistuje",
|
||||||
|
"generic-user-update": "Aktualizácia používateľa prebehla s výnimkou",
|
||||||
|
"username-taken": "Používateľské meno už existuje",
|
||||||
|
"user-already-confirmed": "Používateľ je už potvrdený",
|
||||||
|
"user-already-registered": "Používateľ je už registrovaný ako {0}",
|
||||||
|
"user-already-invited": "Používateľ je už pod týmto e-mailom pozvaný a musí ešte prijať pozvanie.",
|
||||||
|
"generic-password-update": "Pri potvrdení nového hesla sa vyskytla neočakávaná chyba",
|
||||||
|
"generic-invite-user": "Pri pozývaní tohto používateľa sa vyskytla chyba. Pozrite záznamy udalostí.",
|
||||||
|
"password-updated": "Heslo aktualizované",
|
||||||
|
"forgot-password-generic": "E-mail bude odoslaný na zadanú adresu len v prípade, ak existuje v databáze",
|
||||||
|
"invalid-email-confirmation": "Neplatné potvrdenie e-mailu",
|
||||||
|
"not-accessible-password": "Váš server nie je dostupný. Odkaz na resetovanie vášho hesla je v záznamoch udalostí",
|
||||||
|
"email-taken": "Zadaný e-mail už existuje",
|
||||||
|
"denied": "Nepovolené",
|
||||||
|
"manual-setup-fail": "Manuálne nastavenie nie je možné dokončiť. Prosím zrušte aktuálny postup a znovu vytvorte pozvánku",
|
||||||
|
"generic-user-email-update": "Nemožno aktualizovať e-mail používateľa. Skontrolujte záznamy udalostí.",
|
||||||
|
"email-not-enabled": "E-mail nie je na tomto serveri povolený. Preto túto akciu nemôžete vykonať.",
|
||||||
|
"collection-updated": "Zbierka bola úspešne aktualizovaná",
|
||||||
|
"device-doesnt-exist": "Zariadenie neexistuje",
|
||||||
|
"generic-device-delete": "Pri odstraňovaní zariadenia sa vyskytla chyba",
|
||||||
|
"greater-0": "{0} musí byť väčší ako 0",
|
||||||
|
"send-to-size-limit": "Snažíte sa odoslať súbor(y), ktoré sú príliš veľké pre vášho e-mailového poskytovateľa",
|
||||||
|
"send-to-device-status": "Prenos súborov do vášho zariadenia",
|
||||||
|
"no-cover-image": "Žiadny prebal",
|
||||||
|
"must-be-defined": "{0} musí byť definovaný",
|
||||||
|
"generic-favicon": "Pri získavaní favicon-u domény sa vyskytla chyba",
|
||||||
|
"no-library-access": "Pozužívateľ nemá prístup do tejto knižnice",
|
||||||
|
"user-doesnt-exist": "Používateľ neexistuje",
|
||||||
|
"collection-already-exists": "Zbierka už existuje",
|
||||||
|
"not-accessible": "Váš server nie je dostupný z vonkajšieho prostredia",
|
||||||
|
"email-sent": "E-mail odoslaný",
|
||||||
|
"user-migration-needed": "Uvedený používateľ potrebuje migrovať. Odhláste ho a opäť prihláste na spustenie migrácie",
|
||||||
|
"generic-invite-email": "Pri opakovanom odosielaní pozývacieho e-mailu sa vyskytla chyba",
|
||||||
|
"email-settings-invalid": "V nastaveniach e-mailu chýbajú potrebné údaje. Uistite sa, že všetky nastavenia e-mailu sú uložené.",
|
||||||
|
"chapter-doesnt-exist": "Kapitola neexistuje",
|
||||||
|
"critical-email-migration": "Počas migrácie e-mailu sa vyskytla chyba. Kontaktujte podporu",
|
||||||
|
"collection-deleted": "Zbierka bola vymazaná",
|
||||||
|
"generic-error": "Niečo sa pokazilo, skúste to znova",
|
||||||
|
"collection-doesnt-exist": "Zbierka neexistuje",
|
||||||
|
"generic-device-update": "Pri aktualizácii zariadenia sa vyskytla chyba",
|
||||||
|
"bookmark-doesnt-exist": "Záložka neexistuje",
|
||||||
|
"person-doesnt-exist": "Osoba neexistuje",
|
||||||
|
"send-to-kavita-email": "Odoslanie do zariadenia nemôže byť použité bez nastavenia e-amilu",
|
||||||
|
"send-to-unallowed": "Nemôžete odosielať do zariadenia, ktoré nie je vaše",
|
||||||
|
"generic-library": "Vyskytla sa kritická chyba. Prosím skúste to opäť.",
|
||||||
|
"pdf-doesnt-exist": "PDF neexistuje, hoci by malo",
|
||||||
|
"generic-library-update": "Počas aktualizácie knižnice sa vyskytla kritická chyba.",
|
||||||
|
"invalid-access": "Neplatný prístup",
|
||||||
|
"perform-scan": "Prosím, vykonajte opakovaný sken na tejto sérii alebo knižnici",
|
||||||
|
"generic-read-progress": "Pri ukladaní aktuálneho stavu sa vyskytla chyba",
|
||||||
|
"generic-clear-bookmarks": "Záložky nie je možné vymazať",
|
||||||
|
"bookmark-permission": "Nemáte oprávnenie na vkladanie/odstraňovanie záložiek",
|
||||||
|
"bookmark-save": "Nemožno uložiť záložku",
|
||||||
|
"bookmarks-empty": "Záložky nemôžu byť prázdne",
|
||||||
|
"library-doesnt-exist": "Knižnica neexistuje",
|
||||||
|
"invalid-path": "Neplatné umiestnenie",
|
||||||
|
"generic-send-to": "Pri odosielaní súboru(-ov) do vášho zariadenia sa vyskytla chyba",
|
||||||
|
"no-image-for-page": "Žiadny taký obrázok pre stránku {0}. Pokúste sa ju obnoviť, aby ste ju mohli nanovo uložiť.",
|
||||||
|
"delete-library-while-scan": "Nemôžete odstrániť knižnicu počas prebiehajúceho skenovania. Prosím, vyčkajte na dokončenie skenovania alebo reštartujte Kavitu a skúste ju opäť odstrániť",
|
||||||
|
"invalid-username": "Neplatné používateľské meno",
|
||||||
|
"account-email-invalid": "E-mail uvedený v údajoch administrátora nie je platným e-mailom. Nie je možné zaslať testovací e-mail.",
|
||||||
|
"admin-already-exists": "Administrátor už existuje",
|
||||||
|
"invalid-filename": "Neplatný názov súboru",
|
||||||
|
"file-doesnt-exist": "Súbor neexistuje",
|
||||||
|
"invalid-email": "E-mail v záznamoch pre používateľov nie platný e-mail. Odkazy sú uvedené v záznamoch udalostí.",
|
||||||
|
"file-missing": "Súbor nebol nájdený v knihe",
|
||||||
|
"error-import-stack": "Pri importovaní MAL balíka sa vyskytla chyba",
|
||||||
|
"person-name-required": "Meno osoby je povinné a nesmie byť prázdne",
|
||||||
|
"person-name-unique": "Meno osoby musí byť jedinečné",
|
||||||
|
"person-image-doesnt-exist": "Osoba neexistuje v databáze CoversDB",
|
||||||
|
"generic-device-create": "Pri vytváraní zariadenia sa vyskytla chyba",
|
||||||
|
"series-doesnt-exist": "Séria neexistuje",
|
||||||
|
"volume-doesnt-exist": "Zväzok neexistuje",
|
||||||
|
"library-name-exists": "Názov knižnice už existuje. Prosím, vyberte si pre daný server jedinečný názov."
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -208,5 +208,6 @@
|
||||||
"smart-filter-name-required": "需要智能筛选器名称",
|
"smart-filter-name-required": "需要智能筛选器名称",
|
||||||
"smart-filter-system-name": "您不能使用系统提供的流名称",
|
"smart-filter-system-name": "您不能使用系统提供的流名称",
|
||||||
"sidenav-stream-only-delete-smart-filter": "只能从侧边栏删除智能筛选器流",
|
"sidenav-stream-only-delete-smart-filter": "只能从侧边栏删除智能筛选器流",
|
||||||
"aliases-have-overlap": "一个或多个别名与其他人有重叠,无法更新"
|
"aliases-have-overlap": "一个或多个别名与其他人有重叠,无法更新",
|
||||||
|
"generated-reading-profile-name": "由 {0} 生成"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,11 +10,9 @@ using API.Entities.Interfaces;
|
||||||
using API.Extensions;
|
using API.Extensions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using NetVips;
|
using NetVips;
|
||||||
using SixLabors.ImageSharp;
|
|
||||||
using SixLabors.ImageSharp.PixelFormats;
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
using SixLabors.ImageSharp.Processing;
|
using SixLabors.ImageSharp.Processing;
|
||||||
using SixLabors.ImageSharp.Processing.Processors.Quantization;
|
using SixLabors.ImageSharp.Processing.Processors.Quantization;
|
||||||
using Color = System.Drawing.Color;
|
|
||||||
using Image = NetVips.Image;
|
using Image = NetVips.Image;
|
||||||
|
|
||||||
namespace API.Services;
|
namespace API.Services;
|
||||||
|
|
@ -750,7 +748,7 @@ public class ImageService : IImageService
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Color HexToRgb(string? hex)
|
public static (int R, int G, int B) HexToRgb(string? hex)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(hex)) throw new ArgumentException("Hex cannot be null");
|
if (string.IsNullOrEmpty(hex)) throw new ArgumentException("Hex cannot be null");
|
||||||
|
|
||||||
|
|
@ -774,7 +772,7 @@ public class ImageService : IImageService
|
||||||
var g = Convert.ToInt32(hex.Substring(2, 2), 16);
|
var g = Convert.ToInt32(hex.Substring(2, 2), 16);
|
||||||
var b = Convert.ToInt32(hex.Substring(4, 2), 16);
|
var b = Convert.ToInt32(hex.Substring(4, 2), 16);
|
||||||
|
|
||||||
return Color.FromArgb(r, g, b);
|
return (r, g, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
90
API/Services/KoreaderService.cs
Normal file
90
API/Services/KoreaderService.cs
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using API.Data;
|
||||||
|
using API.DTOs.Koreader;
|
||||||
|
using API.DTOs.Progress;
|
||||||
|
using API.Helpers;
|
||||||
|
using API.Helpers.Builders;
|
||||||
|
using Kavita.Common;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace API.Services;
|
||||||
|
|
||||||
|
#nullable enable
|
||||||
|
|
||||||
|
public interface IKoreaderService
|
||||||
|
{
|
||||||
|
Task SaveProgress(KoreaderBookDto koreaderBookDto, int userId);
|
||||||
|
Task<KoreaderBookDto> GetProgress(string bookHash, int userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public class KoreaderService : IKoreaderService
|
||||||
|
{
|
||||||
|
private readonly IReaderService _readerService;
|
||||||
|
private readonly IUnitOfWork _unitOfWork;
|
||||||
|
private readonly ILocalizationService _localizationService;
|
||||||
|
private readonly ILogger<KoreaderService> _logger;
|
||||||
|
|
||||||
|
public KoreaderService(IReaderService readerService, IUnitOfWork unitOfWork, ILocalizationService localizationService, ILogger<KoreaderService> logger)
|
||||||
|
{
|
||||||
|
_readerService = readerService;
|
||||||
|
_unitOfWork = unitOfWork;
|
||||||
|
_localizationService = localizationService;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Given a Koreader hash, locate the underlying file and generate/update a progress event.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="koreaderBookDto"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
public async Task SaveProgress(KoreaderBookDto koreaderBookDto, int userId)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Saving Koreader progress for {UserId}: {KoreaderProgress}", userId, koreaderBookDto.Progress);
|
||||||
|
var file = await _unitOfWork.MangaFileRepository.GetByKoreaderHash(koreaderBookDto.Document);
|
||||||
|
if (file == null) throw new KavitaException(await _localizationService.Translate(userId, "file-missing"));
|
||||||
|
|
||||||
|
var userProgressDto = await _unitOfWork.AppUserProgressRepository.GetUserProgressDtoAsync(file.ChapterId, userId);
|
||||||
|
if (userProgressDto == null)
|
||||||
|
{
|
||||||
|
var chapterDto = await _unitOfWork.ChapterRepository.GetChapterDtoAsync(file.ChapterId);
|
||||||
|
if (chapterDto == null) throw new KavitaException(await _localizationService.Translate(userId, "chapter-doesnt-exist"));
|
||||||
|
|
||||||
|
var volumeDto = await _unitOfWork.VolumeRepository.GetVolumeByIdAsync(chapterDto.VolumeId);
|
||||||
|
if (volumeDto == null) throw new KavitaException(await _localizationService.Translate(userId, "volume-doesnt-exist"));
|
||||||
|
|
||||||
|
userProgressDto = new ProgressDto()
|
||||||
|
{
|
||||||
|
ChapterId = file.ChapterId,
|
||||||
|
VolumeId = chapterDto.VolumeId,
|
||||||
|
SeriesId = volumeDto.SeriesId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Update the bookScrollId if possible
|
||||||
|
KoreaderHelper.UpdateProgressDto(userProgressDto, koreaderBookDto.Progress);
|
||||||
|
|
||||||
|
await _readerService.SaveReadingProgress(userProgressDto, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a Koreader Dto representing current book and the progress within
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bookHash"></param>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public async Task<KoreaderBookDto> GetProgress(string bookHash, int userId)
|
||||||
|
{
|
||||||
|
var settingsDto = await _unitOfWork.SettingsRepository.GetSettingsDtoAsync();
|
||||||
|
|
||||||
|
var file = await _unitOfWork.MangaFileRepository.GetByKoreaderHash(bookHash);
|
||||||
|
|
||||||
|
if (file == null) throw new KavitaException(await _localizationService.Translate(userId, "file-missing"));
|
||||||
|
|
||||||
|
var progressDto = await _unitOfWork.AppUserProgressRepository.GetUserProgressDtoAsync(file.ChapterId, userId);
|
||||||
|
var koreaderProgress = KoreaderHelper.GetKoreaderPosition(progressDto);
|
||||||
|
|
||||||
|
return new KoreaderBookDtoBuilder(bookHash).WithProgress(koreaderProgress)
|
||||||
|
.WithPercentage(progressDto?.PageNum, file.Pages)
|
||||||
|
.WithDeviceId(settingsDto.InstallId, userId)
|
||||||
|
.Build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -200,6 +200,9 @@ public class ExternalMetadataService : IExternalMetadataService
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the match results for a Series from UI Flow
|
/// Returns the match results for a Series from UI Flow
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <remarks>
|
||||||
|
/// Will extract alternative names like Localized name, year will send as ReleaseYear but fallback to Comic Vine syntax if applicable
|
||||||
|
/// </remarks>
|
||||||
/// <param name="dto"></param>
|
/// <param name="dto"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public async Task<IList<ExternalSeriesMatchDto>> MatchSeries(MatchSeriesDto dto)
|
public async Task<IList<ExternalSeriesMatchDto>> MatchSeries(MatchSeriesDto dto)
|
||||||
|
|
@ -212,19 +215,26 @@ public class ExternalMetadataService : IExternalMetadataService
|
||||||
var potentialAnilistId = ScrobblingService.ExtractId<int?>(dto.Query, ScrobblingService.AniListWeblinkWebsite);
|
var potentialAnilistId = ScrobblingService.ExtractId<int?>(dto.Query, ScrobblingService.AniListWeblinkWebsite);
|
||||||
var potentialMalId = ScrobblingService.ExtractId<long?>(dto.Query, ScrobblingService.MalWeblinkWebsite);
|
var potentialMalId = ScrobblingService.ExtractId<long?>(dto.Query, ScrobblingService.MalWeblinkWebsite);
|
||||||
|
|
||||||
List<string> altNames = [series.LocalizedName, series.OriginalName];
|
var format = series.Library.Type.ConvertToPlusMediaFormat(series.Format);
|
||||||
if (potentialAnilistId == null && potentialMalId == null && !string.IsNullOrEmpty(dto.Query))
|
var otherNames = ExtractAlternativeNames(series);
|
||||||
|
|
||||||
|
var year = series.Metadata.ReleaseYear;
|
||||||
|
if (year == 0 && format == PlusMediaFormat.Comic && !string.IsNullOrWhiteSpace(series.Name))
|
||||||
{
|
{
|
||||||
altNames.Add(dto.Query);
|
var potentialYear = Parser.ParseYear(series.Name);
|
||||||
|
if (!string.IsNullOrEmpty(potentialYear))
|
||||||
|
{
|
||||||
|
year = int.Parse(potentialYear);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var matchRequest = new MatchSeriesRequestDto()
|
var matchRequest = new MatchSeriesRequestDto()
|
||||||
{
|
{
|
||||||
Format = series.Library.Type.ConvertToPlusMediaFormat(series.Format),
|
Format = format,
|
||||||
Query = dto.Query,
|
Query = dto.Query,
|
||||||
SeriesName = series.Name,
|
SeriesName = series.Name,
|
||||||
AlternativeNames = altNames.Where(s => !string.IsNullOrEmpty(s)).ToList(),
|
AlternativeNames = otherNames,
|
||||||
Year = series.Metadata.ReleaseYear,
|
Year = year,
|
||||||
AniListId = potentialAnilistId ?? ScrobblingService.GetAniListId(series),
|
AniListId = potentialAnilistId ?? ScrobblingService.GetAniListId(series),
|
||||||
MalId = potentialMalId ?? ScrobblingService.GetMalId(series)
|
MalId = potentialMalId ?? ScrobblingService.GetMalId(series)
|
||||||
};
|
};
|
||||||
|
|
@ -254,6 +264,12 @@ public class ExternalMetadataService : IExternalMetadataService
|
||||||
return ArraySegment<ExternalSeriesMatchDto>.Empty;
|
return ArraySegment<ExternalSeriesMatchDto>.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static List<string> ExtractAlternativeNames(Series series)
|
||||||
|
{
|
||||||
|
List<string> altNames = [series.LocalizedName, series.OriginalName];
|
||||||
|
return altNames.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Retrieves Metadata about a Recommended External Series
|
/// Retrieves Metadata about a Recommended External Series
|
||||||
|
|
|
||||||
|
|
@ -130,22 +130,23 @@ public class LicenseService(
|
||||||
if (cacheValue.HasValue) return cacheValue.Value;
|
if (cacheValue.HasValue) return cacheValue.Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var result = false;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var serverSetting = await unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
|
var serverSetting = await unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
|
||||||
var result = await IsLicenseValid(serverSetting.Value);
|
result = await IsLicenseValid(serverSetting.Value);
|
||||||
await provider.FlushAsync();
|
|
||||||
await provider.SetAsync(CacheKey, result, _licenseCacheTimeout);
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "There was an issue connecting to Kavita+");
|
logger.LogError(ex, "There was an issue connecting to Kavita+");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
await provider.FlushAsync();
|
await provider.FlushAsync();
|
||||||
await provider.SetAsync(CacheKey, false, _licenseCacheTimeout);
|
await provider.SetAsync(CacheKey, result, _licenseCacheTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
|
||||||
|
|
@ -432,6 +432,7 @@ public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService
|
||||||
existingProfile.SwipeToPaginate = dto.SwipeToPaginate;
|
existingProfile.SwipeToPaginate = dto.SwipeToPaginate;
|
||||||
existingProfile.AllowAutomaticWebtoonReaderDetection = dto.AllowAutomaticWebtoonReaderDetection;
|
existingProfile.AllowAutomaticWebtoonReaderDetection = dto.AllowAutomaticWebtoonReaderDetection;
|
||||||
existingProfile.WidthOverride = dto.WidthOverride;
|
existingProfile.WidthOverride = dto.WidthOverride;
|
||||||
|
existingProfile.DisableWidthOverride = dto.DisableWidthOverride;
|
||||||
|
|
||||||
// Book Reader
|
// Book Reader
|
||||||
existingProfile.BookReaderMargin = dto.BookReaderMargin;
|
existingProfile.BookReaderMargin = dto.BookReaderMargin;
|
||||||
|
|
|
||||||
|
|
@ -206,17 +206,12 @@ public class CoverDbService : ICoverDbService
|
||||||
throw new KavitaException($"Could not grab publisher image for {publisherName}");
|
throw new KavitaException($"Could not grab publisher image for {publisherName}");
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogTrace("Fetching publisher image from {Url}", publisherLink.Sanitize());
|
|
||||||
// Download the publisher file using Flurl
|
|
||||||
var publisherStream = await publisherLink
|
|
||||||
.AllowHttpStatus("2xx,304")
|
|
||||||
.GetStreamAsync();
|
|
||||||
|
|
||||||
// Create the destination file path
|
// Create the destination file path
|
||||||
using var image = Image.NewFromStream(publisherStream);
|
|
||||||
var filename = ImageService.GetPublisherFormat(publisherName, encodeFormat);
|
var filename = ImageService.GetPublisherFormat(publisherName, encodeFormat);
|
||||||
|
|
||||||
image.WriteToFile(Path.Combine(_directoryService.PublisherDirectory, filename));
|
_logger.LogTrace("Fetching publisher image from {Url}", publisherLink.Sanitize());
|
||||||
|
await DownloadImageFromUrl(publisherName, encodeFormat, publisherLink, _directoryService.PublisherDirectory);
|
||||||
|
|
||||||
_logger.LogDebug("Publisher image for {PublisherName} downloaded and saved successfully", publisherName.Sanitize());
|
_logger.LogDebug("Publisher image for {PublisherName} downloaded and saved successfully", publisherName.Sanitize());
|
||||||
|
|
||||||
return filename;
|
return filename;
|
||||||
|
|
@ -302,7 +297,27 @@ public class CoverDbService : ICoverDbService
|
||||||
.GetStreamAsync();
|
.GetStreamAsync();
|
||||||
|
|
||||||
using var image = Image.NewFromStream(imageStream);
|
using var image = Image.NewFromStream(imageStream);
|
||||||
image.WriteToFile(targetFile);
|
try
|
||||||
|
{
|
||||||
|
image.WriteToFile(targetFile);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return filename;
|
return filename;
|
||||||
}
|
}
|
||||||
|
|
@ -385,14 +400,13 @@ public class CoverDbService : ICoverDbService
|
||||||
private async Task<string> FallbackToKavitaReaderPublisher(string publisherName)
|
private async Task<string> FallbackToKavitaReaderPublisher(string publisherName)
|
||||||
{
|
{
|
||||||
const string publisherFileName = "publishers.txt";
|
const string publisherFileName = "publishers.txt";
|
||||||
var externalLink = string.Empty;
|
|
||||||
var allOverrides = await GetCachedData(publisherFileName) ??
|
var allOverrides = await GetCachedData(publisherFileName) ??
|
||||||
await $"{NewHost}publishers/{publisherFileName}".GetStringAsync();
|
await $"{NewHost}publishers/{publisherFileName}".GetStringAsync();
|
||||||
|
|
||||||
// Cache immediately
|
// Cache immediately
|
||||||
await CacheDataAsync(publisherFileName, allOverrides);
|
await CacheDataAsync(publisherFileName, allOverrides);
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(allOverrides)) return externalLink;
|
if (string.IsNullOrEmpty(allOverrides)) return string.Empty;
|
||||||
|
|
||||||
var externalFile = allOverrides
|
var externalFile = allOverrides
|
||||||
.Split("\n")
|
.Split("\n")
|
||||||
|
|
@ -415,7 +429,7 @@ public class CoverDbService : ICoverDbService
|
||||||
throw new KavitaException($"Could not grab publisher image for {publisherName}");
|
throw new KavitaException($"Could not grab publisher image for {publisherName}");
|
||||||
}
|
}
|
||||||
|
|
||||||
return $"{NewHost}publishers/{externalLink}";
|
return $"{NewHost}publishers/{externalFile}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task CacheDataAsync(string fileName, string? content)
|
private async Task CacheDataAsync(string fileName, string? content)
|
||||||
|
|
@ -572,8 +586,7 @@ public class CoverDbService : ICoverDbService
|
||||||
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
|
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
|
||||||
if (choseNewImage)
|
if (choseNewImage)
|
||||||
{
|
{
|
||||||
|
// Don't delete the Series cover unless it is an override, otherwise the first chapter will be null
|
||||||
// Don't delete series cover, unless it's an override, otherwise the first chapter cover will be null
|
|
||||||
if (existingPath.Contains(ImageService.GetSeriesFormat(series.Id)))
|
if (existingPath.Contains(ImageService.GetSeriesFormat(series.Id)))
|
||||||
{
|
{
|
||||||
_directoryService.DeleteFiles([existingPath]);
|
_directoryService.DeleteFiles([existingPath]);
|
||||||
|
|
@ -624,6 +637,7 @@ public class CoverDbService : ICoverDbService
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Refactor this to IHasCoverImage instead of a hard entity type
|
||||||
public async Task SetChapterCoverByUrl(Chapter chapter, string url, bool fromBase64 = true, bool chooseBetterImage = false)
|
public async Task SetChapterCoverByUrl(Chapter chapter, string url, bool fromBase64 = true, bool chooseBetterImage = false)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(url))
|
if (!string.IsNullOrEmpty(url))
|
||||||
|
|
|
||||||
|
|
@ -1159,6 +1159,12 @@ public static partial class Parser
|
||||||
return !string.IsNullOrEmpty(name) && SeriesAndYearRegex.IsMatch(name);
|
return !string.IsNullOrEmpty(name) && SeriesAndYearRegex.IsMatch(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parse a Year from a Comic Series: Series Name (YEAR)
|
||||||
|
/// </summary>
|
||||||
|
/// <example>Harley Quinn (2024) returns 2024</example>
|
||||||
|
/// <param name="name"></param>
|
||||||
|
/// <returns></returns>
|
||||||
public static string ParseYear(string? name)
|
public static string ParseYear(string? name)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(name)) return string.Empty;
|
if (string.IsNullOrEmpty(name)) return string.Empty;
|
||||||
|
|
|
||||||
|
|
@ -880,6 +880,8 @@ public class ProcessSeries : IProcessSeries
|
||||||
existingFile.FileName = Parser.Parser.RemoveExtensionIfSupported(existingFile.FilePath);
|
existingFile.FileName = Parser.Parser.RemoveExtensionIfSupported(existingFile.FilePath);
|
||||||
existingFile.FilePath = Parser.Parser.NormalizePath(existingFile.FilePath);
|
existingFile.FilePath = Parser.Parser.NormalizePath(existingFile.FilePath);
|
||||||
existingFile.Bytes = fileInfo.Length;
|
existingFile.Bytes = fileInfo.Length;
|
||||||
|
existingFile.KoreaderHash = KoreaderHelper.HashContents(existingFile.FilePath);
|
||||||
|
|
||||||
// We skip updating DB here with last modified time so that metadata refresh can do it
|
// We skip updating DB here with last modified time so that metadata refresh can do it
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
|
|
@ -888,6 +890,7 @@ public class ProcessSeries : IProcessSeries
|
||||||
var file = new MangaFileBuilder(info.FullFilePath, info.Format, _readingItemService.GetNumberOfPages(info.FullFilePath, info.Format))
|
var file = new MangaFileBuilder(info.FullFilePath, info.Format, _readingItemService.GetNumberOfPages(info.FullFilePath, info.Format))
|
||||||
.WithExtension(fileInfo.Extension)
|
.WithExtension(fileInfo.Extension)
|
||||||
.WithBytes(fileInfo.Length)
|
.WithBytes(fileInfo.Length)
|
||||||
|
.WithHash()
|
||||||
.Build();
|
.Build();
|
||||||
chapter.Files.Add(file);
|
chapter.Files.Add(file);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
<TargetFramework>net9.0</TargetFramework>
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
<Company>kavitareader.com</Company>
|
<Company>kavitareader.com</Company>
|
||||||
<Product>Kavita</Product>
|
<Product>Kavita</Product>
|
||||||
<AssemblyVersion>0.8.6.13</AssemblyVersion>
|
<AssemblyVersion>0.8.6.16</AssemblyVersion>
|
||||||
<NeutralLanguage>en</NeutralLanguage>
|
<NeutralLanguage>en</NeutralLanguage>
|
||||||
<TieredPGO>true</TieredPGO>
|
<TieredPGO>true</TieredPGO>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
|
||||||
|
|
@ -107,13 +107,10 @@ Support this project by becoming a sponsor. Your logo will show up here with a l
|
||||||
## Mega Sponsors
|
## Mega Sponsors
|
||||||
<img src="https://opencollective.com/Kavita/tiers/mega-sponsor.svg?width=890"></a>
|
<img src="https://opencollective.com/Kavita/tiers/mega-sponsor.svg?width=890"></a>
|
||||||
|
|
||||||
## JetBrains
|
## Powered By
|
||||||
Thank you to [<img src="/Logo/jetbrains.svg" alt="" width="32"> JetBrains](http://www.jetbrains.com/) for providing us with free licenses to their great tools.
|
[](https://jb.gg/OpenSource)
|
||||||
|
|
||||||
* [<img src="/Logo/rider.svg" alt="" width="32"> Rider](http://www.jetbrains.com/rider/)
|
|
||||||
|
|
||||||
### License
|
### License
|
||||||
|
|
||||||
* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html)
|
* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html)
|
||||||
* Copyright 2020-2024
|
* Copyright 2020-2024
|
||||||
|
|
||||||
|
|
|
||||||
30
UI/Web/src/_tag-card-common.scss
Normal file
30
UI/Web/src/_tag-card-common.scss
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
.tag-card {
|
||||||
|
background-color: var(--bs-card-color, #2c2c2c);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
|
||||||
|
transition: transform 0.2s ease, background 0.3s ease;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-card:hover {
|
||||||
|
background-color: #3a3a3a;
|
||||||
|
//transform: translateY(-3px); // Cool effect but has a weird background issue. ROBBIE: Fix this
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-name {
|
||||||
|
font-size: 1.1rem;
|
||||||
|
font-weight: 600;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
max-height: 8rem;
|
||||||
|
height: 8rem;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-meta {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
color: var(--text-muted-color, #bbb);
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import {MatchStateOption} from "./match-state-option";
|
import {MatchStateOption} from "./match-state-option";
|
||||||
|
import {LibraryType} from "../library/library";
|
||||||
|
|
||||||
export interface ManageMatchFilter {
|
export interface ManageMatchFilter {
|
||||||
matchStateOption: MatchStateOption;
|
matchStateOption: MatchStateOption;
|
||||||
|
libraryType: LibraryType | -1;
|
||||||
searchTerm: string;
|
searchTerm: string;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,8 @@ export enum LibraryType {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const allLibraryTypes = [LibraryType.Manga, LibraryType.ComicVine, LibraryType.Comic, LibraryType.Book, LibraryType.LightNovel, LibraryType.Images];
|
export const allLibraryTypes = [LibraryType.Manga, LibraryType.ComicVine, LibraryType.Comic, LibraryType.Book, LibraryType.LightNovel, LibraryType.Images];
|
||||||
|
export const allKavitaPlusMetadataApplicableTypes = [LibraryType.Manga, LibraryType.LightNovel, LibraryType.ComicVine, LibraryType.Comic];
|
||||||
|
export const allKavitaPlusScrobbleEligibleTypes = [LibraryType.Manga, LibraryType.LightNovel];
|
||||||
|
|
||||||
export interface Library {
|
export interface Library {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
|
||||||
6
UI/Web/src/app/_models/metadata/browse/browse-genre.ts
Normal file
6
UI/Web/src/app/_models/metadata/browse/browse-genre.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
import {Genre} from "../genre";
|
||||||
|
|
||||||
|
export interface BrowseGenre extends Genre {
|
||||||
|
seriesCount: number;
|
||||||
|
chapterCount: number;
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import {Person} from "../metadata/person";
|
import {Person} from "../person";
|
||||||
|
|
||||||
export interface BrowsePerson extends Person {
|
export interface BrowsePerson extends Person {
|
||||||
seriesCount: number;
|
seriesCount: number;
|
||||||
issueCount: number;
|
chapterCount: number;
|
||||||
}
|
}
|
||||||
6
UI/Web/src/app/_models/metadata/browse/browse-tag.ts
Normal file
6
UI/Web/src/app/_models/metadata/browse/browse-tag.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
import {Tag} from "../../tag";
|
||||||
|
|
||||||
|
export interface BrowseTag extends Tag {
|
||||||
|
seriesCount: number;
|
||||||
|
chapterCount: number;
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,10 @@ export interface Language {
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface KavitaLocale {
|
export interface KavitaLocale {
|
||||||
fileName: string; // isoCode aka what maps to the file on disk and what transloco loads
|
/**
|
||||||
|
* isoCode aka what maps to the file on disk and what transloco loads
|
||||||
|
*/
|
||||||
|
fileName: string;
|
||||||
renderName: string;
|
renderName: string;
|
||||||
translationCompletion: number;
|
translationCompletion: number;
|
||||||
isRtL: boolean;
|
isRtL: boolean;
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ import {IHasCover} from "../common/i-has-cover";
|
||||||
|
|
||||||
export enum PersonRole {
|
export enum PersonRole {
|
||||||
Other = 1,
|
Other = 1,
|
||||||
Artist = 2,
|
|
||||||
Writer = 3,
|
Writer = 3,
|
||||||
Penciller = 4,
|
Penciller = 4,
|
||||||
Inker = 5,
|
Inker = 5,
|
||||||
|
|
@ -32,3 +31,22 @@ export interface Person extends IHasCover {
|
||||||
primaryColor: string;
|
primaryColor: string;
|
||||||
secondaryColor: string;
|
secondaryColor: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Excludes Other as it's not in use
|
||||||
|
*/
|
||||||
|
export const allPeopleRoles = [
|
||||||
|
PersonRole.Writer,
|
||||||
|
PersonRole.Penciller,
|
||||||
|
PersonRole.Inker,
|
||||||
|
PersonRole.Colorist,
|
||||||
|
PersonRole.Letterer,
|
||||||
|
PersonRole.CoverArtist,
|
||||||
|
PersonRole.Editor,
|
||||||
|
PersonRole.Publisher,
|
||||||
|
PersonRole.Character,
|
||||||
|
PersonRole.Translator,
|
||||||
|
PersonRole.Imprint,
|
||||||
|
PersonRole.Team,
|
||||||
|
PersonRole.Location
|
||||||
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import {MangaFormat} from "../manga-format";
|
import {MangaFormat} from "../manga-format";
|
||||||
import {SeriesFilterV2} from "./v2/series-filter-v2";
|
import {FilterV2} from "./v2/filter-v2";
|
||||||
|
|
||||||
export interface FilterItem<T> {
|
export interface FilterItem<T> {
|
||||||
title: string;
|
title: string;
|
||||||
|
|
@ -7,10 +7,6 @@ export interface FilterItem<T> {
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SortOptions {
|
|
||||||
sortField: SortField;
|
|
||||||
isAscending: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum SortField {
|
export enum SortField {
|
||||||
SortName = 1,
|
SortName = 1,
|
||||||
|
|
@ -27,7 +23,7 @@ export enum SortField {
|
||||||
Random = 9
|
Random = 9
|
||||||
}
|
}
|
||||||
|
|
||||||
export const allSortFields = Object.keys(SortField)
|
export const allSeriesSortFields = Object.keys(SortField)
|
||||||
.filter(key => !isNaN(Number(key)) && parseInt(key, 10) >= 0)
|
.filter(key => !isNaN(Number(key)) && parseInt(key, 10) >= 0)
|
||||||
.map(key => parseInt(key, 10)) as SortField[];
|
.map(key => parseInt(key, 10)) as SortField[];
|
||||||
|
|
||||||
|
|
@ -54,8 +50,8 @@ export const mangaFormatFilters = [
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
export interface FilterEvent {
|
export interface FilterEvent<TFilter extends number = number, TSort extends number = number> {
|
||||||
filterV2: SeriesFilterV2;
|
filterV2: FilterV2<TFilter, TSort>;
|
||||||
isFirst: boolean;
|
isFirst: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
import {PersonRole} from "../person";
|
||||||
|
import {PersonSortOptions} from "./sort-options";
|
||||||
|
|
||||||
|
export interface BrowsePersonFilter {
|
||||||
|
roles: Array<PersonRole>;
|
||||||
|
query?: string;
|
||||||
|
sortOptions?: PersonSortOptions;
|
||||||
|
}
|
||||||
|
|
@ -48,7 +48,7 @@ const enumArray = Object.keys(FilterField)
|
||||||
|
|
||||||
enumArray.sort((a, b) => a.value.localeCompare(b.value));
|
enumArray.sort((a, b) => a.value.localeCompare(b.value));
|
||||||
|
|
||||||
export const allFields = enumArray
|
export const allSeriesFilterFields = enumArray
|
||||||
.map(key => parseInt(key.key, 10))as FilterField[];
|
.map(key => parseInt(key.key, 10))as FilterField[];
|
||||||
|
|
||||||
export const allPeople = [
|
export const allPeople = [
|
||||||
|
|
@ -66,7 +66,6 @@ export const allPeople = [
|
||||||
|
|
||||||
export const personRoleForFilterField = (role: PersonRole) => {
|
export const personRoleForFilterField = (role: PersonRole) => {
|
||||||
switch (role) {
|
switch (role) {
|
||||||
case PersonRole.Artist: return FilterField.CoverArtist;
|
|
||||||
case PersonRole.Character: return FilterField.Characters;
|
case PersonRole.Character: return FilterField.Characters;
|
||||||
case PersonRole.Colorist: return FilterField.Colorist;
|
case PersonRole.Colorist: return FilterField.Colorist;
|
||||||
case PersonRole.CoverArtist: return FilterField.CoverArtist;
|
case PersonRole.CoverArtist: return FilterField.CoverArtist;
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
import { FilterComparison } from "./filter-comparison";
|
import {FilterComparison} from "./filter-comparison";
|
||||||
import { FilterField } from "./filter-field";
|
|
||||||
|
|
||||||
export interface FilterStatement {
|
export interface FilterStatement<T extends number = number> {
|
||||||
comparison: FilterComparison;
|
comparison: FilterComparison;
|
||||||
field: FilterField;
|
field: T;
|
||||||
value: string;
|
value: string;
|
||||||
}
|
}
|
||||||
11
UI/Web/src/app/_models/metadata/v2/filter-v2.ts
Normal file
11
UI/Web/src/app/_models/metadata/v2/filter-v2.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
import {FilterStatement} from "./filter-statement";
|
||||||
|
import {FilterCombination} from "./filter-combination";
|
||||||
|
import {SortOptions} from "./sort-options";
|
||||||
|
|
||||||
|
export interface FilterV2<TFilter extends number = number, TSort extends number = number> {
|
||||||
|
name?: string;
|
||||||
|
statements: Array<FilterStatement<TFilter>>;
|
||||||
|
combination: FilterCombination;
|
||||||
|
sortOptions?: SortOptions<TSort>;
|
||||||
|
limitTo: number;
|
||||||
|
}
|
||||||
12
UI/Web/src/app/_models/metadata/v2/person-filter-field.ts
Normal file
12
UI/Web/src/app/_models/metadata/v2/person-filter-field.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
export enum PersonFilterField {
|
||||||
|
Role = 1,
|
||||||
|
Name = 2,
|
||||||
|
SeriesCount = 3,
|
||||||
|
ChapterCount = 4,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export const allPersonFilterFields = Object.keys(PersonFilterField)
|
||||||
|
.filter(key => !isNaN(Number(key)) && parseInt(key, 10) >= 0)
|
||||||
|
.map(key => parseInt(key, 10)) as PersonFilterField[];
|
||||||
|
|
||||||
9
UI/Web/src/app/_models/metadata/v2/person-sort-field.ts
Normal file
9
UI/Web/src/app/_models/metadata/v2/person-sort-field.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
export enum PersonSortField {
|
||||||
|
Name = 1,
|
||||||
|
SeriesCount = 2,
|
||||||
|
ChapterCount = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
export const allPersonSortFields = Object.keys(PersonSortField)
|
||||||
|
.filter(key => !isNaN(Number(key)) && parseInt(key, 10) >= 0)
|
||||||
|
.map(key => parseInt(key, 10)) as PersonSortField[];
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
import { SortOptions } from "../series-filter";
|
|
||||||
import {FilterStatement} from "./filter-statement";
|
|
||||||
import {FilterCombination} from "./filter-combination";
|
|
||||||
|
|
||||||
export interface SeriesFilterV2 {
|
|
||||||
name?: string;
|
|
||||||
statements: Array<FilterStatement>;
|
|
||||||
combination: FilterCombination;
|
|
||||||
sortOptions?: SortOptions;
|
|
||||||
limitTo: number;
|
|
||||||
}
|
|
||||||
17
UI/Web/src/app/_models/metadata/v2/sort-options.ts
Normal file
17
UI/Web/src/app/_models/metadata/v2/sort-options.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
import {PersonSortField} from "./person-sort-field";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Series-based Sort options
|
||||||
|
*/
|
||||||
|
export interface SortOptions<TSort extends number = number> {
|
||||||
|
sortField: TSort;
|
||||||
|
isAscending: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Person-based Sort Options
|
||||||
|
*/
|
||||||
|
export interface PersonSortOptions {
|
||||||
|
sortField: PersonSortField;
|
||||||
|
isAscending: boolean;
|
||||||
|
}
|
||||||
|
|
@ -12,6 +12,7 @@ import {PdfLayoutMode} from "./pdf-layout-mode";
|
||||||
import {PdfSpreadMode} from "./pdf-spread-mode";
|
import {PdfSpreadMode} from "./pdf-spread-mode";
|
||||||
import {Series} from "../series";
|
import {Series} from "../series";
|
||||||
import {Library} from "../library/library";
|
import {Library} from "../library/library";
|
||||||
|
import {UserBreakpoint} from "../../shared/_services/utility.service";
|
||||||
|
|
||||||
export enum ReadingProfileKind {
|
export enum ReadingProfileKind {
|
||||||
Default = 0,
|
Default = 0,
|
||||||
|
|
@ -39,6 +40,7 @@ export interface ReadingProfile {
|
||||||
swipeToPaginate: boolean;
|
swipeToPaginate: boolean;
|
||||||
allowAutomaticWebtoonReaderDetection: boolean;
|
allowAutomaticWebtoonReaderDetection: boolean;
|
||||||
widthOverride?: number;
|
widthOverride?: number;
|
||||||
|
disableWidthOverride: UserBreakpoint;
|
||||||
|
|
||||||
// Book Reader
|
// Book Reader
|
||||||
bookReaderMargin: number;
|
bookReaderMargin: number;
|
||||||
|
|
@ -75,3 +77,4 @@ export const pdfLayoutModes = [{text: 'pdf-multiple', value: PdfLayoutMode.Multi
|
||||||
export const pdfScrollModes = [{text: 'pdf-vertical', value: PdfScrollMode.Vertical}, {text: 'pdf-horizontal', value: PdfScrollMode.Horizontal}, {text: 'pdf-page', value: PdfScrollMode.Page}];
|
export const pdfScrollModes = [{text: 'pdf-vertical', value: PdfScrollMode.Vertical}, {text: 'pdf-horizontal', value: PdfScrollMode.Horizontal}, {text: 'pdf-page', value: PdfScrollMode.Page}];
|
||||||
export const pdfSpreadModes = [{text: 'pdf-none', value: PdfSpreadMode.None}, {text: 'pdf-odd', value: PdfSpreadMode.Odd}, {text: 'pdf-even', value: PdfSpreadMode.Even}];
|
export const pdfSpreadModes = [{text: 'pdf-none', value: PdfSpreadMode.None}, {text: 'pdf-odd', value: PdfSpreadMode.Odd}, {text: 'pdf-even', value: PdfSpreadMode.Even}];
|
||||||
export const pdfThemes = [{text: 'pdf-light', value: PdfTheme.Light}, {text: 'pdf-dark', value: PdfTheme.Dark}];
|
export const pdfThemes = [{text: 'pdf-light', value: PdfTheme.Light}, {text: 'pdf-dark', value: PdfTheme.Dark}];
|
||||||
|
export const breakPoints = [UserBreakpoint.Never, UserBreakpoint.Mobile, UserBreakpoint.Tablet, UserBreakpoint.Desktop]
|
||||||
|
|
|
||||||
|
|
@ -20,5 +20,6 @@ export enum WikiLink {
|
||||||
UpdateNative = 'https://wiki.kavitareader.com/guides/updating/updating-native',
|
UpdateNative = 'https://wiki.kavitareader.com/guides/updating/updating-native',
|
||||||
UpdateDocker = 'https://wiki.kavitareader.com/guides/updating/updating-docker',
|
UpdateDocker = 'https://wiki.kavitareader.com/guides/updating/updating-docker',
|
||||||
OpdsClients = 'https://wiki.kavitareader.com/guides/features/opds/#opds-capable-clients',
|
OpdsClients = 'https://wiki.kavitareader.com/guides/features/opds/#opds-capable-clients',
|
||||||
Guides = 'https://wiki.kavitareader.com/guides'
|
Guides = 'https://wiki.kavitareader.com/guides',
|
||||||
|
ReadingProfiles = "https://wiki.kavitareader.com/guides/user-settings/reading-profiles/",
|
||||||
}
|
}
|
||||||
|
|
|
||||||
25
UI/Web/src/app/_pipes/breakpoint.pipe.ts
Normal file
25
UI/Web/src/app/_pipes/breakpoint.pipe.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import {Pipe, PipeTransform} from '@angular/core';
|
||||||
|
import {translate} from "@jsverse/transloco";
|
||||||
|
import {UserBreakpoint} from "../shared/_services/utility.service";
|
||||||
|
|
||||||
|
@Pipe({
|
||||||
|
name: 'breakpoint'
|
||||||
|
})
|
||||||
|
export class BreakpointPipe implements PipeTransform {
|
||||||
|
|
||||||
|
transform(value: UserBreakpoint): string {
|
||||||
|
const v = parseInt(value + '', 10) as UserBreakpoint;
|
||||||
|
switch (v) {
|
||||||
|
case UserBreakpoint.Never:
|
||||||
|
return translate('breakpoint-pipe.never');
|
||||||
|
case UserBreakpoint.Mobile:
|
||||||
|
return translate('breakpoint-pipe.mobile');
|
||||||
|
case UserBreakpoint.Tablet:
|
||||||
|
return translate('breakpoint-pipe.tablet');
|
||||||
|
case UserBreakpoint.Desktop:
|
||||||
|
return translate('breakpoint-pipe.desktop');
|
||||||
|
}
|
||||||
|
throw new Error("unknown breakpoint value: " + value);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
78
UI/Web/src/app/_pipes/browse-title.pipe.ts
Normal file
78
UI/Web/src/app/_pipes/browse-title.pipe.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
import {Pipe, PipeTransform} from '@angular/core';
|
||||||
|
import {FilterField} from "../_models/metadata/v2/filter-field";
|
||||||
|
import {translate} from "@jsverse/transloco";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Responsible for taking a filter field and value (as a string) and translating into a "Browse X" heading for All Series page
|
||||||
|
* Example: Genre & "Action" -> Browse Action
|
||||||
|
* Example: Artist & "Joe Shmo" -> Browse Joe Shmo Works
|
||||||
|
*/
|
||||||
|
@Pipe({
|
||||||
|
name: 'browseTitle'
|
||||||
|
})
|
||||||
|
export class BrowseTitlePipe implements PipeTransform {
|
||||||
|
|
||||||
|
transform(field: FilterField, value: string): string {
|
||||||
|
switch (field) {
|
||||||
|
case FilterField.PublicationStatus:
|
||||||
|
return translate('browse-title-pipe.publication-status', {value});
|
||||||
|
case FilterField.AgeRating:
|
||||||
|
return translate('browse-title-pipe.age-rating', {value});
|
||||||
|
case FilterField.UserRating:
|
||||||
|
return translate('browse-title-pipe.user-rating', {value});
|
||||||
|
case FilterField.Tags:
|
||||||
|
return translate('browse-title-pipe.tag', {value});
|
||||||
|
case FilterField.Translators:
|
||||||
|
return translate('browse-title-pipe.translator', {value});
|
||||||
|
case FilterField.Characters:
|
||||||
|
return translate('browse-title-pipe.character', {value});
|
||||||
|
case FilterField.Publisher:
|
||||||
|
return translate('browse-title-pipe.publisher', {value});
|
||||||
|
case FilterField.Editor:
|
||||||
|
return translate('browse-title-pipe.editor', {value});
|
||||||
|
case FilterField.CoverArtist:
|
||||||
|
return translate('browse-title-pipe.artist', {value});
|
||||||
|
case FilterField.Letterer:
|
||||||
|
return translate('browse-title-pipe.letterer', {value});
|
||||||
|
case FilterField.Colorist:
|
||||||
|
return translate('browse-title-pipe.colorist', {value});
|
||||||
|
case FilterField.Inker:
|
||||||
|
return translate('browse-title-pipe.inker', {value});
|
||||||
|
case FilterField.Penciller:
|
||||||
|
return translate('browse-title-pipe.penciller', {value});
|
||||||
|
case FilterField.Writers:
|
||||||
|
return translate('browse-title-pipe.writer', {value});
|
||||||
|
case FilterField.Genres:
|
||||||
|
return translate('browse-title-pipe.genre', {value});
|
||||||
|
case FilterField.Libraries:
|
||||||
|
return translate('browse-title-pipe.library', {value});
|
||||||
|
case FilterField.Formats:
|
||||||
|
return translate('browse-title-pipe.format', {value});
|
||||||
|
case FilterField.ReleaseYear:
|
||||||
|
return translate('browse-title-pipe.release-year', {value});
|
||||||
|
case FilterField.Imprint:
|
||||||
|
return translate('browse-title-pipe.imprint', {value});
|
||||||
|
case FilterField.Team:
|
||||||
|
return translate('browse-title-pipe.team', {value});
|
||||||
|
case FilterField.Location:
|
||||||
|
return translate('browse-title-pipe.location', {value});
|
||||||
|
|
||||||
|
// These have no natural links in the app to demand a richer title experience
|
||||||
|
case FilterField.Languages:
|
||||||
|
case FilterField.CollectionTags:
|
||||||
|
case FilterField.ReadProgress:
|
||||||
|
case FilterField.ReadTime:
|
||||||
|
case FilterField.Path:
|
||||||
|
case FilterField.FilePath:
|
||||||
|
case FilterField.WantToRead:
|
||||||
|
case FilterField.ReadingDate:
|
||||||
|
case FilterField.AverageRating:
|
||||||
|
case FilterField.ReadLast:
|
||||||
|
case FilterField.Summary:
|
||||||
|
case FilterField.SeriesName:
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
108
UI/Web/src/app/_pipes/generic-filter-field.pipe.ts
Normal file
108
UI/Web/src/app/_pipes/generic-filter-field.pipe.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
import {Pipe, PipeTransform} from '@angular/core';
|
||||||
|
import {FilterField} from "../_models/metadata/v2/filter-field";
|
||||||
|
import {translate} from "@jsverse/transloco";
|
||||||
|
import {ValidFilterEntity} from "../metadata-filter/filter-settings";
|
||||||
|
import {PersonFilterField} from "../_models/metadata/v2/person-filter-field";
|
||||||
|
|
||||||
|
@Pipe({
|
||||||
|
name: 'genericFilterField'
|
||||||
|
})
|
||||||
|
export class GenericFilterFieldPipe implements PipeTransform {
|
||||||
|
|
||||||
|
transform<T extends number>(value: T, entityType: ValidFilterEntity): string {
|
||||||
|
|
||||||
|
switch (entityType) {
|
||||||
|
case "series":
|
||||||
|
return this.translateFilterField(value as FilterField);
|
||||||
|
case "person":
|
||||||
|
return this.translatePersonFilterField(value as PersonFilterField);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private translatePersonFilterField(value: PersonFilterField) {
|
||||||
|
switch (value) {
|
||||||
|
case PersonFilterField.Role:
|
||||||
|
return translate('generic-filter-field-pipe.person-role');
|
||||||
|
case PersonFilterField.Name:
|
||||||
|
return translate('generic-filter-field-pipe.person-name');
|
||||||
|
case PersonFilterField.SeriesCount:
|
||||||
|
return translate('generic-filter-field-pipe.person-series-count');
|
||||||
|
case PersonFilterField.ChapterCount:
|
||||||
|
return translate('generic-filter-field-pipe.person-chapter-count');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private translateFilterField(value: FilterField) {
|
||||||
|
switch (value) {
|
||||||
|
case FilterField.AgeRating:
|
||||||
|
return translate('filter-field-pipe.age-rating');
|
||||||
|
case FilterField.Characters:
|
||||||
|
return translate('filter-field-pipe.characters');
|
||||||
|
case FilterField.CollectionTags:
|
||||||
|
return translate('filter-field-pipe.collection-tags');
|
||||||
|
case FilterField.Colorist:
|
||||||
|
return translate('filter-field-pipe.colorist');
|
||||||
|
case FilterField.CoverArtist:
|
||||||
|
return translate('filter-field-pipe.cover-artist');
|
||||||
|
case FilterField.Editor:
|
||||||
|
return translate('filter-field-pipe.editor');
|
||||||
|
case FilterField.Formats:
|
||||||
|
return translate('filter-field-pipe.formats');
|
||||||
|
case FilterField.Genres:
|
||||||
|
return translate('filter-field-pipe.genres');
|
||||||
|
case FilterField.Inker:
|
||||||
|
return translate('filter-field-pipe.inker');
|
||||||
|
case FilterField.Imprint:
|
||||||
|
return translate('filter-field-pipe.imprint');
|
||||||
|
case FilterField.Team:
|
||||||
|
return translate('filter-field-pipe.team');
|
||||||
|
case FilterField.Location:
|
||||||
|
return translate('filter-field-pipe.location');
|
||||||
|
case FilterField.Languages:
|
||||||
|
return translate('filter-field-pipe.languages');
|
||||||
|
case FilterField.Libraries:
|
||||||
|
return translate('filter-field-pipe.libraries');
|
||||||
|
case FilterField.Letterer:
|
||||||
|
return translate('filter-field-pipe.letterer');
|
||||||
|
case FilterField.PublicationStatus:
|
||||||
|
return translate('filter-field-pipe.publication-status');
|
||||||
|
case FilterField.Penciller:
|
||||||
|
return translate('filter-field-pipe.penciller');
|
||||||
|
case FilterField.Publisher:
|
||||||
|
return translate('filter-field-pipe.publisher');
|
||||||
|
case FilterField.ReadProgress:
|
||||||
|
return translate('filter-field-pipe.read-progress');
|
||||||
|
case FilterField.ReadTime:
|
||||||
|
return translate('filter-field-pipe.read-time');
|
||||||
|
case FilterField.ReleaseYear:
|
||||||
|
return translate('filter-field-pipe.release-year');
|
||||||
|
case FilterField.SeriesName:
|
||||||
|
return translate('filter-field-pipe.series-name');
|
||||||
|
case FilterField.Summary:
|
||||||
|
return translate('filter-field-pipe.summary');
|
||||||
|
case FilterField.Tags:
|
||||||
|
return translate('filter-field-pipe.tags');
|
||||||
|
case FilterField.Translators:
|
||||||
|
return translate('filter-field-pipe.translators');
|
||||||
|
case FilterField.UserRating:
|
||||||
|
return translate('filter-field-pipe.user-rating');
|
||||||
|
case FilterField.Writers:
|
||||||
|
return translate('filter-field-pipe.writers');
|
||||||
|
case FilterField.Path:
|
||||||
|
return translate('filter-field-pipe.path');
|
||||||
|
case FilterField.FilePath:
|
||||||
|
return translate('filter-field-pipe.file-path');
|
||||||
|
case FilterField.WantToRead:
|
||||||
|
return translate('filter-field-pipe.want-to-read');
|
||||||
|
case FilterField.ReadingDate:
|
||||||
|
return translate('filter-field-pipe.read-date');
|
||||||
|
case FilterField.ReadLast:
|
||||||
|
return translate('filter-field-pipe.read-last');
|
||||||
|
case FilterField.AverageRating:
|
||||||
|
return translate('filter-field-pipe.average-rating');
|
||||||
|
default:
|
||||||
|
throw new Error(`Invalid FilterField value: ${value}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import {inject, Pipe, PipeTransform} from '@angular/core';
|
import {Pipe, PipeTransform} from '@angular/core';
|
||||||
import { PersonRole } from '../_models/metadata/person';
|
import {PersonRole} from '../_models/metadata/person';
|
||||||
import {translate, TranslocoService} from "@jsverse/transloco";
|
import {translate} from "@jsverse/transloco";
|
||||||
|
|
||||||
@Pipe({
|
@Pipe({
|
||||||
name: 'personRole',
|
name: 'personRole',
|
||||||
|
|
@ -10,8 +10,6 @@ export class PersonRolePipe implements PipeTransform {
|
||||||
|
|
||||||
transform(value: PersonRole): string {
|
transform(value: PersonRole): string {
|
||||||
switch (value) {
|
switch (value) {
|
||||||
case PersonRole.Artist:
|
|
||||||
return translate('person-role-pipe.artist');
|
|
||||||
case PersonRole.Character:
|
case PersonRole.Character:
|
||||||
return translate('person-role-pipe.character');
|
return translate('person-role-pipe.character');
|
||||||
case PersonRole.Colorist:
|
case PersonRole.Colorist:
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,8 @@
|
||||||
import { Pipe, PipeTransform } from '@angular/core';
|
import {Pipe, PipeTransform} from '@angular/core';
|
||||||
import {SortField} from "../_models/metadata/series-filter";
|
import {SortField} from "../_models/metadata/series-filter";
|
||||||
import {TranslocoService} from "@jsverse/transloco";
|
import {TranslocoService} from "@jsverse/transloco";
|
||||||
|
import {ValidFilterEntity} from "../metadata-filter/filter-settings";
|
||||||
|
import {PersonSortField} from "../_models/metadata/v2/person-sort-field";
|
||||||
|
|
||||||
@Pipe({
|
@Pipe({
|
||||||
name: 'sortField',
|
name: 'sortField',
|
||||||
|
|
@ -11,7 +13,30 @@ export class SortFieldPipe implements PipeTransform {
|
||||||
constructor(private translocoService: TranslocoService) {
|
constructor(private translocoService: TranslocoService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
transform(value: SortField): string {
|
transform<T extends number>(value: T, entityType: ValidFilterEntity): string {
|
||||||
|
|
||||||
|
switch (entityType) {
|
||||||
|
case 'series':
|
||||||
|
return this.seriesSortFields(value as SortField);
|
||||||
|
case 'person':
|
||||||
|
return this.personSortFields(value as PersonSortField);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private personSortFields(value: PersonSortField) {
|
||||||
|
switch (value) {
|
||||||
|
case PersonSortField.Name:
|
||||||
|
return this.translocoService.translate('sort-field-pipe.person-name');
|
||||||
|
case PersonSortField.SeriesCount:
|
||||||
|
return this.translocoService.translate('sort-field-pipe.person-series-count');
|
||||||
|
case PersonSortField.ChapterCount:
|
||||||
|
return this.translocoService.translate('sort-field-pipe.person-chapter-count');
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private seriesSortFields(value: SortField) {
|
||||||
switch (value) {
|
switch (value) {
|
||||||
case SortField.SortName:
|
case SortField.SortName:
|
||||||
return this.translocoService.translate('sort-field-pipe.sort-name');
|
return this.translocoService.translate('sort-field-pipe.sort-name');
|
||||||
|
|
@ -32,7 +57,6 @@ export class SortFieldPipe implements PipeTransform {
|
||||||
case SortField.Random:
|
case SortField.Random:
|
||||||
return this.translocoService.translate('sort-field-pipe.random');
|
return this.translocoService.translate('sort-field-pipe.random');
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
22
UI/Web/src/app/_resolvers/url-filter.resolver.ts
Normal file
22
UI/Web/src/app/_resolvers/url-filter.resolver.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
import {Injectable} from "@angular/core";
|
||||||
|
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from "@angular/router";
|
||||||
|
import {Observable, of} from "rxjs";
|
||||||
|
import {FilterV2} from "../_models/metadata/v2/filter-v2";
|
||||||
|
import {FilterUtilitiesService} from "../shared/_services/filter-utilities.service";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks the url for a filter and resolves one if applicable, otherwise returns null.
|
||||||
|
* It is up to the consumer to cast appropriately.
|
||||||
|
*/
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class UrlFilterResolver implements Resolve<any> {
|
||||||
|
|
||||||
|
constructor(private filterUtilitiesService: FilterUtilitiesService) {}
|
||||||
|
|
||||||
|
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<FilterV2 | null> {
|
||||||
|
if (!state.url.includes('?')) return of(null);
|
||||||
|
return this.filterUtilitiesService.decodeFilter(state.url.split('?')[1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,13 @@
|
||||||
import { Routes } from "@angular/router";
|
import {Routes} from "@angular/router";
|
||||||
import { AllSeriesComponent } from "../all-series/_components/all-series/all-series.component";
|
import {AllSeriesComponent} from "../all-series/_components/all-series/all-series.component";
|
||||||
|
import {UrlFilterResolver} from "../_resolvers/url-filter.resolver";
|
||||||
|
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{path: '', component: AllSeriesComponent, pathMatch: 'full'},
|
{path: '', component: AllSeriesComponent, pathMatch: 'full',
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
resolve: {
|
||||||
|
filter: UrlFilterResolver
|
||||||
|
}
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,12 @@
|
||||||
import { Routes } from "@angular/router";
|
import {Routes} from "@angular/router";
|
||||||
import { BookmarksComponent } from "../bookmark/_components/bookmarks/bookmarks.component";
|
import {BookmarksComponent} from "../bookmark/_components/bookmarks/bookmarks.component";
|
||||||
|
import {UrlFilterResolver} from "../_resolvers/url-filter.resolver";
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{path: '', component: BookmarksComponent, pathMatch: 'full'},
|
{path: '', component: BookmarksComponent, pathMatch: 'full',
|
||||||
|
resolve: {
|
||||||
|
filter: UrlFilterResolver
|
||||||
|
},
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
import { Routes } from "@angular/router";
|
|
||||||
import { AllSeriesComponent } from "../all-series/_components/all-series/all-series.component";
|
|
||||||
import {BrowseAuthorsComponent} from "../browse-people/browse-authors.component";
|
|
||||||
|
|
||||||
|
|
||||||
export const routes: Routes = [
|
|
||||||
{path: '', component: BrowseAuthorsComponent, pathMatch: 'full'},
|
|
||||||
];
|
|
||||||
24
UI/Web/src/app/_routes/browse-routing.module.ts
Normal file
24
UI/Web/src/app/_routes/browse-routing.module.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
import {Routes} from "@angular/router";
|
||||||
|
import {BrowsePeopleComponent} from "../browse/browse-people/browse-people.component";
|
||||||
|
import {BrowseGenresComponent} from "../browse/browse-genres/browse-genres.component";
|
||||||
|
import {BrowseTagsComponent} from "../browse/browse-tags/browse-tags.component";
|
||||||
|
import {UrlFilterResolver} from "../_resolvers/url-filter.resolver";
|
||||||
|
|
||||||
|
|
||||||
|
export const routes: Routes = [
|
||||||
|
// Legacy route
|
||||||
|
{path: 'authors', component: BrowsePeopleComponent, pathMatch: 'full',
|
||||||
|
resolve: {
|
||||||
|
filter: UrlFilterResolver
|
||||||
|
},
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
},
|
||||||
|
{path: 'people', component: BrowsePeopleComponent, pathMatch: 'full',
|
||||||
|
resolve: {
|
||||||
|
filter: UrlFilterResolver
|
||||||
|
},
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
},
|
||||||
|
{path: 'genres', component: BrowseGenresComponent, pathMatch: 'full'},
|
||||||
|
{path: 'tags', component: BrowseTagsComponent, pathMatch: 'full'},
|
||||||
|
];
|
||||||
|
|
@ -1,9 +1,15 @@
|
||||||
import { Routes } from '@angular/router';
|
import {Routes} from '@angular/router';
|
||||||
import { AllCollectionsComponent } from '../collections/_components/all-collections/all-collections.component';
|
import {AllCollectionsComponent} from '../collections/_components/all-collections/all-collections.component';
|
||||||
import { CollectionDetailComponent } from '../collections/_components/collection-detail/collection-detail.component';
|
import {CollectionDetailComponent} from '../collections/_components/collection-detail/collection-detail.component';
|
||||||
|
import {UrlFilterResolver} from "../_resolvers/url-filter.resolver";
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{path: '', component: AllCollectionsComponent, pathMatch: 'full'},
|
{path: '', component: AllCollectionsComponent, pathMatch: 'full'},
|
||||||
{path: ':id', component: CollectionDetailComponent},
|
{path: ':id', component: CollectionDetailComponent,
|
||||||
|
resolve: {
|
||||||
|
filter: UrlFilterResolver
|
||||||
|
},
|
||||||
|
runGuardsAndResolvers: 'always',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue