Merged develop in
This commit is contained in:
commit
2af01b654d
256 changed files with 17954 additions and 3884 deletions
124
API.Tests/Helpers/RandfHelper.cs
Normal file
124
API.Tests/Helpers/RandfHelper.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
namespace API.Tests.Helpers;
|
||||
|
||||
public class RandfHelper
|
||||
{
|
||||
private static readonly Random Random = new ();
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if all simple fields are equal
|
||||
/// </summary>
|
||||
/// <param name="obj1"></param>
|
||||
/// <param name="obj2"></param>
|
||||
/// <param name="ignoreFields">fields to ignore, note that the names are very weird sometimes</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentNullException"></exception>
|
||||
/// <exception cref="ArgumentException"></exception>
|
||||
public static bool AreSimpleFieldsEqual(object obj1, object obj2, IList<string> ignoreFields)
|
||||
{
|
||||
if (obj1 == null || obj2 == null)
|
||||
throw new ArgumentNullException("Neither object can be null.");
|
||||
|
||||
Type type1 = obj1.GetType();
|
||||
Type type2 = obj2.GetType();
|
||||
|
||||
if (type1 != type2)
|
||||
throw new ArgumentException("Objects must be of the same type.");
|
||||
|
||||
FieldInfo[] fields = type1.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
if (field.IsInitOnly) continue;
|
||||
if (ignoreFields.Contains(field.Name)) continue;
|
||||
|
||||
Type fieldType = field.FieldType;
|
||||
|
||||
if (IsRelevantType(fieldType))
|
||||
{
|
||||
object value1 = field.GetValue(obj1);
|
||||
object value2 = field.GetValue(obj2);
|
||||
|
||||
if (!Equals(value1, value2))
|
||||
{
|
||||
throw new ArgumentException("Fields must be of the same type: " + field.Name + " was " + value1 + " and " + value2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsRelevantType(Type type)
|
||||
{
|
||||
return type.IsPrimitive
|
||||
|| type == typeof(string)
|
||||
|| type.IsEnum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets all simple fields of the given object to a random value
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <remarks>Simple is, primitive, string, or enum</remarks>
|
||||
/// <exception cref="ArgumentNullException"></exception>
|
||||
public static void SetRandomValues(object obj)
|
||||
{
|
||||
if (obj == null) throw new ArgumentNullException(nameof(obj));
|
||||
|
||||
Type type = obj.GetType();
|
||||
FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
if (field.IsInitOnly) continue; // Skip readonly fields
|
||||
|
||||
object value = GenerateRandomValue(field.FieldType);
|
||||
if (value != null)
|
||||
{
|
||||
field.SetValue(obj, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static object GenerateRandomValue(Type type)
|
||||
{
|
||||
if (type == typeof(int))
|
||||
return Random.Next();
|
||||
if (type == typeof(float))
|
||||
return (float)Random.NextDouble() * 100;
|
||||
if (type == typeof(double))
|
||||
return Random.NextDouble() * 100;
|
||||
if (type == typeof(bool))
|
||||
return Random.Next(2) == 1;
|
||||
if (type == typeof(char))
|
||||
return (char)Random.Next('A', 'Z' + 1);
|
||||
if (type == typeof(byte))
|
||||
return (byte)Random.Next(0, 256);
|
||||
if (type == typeof(short))
|
||||
return (short)Random.Next(short.MinValue, short.MaxValue);
|
||||
if (type == typeof(long))
|
||||
return (long)(Random.NextDouble() * long.MaxValue);
|
||||
if (type == typeof(string))
|
||||
return GenerateRandomString(10);
|
||||
if (type.IsEnum)
|
||||
{
|
||||
var values = Enum.GetValues(type);
|
||||
return values.GetValue(Random.Next(values.Length));
|
||||
}
|
||||
|
||||
// Unsupported type
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string GenerateRandomString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
return new string(Enumerable.Repeat(chars, length)
|
||||
.Select(s => s[Random.Next(s.Length)]).ToArray());
|
||||
}
|
||||
}
|
||||
|
|
@ -161,10 +161,10 @@ public class ImageServiceTests
|
|||
|
||||
private static void GenerateColorImage(string hexColor, string outputPath)
|
||||
{
|
||||
var color = ImageService.HexToRgb(hexColor);
|
||||
using var colorImage = Image.Black(200, 100);
|
||||
using var output = colorImage + new[] { color.R / 255.0, color.G / 255.0, color.B / 255.0 };
|
||||
output.WriteToFile(outputPath);
|
||||
var (r, g, b) = ImageService.HexToRgb(hexColor);
|
||||
using var blackImage = Image.Black(200, 100);
|
||||
using var colorImage = blackImage.NewFromImage(r, g, b);
|
||||
colorImage.WriteToFile(outputPath);
|
||||
}
|
||||
|
||||
private void GenerateHtmlFileForColorScape()
|
||||
|
|
|
|||
561
API.Tests/Services/ReadingProfileServiceTest.cs
Normal file
561
API.Tests/Services/ReadingProfileServiceTest.cs
Normal file
|
|
@ -0,0 +1,561 @@
|
|||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.Data.Repositories;
|
||||
using API.DTOs;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Helpers.Builders;
|
||||
using API.Services;
|
||||
using API.Tests.Helpers;
|
||||
using Kavita.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace API.Tests.Services;
|
||||
|
||||
public class ReadingProfileServiceTest: AbstractDbTest
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Does not add a default reading profile
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async Task<(ReadingProfileService, AppUser, Library, Series)> Setup()
|
||||
{
|
||||
var user = new AppUserBuilder("amelia", "amelia@localhost").Build();
|
||||
Context.AppUser.Add(user);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var series = new SeriesBuilder("Spice and Wolf").Build();
|
||||
|
||||
var library = new LibraryBuilder("Manga")
|
||||
.WithSeries(series)
|
||||
.Build();
|
||||
|
||||
user.Libraries.Add(library);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var rps = new ReadingProfileService(UnitOfWork, Substitute.For<ILocalizationService>(), Mapper);
|
||||
user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.UserPreferences);
|
||||
|
||||
return (rps, user, library, series);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ImplicitProfileFirst()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, library, series) = await Setup();
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithKind(ReadingProfileKind.Implicit)
|
||||
.WithSeries(series)
|
||||
.WithName("Implicit Profile")
|
||||
.Build();
|
||||
|
||||
var profile2 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Non-implicit Profile")
|
||||
.Build();
|
||||
|
||||
user.ReadingProfiles.Add(profile);
|
||||
user.ReadingProfiles.Add(profile2);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal("Implicit Profile", seriesProfile.Name);
|
||||
|
||||
// Find parent
|
||||
seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id, true);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal("Non-implicit Profile", seriesProfile.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CantDeleteDefaultReadingProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, _, _) = await Setup();
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithKind(ReadingProfileKind.Default)
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await Assert.ThrowsAsync<KavitaException>(async () =>
|
||||
{
|
||||
await rps.DeleteReadingProfile(user.Id, profile.Id);
|
||||
});
|
||||
|
||||
var profile2 = new AppUserReadingProfileBuilder(user.Id).Build();
|
||||
Context.AppUserReadingProfiles.Add(profile2);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.DeleteReadingProfile(user.Id, profile2.Id);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var allProfiles = await Context.AppUserReadingProfiles.ToListAsync();
|
||||
Assert.Single(allProfiles);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateImplicitSeriesReadingProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, _, series) = await Setup();
|
||||
|
||||
var dto = new UserReadingProfileDto
|
||||
{
|
||||
ReaderMode = ReaderMode.Webtoon,
|
||||
ScalingOption = ScalingOption.FitToHeight,
|
||||
WidthOverride = 53,
|
||||
};
|
||||
|
||||
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
|
||||
|
||||
var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Contains(profile.SeriesIds, s => s == series.Id);
|
||||
Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateImplicitReadingProfile_DoesNotCreateNew()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, _, series) = await Setup();
|
||||
|
||||
var dto = new UserReadingProfileDto
|
||||
{
|
||||
ReaderMode = ReaderMode.Webtoon,
|
||||
ScalingOption = ScalingOption.FitToHeight,
|
||||
WidthOverride = 53,
|
||||
};
|
||||
|
||||
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
|
||||
|
||||
var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Contains(profile.SeriesIds, s => s == series.Id);
|
||||
Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
|
||||
|
||||
dto = new UserReadingProfileDto
|
||||
{
|
||||
ReaderMode = ReaderMode.LeftRight,
|
||||
};
|
||||
|
||||
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
|
||||
profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Contains(profile.SeriesIds, s => s == series.Id);
|
||||
Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
|
||||
Assert.Equal(ReaderMode.LeftRight, profile.ReaderMode);
|
||||
|
||||
var implicitCount = await Context.AppUserReadingProfiles
|
||||
.Where(p => p.Kind == ReadingProfileKind.Implicit)
|
||||
.CountAsync();
|
||||
Assert.Equal(1, implicitCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCorrectProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Series Specific")
|
||||
.Build();
|
||||
var profile2 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithLibrary(lib)
|
||||
.WithName("Library Specific")
|
||||
.Build();
|
||||
var profile3 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithKind(ReadingProfileKind.Default)
|
||||
.WithName("Global")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
Context.AppUserReadingProfiles.Add(profile2);
|
||||
Context.AppUserReadingProfiles.Add(profile3);
|
||||
|
||||
var series2 = new SeriesBuilder("Rainbows After Storms").Build();
|
||||
lib.Series.Add(series2);
|
||||
|
||||
var lib2 = new LibraryBuilder("Manga2").Build();
|
||||
var series3 = new SeriesBuilder("A Tropical Fish Yearns for Snow").Build();
|
||||
lib2.Series.Add(series3);
|
||||
|
||||
user.Libraries.Add(lib2);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var p = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(p);
|
||||
Assert.Equal("Series Specific", p.Name);
|
||||
|
||||
p = await rps.GetReadingProfileDtoForSeries(user.Id, series2.Id);
|
||||
Assert.NotNull(p);
|
||||
Assert.Equal("Library Specific", p.Name);
|
||||
|
||||
p = await rps.GetReadingProfileDtoForSeries(user.Id, series3.Id);
|
||||
Assert.NotNull(p);
|
||||
Assert.Equal("Global", p.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReplaceReadingProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var profile1 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Profile 1")
|
||||
.Build();
|
||||
|
||||
var profile2 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("Profile 2")
|
||||
.Build();
|
||||
|
||||
Context.AppUserReadingProfiles.Add(profile1);
|
||||
Context.AppUserReadingProfiles.Add(profile2);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var profile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Equal("Profile 1", profile.Name);
|
||||
|
||||
await rps.AddProfileToSeries(user.Id, profile2.Id, series.Id);
|
||||
profile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(profile);
|
||||
Assert.Equal("Profile 2", profile.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteReadingProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var profile1 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Profile 1")
|
||||
.Build();
|
||||
|
||||
Context.AppUserReadingProfiles.Add(profile1);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.ClearSeriesProfile(user.Id, series.Id);
|
||||
var profiles = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
|
||||
Assert.DoesNotContain(profiles, rp => rp.SeriesIds.Contains(series.Id));
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BulkAddReadingProfiles()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var generatedSeries = new SeriesBuilder($"Generated Series #{i}").Build();
|
||||
lib.Series.Add(generatedSeries);
|
||||
}
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Profile")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
|
||||
var profile2 = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Profile2")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile2);
|
||||
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var someSeriesIds = lib.Series.Take(lib.Series.Count / 2).Select(s => s.Id).ToList();
|
||||
await rps.BulkAddProfileToSeries(user.Id, profile.Id, someSeriesIds);
|
||||
|
||||
foreach (var id in someSeriesIds)
|
||||
{
|
||||
var foundProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
|
||||
Assert.NotNull(foundProfile);
|
||||
Assert.Equal(profile.Id, foundProfile.Id);
|
||||
}
|
||||
|
||||
var allIds = lib.Series.Select(s => s.Id).ToList();
|
||||
await rps.BulkAddProfileToSeries(user.Id, profile2.Id, allIds);
|
||||
|
||||
foreach (var id in allIds)
|
||||
{
|
||||
var foundProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
|
||||
Assert.NotNull(foundProfile);
|
||||
Assert.Equal(profile2.Id, foundProfile.Id);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BulkAssignDeletesImplicit()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var implicitProfile = Mapper.Map<UserReadingProfileDto>(new AppUserReadingProfileBuilder(user.Id)
|
||||
.Build());
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("Profile 1")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
var generatedSeries = new SeriesBuilder($"Generated Series #{i}").Build();
|
||||
lib.Series.Add(generatedSeries);
|
||||
}
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var ids = lib.Series.Select(s => s.Id).ToList();
|
||||
|
||||
foreach (var id in ids)
|
||||
{
|
||||
await rps.UpdateImplicitReadingProfile(user.Id, id, implicitProfile);
|
||||
var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal(ReadingProfileKind.Implicit, seriesProfile.Kind);
|
||||
}
|
||||
|
||||
await rps.BulkAddProfileToSeries(user.Id, profile.Id, ids);
|
||||
|
||||
foreach (var id in ids)
|
||||
{
|
||||
var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal(ReadingProfileKind.User, seriesProfile.Kind);
|
||||
}
|
||||
|
||||
var implicitCount = await Context.AppUserReadingProfiles
|
||||
.Where(p => p.Kind == ReadingProfileKind.Implicit)
|
||||
.CountAsync();
|
||||
Assert.Equal(0, implicitCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddDeletesImplicit()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var implicitProfile = Mapper.Map<UserReadingProfileDto>(new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithKind(ReadingProfileKind.Implicit)
|
||||
.Build());
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("Profile 1")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, implicitProfile);
|
||||
|
||||
var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal(ReadingProfileKind.Implicit, seriesProfile.Kind);
|
||||
|
||||
await rps.AddProfileToSeries(user.Id, profile.Id, series.Id);
|
||||
|
||||
seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
|
||||
Assert.NotNull(seriesProfile);
|
||||
Assert.Equal(ReadingProfileKind.User, seriesProfile.Kind);
|
||||
|
||||
var implicitCount = await Context.AppUserReadingProfiles
|
||||
.Where(p => p.Kind == ReadingProfileKind.Implicit)
|
||||
.CountAsync();
|
||||
Assert.Equal(0, implicitCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateReadingProfile()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, series) = await Setup();
|
||||
|
||||
var dto = new UserReadingProfileDto
|
||||
{
|
||||
Name = "Profile 1",
|
||||
ReaderMode = ReaderMode.LeftRight,
|
||||
EmulateBook = false,
|
||||
};
|
||||
|
||||
await rps.CreateReadingProfile(user.Id, dto);
|
||||
|
||||
var dto2 = new UserReadingProfileDto
|
||||
{
|
||||
Name = "Profile 2",
|
||||
ReaderMode = ReaderMode.LeftRight,
|
||||
EmulateBook = false,
|
||||
};
|
||||
|
||||
await rps.CreateReadingProfile(user.Id, dto2);
|
||||
|
||||
var dto3 = new UserReadingProfileDto
|
||||
{
|
||||
Name = "Profile 1", // Not unique name
|
||||
ReaderMode = ReaderMode.LeftRight,
|
||||
EmulateBook = false,
|
||||
};
|
||||
|
||||
await Assert.ThrowsAsync<KavitaException>(async () =>
|
||||
{
|
||||
await rps.CreateReadingProfile(user.Id, dto3);
|
||||
});
|
||||
|
||||
var allProfiles = Context.AppUserReadingProfiles.ToList();
|
||||
Assert.Equal(2, allProfiles.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearSeriesProfile_RemovesImplicitAndUnlinksExplicit()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, _, series) = await Setup();
|
||||
|
||||
var implicitProfile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithKind(ReadingProfileKind.Implicit)
|
||||
.WithName("Implicit Profile")
|
||||
.Build();
|
||||
|
||||
var explicitProfile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithSeries(series)
|
||||
.WithName("Explicit Profile")
|
||||
.Build();
|
||||
|
||||
Context.AppUserReadingProfiles.Add(implicitProfile);
|
||||
Context.AppUserReadingProfiles.Add(explicitProfile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var allBefore = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
|
||||
Assert.Equal(2, allBefore.Count(rp => rp.SeriesIds.Contains(series.Id)));
|
||||
|
||||
await rps.ClearSeriesProfile(user.Id, series.Id);
|
||||
|
||||
var remainingProfiles = await Context.AppUserReadingProfiles.ToListAsync();
|
||||
Assert.Single(remainingProfiles);
|
||||
Assert.Equal("Explicit Profile", remainingProfiles[0].Name);
|
||||
Assert.Empty(remainingProfiles[0].SeriesIds);
|
||||
|
||||
var profilesForSeries = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
|
||||
Assert.DoesNotContain(profilesForSeries, rp => rp.SeriesIds.Contains(series.Id));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddProfileToLibrary_AddsAndOverridesExisting()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, _) = await Setup();
|
||||
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("Library Profile")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(profile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.AddProfileToLibrary(user.Id, profile.Id, lib.Id);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
var linkedProfile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
|
||||
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
|
||||
Assert.NotNull(linkedProfile);
|
||||
Assert.Equal(profile.Id, linkedProfile.Id);
|
||||
|
||||
var newProfile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("New Profile")
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(newProfile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.AddProfileToLibrary(user.Id, newProfile.Id, lib.Id);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
linkedProfile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
|
||||
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
|
||||
Assert.NotNull(linkedProfile);
|
||||
Assert.Equal(newProfile.Id, linkedProfile.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearLibraryProfile_RemovesImplicitOrUnlinksExplicit()
|
||||
{
|
||||
await ResetDb();
|
||||
var (rps, user, lib, _) = await Setup();
|
||||
|
||||
var implicitProfile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithKind(ReadingProfileKind.Implicit)
|
||||
.WithLibrary(lib)
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(implicitProfile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.ClearLibraryProfile(user.Id, lib.Id);
|
||||
var profile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
|
||||
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
|
||||
Assert.Null(profile);
|
||||
|
||||
var explicitProfile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithLibrary(lib)
|
||||
.Build();
|
||||
Context.AppUserReadingProfiles.Add(explicitProfile);
|
||||
await UnitOfWork.CommitAsync();
|
||||
|
||||
await rps.ClearLibraryProfile(user.Id, lib.Id);
|
||||
profile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
|
||||
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
|
||||
Assert.Null(profile);
|
||||
|
||||
var stillExists = await Context.AppUserReadingProfiles.FindAsync(explicitProfile.Id);
|
||||
Assert.NotNull(stillExists);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// As response to #3793, I'm not sure if we want to keep this. It's not the most nice. But I think the idea of this test
|
||||
/// is worth having.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void UpdateFields_UpdatesAll()
|
||||
{
|
||||
// Repeat to ensure booleans are flipped and actually tested
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
var profile = new AppUserReadingProfile();
|
||||
var dto = new UserReadingProfileDto();
|
||||
|
||||
RandfHelper.SetRandomValues(profile);
|
||||
RandfHelper.SetRandomValues(dto);
|
||||
|
||||
ReadingProfileService.UpdateReaderProfileFields(profile, dto);
|
||||
|
||||
var newDto = Mapper.Map<UserReadingProfileDto>(profile);
|
||||
|
||||
Assert.True(RandfHelper.AreSimpleFieldsEqual(dto, newDto,
|
||||
["<Id>k__BackingField", "<UserId>k__BackingField"]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected override async Task ResetDb()
|
||||
{
|
||||
Context.AppUserReadingProfiles.RemoveRange(Context.AppUserReadingProfiles);
|
||||
await UnitOfWork.CommitAsync();
|
||||
}
|
||||
}
|
||||
|
|
@ -97,9 +97,9 @@
|
|||
</PackageReference>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
|
||||
<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.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="YamlDotNet" Version="16.3.0" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -153,6 +153,9 @@ public class AccountController : BaseApiController
|
|||
// Assign default streams
|
||||
AddDefaultStreamsToUser(user);
|
||||
|
||||
// Assign default reading profile
|
||||
await AddDefaultReadingProfileToUser(user);
|
||||
|
||||
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
if (string.IsNullOrEmpty(token)) return BadRequest(await _localizationService.Get("en", "confirm-token-gen"));
|
||||
if (!await ConfirmEmailToken(token, user)) return BadRequest(await _localizationService.Get("en", "validate-email", token));
|
||||
|
|
@ -609,7 +612,7 @@ public class AccountController : BaseApiController
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests the Invite Url for the UserId. Will return error if user is already validated.
|
||||
/// Requests the Invite Url for the AppUserId. Will return error if user is already validated.
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="withBaseUrl">Include the "https://ip:port/" in the generated link</param>
|
||||
|
|
@ -669,6 +672,9 @@ public class AccountController : BaseApiController
|
|||
// Assign default streams
|
||||
AddDefaultStreamsToUser(user);
|
||||
|
||||
// Assign default reading profile
|
||||
await AddDefaultReadingProfileToUser(user);
|
||||
|
||||
// Assign Roles
|
||||
var roles = dto.Roles;
|
||||
var hasAdminRole = dto.Roles.Contains(PolicyConstants.AdminRole);
|
||||
|
|
@ -779,6 +785,16 @@ public class AccountController : BaseApiController
|
|||
}
|
||||
}
|
||||
|
||||
private async Task AddDefaultReadingProfileToUser(AppUser user)
|
||||
{
|
||||
var profile = new AppUserReadingProfileBuilder(user.Id)
|
||||
.WithName("Default Profile")
|
||||
.WithKind(ReadingProfileKind.Default)
|
||||
.Build();
|
||||
_unitOfWork.AppUserReadingProfileRepository.Add(profile);
|
||||
await _unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Last step in authentication flow, confirms the email token for email
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -6,8 +6,10 @@ using System.Threading.Tasks;
|
|||
using API.Constants;
|
||||
using API.Data;
|
||||
using API.Data.Repositories;
|
||||
using API.DTOs;
|
||||
using API.DTOs.Filtering;
|
||||
using API.DTOs.Metadata;
|
||||
using API.DTOs.Metadata.Browse;
|
||||
using API.DTOs.Person;
|
||||
using API.DTOs.Recommendation;
|
||||
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));
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// Fetches people from the instance by role
|
||||
/// </summary>
|
||||
|
|
@ -95,6 +113,22 @@ public class MetadataController(IUnitOfWork unitOfWork, ILocalizationService loc
|
|||
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>
|
||||
/// Fetches all age ratings from the instance
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ using System.Threading.Tasks;
|
|||
using API.Data;
|
||||
using API.Data.Repositories;
|
||||
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.Entities.Enums;
|
||||
using API.Extensions;
|
||||
|
|
@ -77,11 +80,13 @@ public class PersonController : BaseApiController
|
|||
/// <param name="userParams"></param>
|
||||
/// <returns></returns>
|
||||
[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;
|
||||
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);
|
||||
|
||||
return Ok(list);
|
||||
}
|
||||
|
||||
|
|
@ -112,6 +117,7 @@ public class PersonController : BaseApiController
|
|||
|
||||
|
||||
person.Name = dto.Name?.Trim();
|
||||
person.NormalizedName = person.Name.ToNormalized();
|
||||
person.Description = dto.Description ?? string.Empty;
|
||||
person.CoverImageLocked = dto.CoverImageLocked;
|
||||
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ public class PluginController(IUnitOfWork unitOfWork, ITokenService tokenService
|
|||
throw new KavitaUnauthenticatedUserException();
|
||||
}
|
||||
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId);
|
||||
logger.LogInformation("Plugin {PluginName} has authenticated with {UserName} ({UserId})'s API Key", pluginName.Replace(Environment.NewLine, string.Empty), user!.UserName, userId);
|
||||
logger.LogInformation("Plugin {PluginName} has authenticated with {UserName} ({AppUserId})'s API Key", pluginName.Replace(Environment.NewLine, string.Empty), user!.UserName, userId);
|
||||
|
||||
return new UserDto
|
||||
{
|
||||
|
|
|
|||
198
API/Controllers/ReadingProfileController.cs
Normal file
198
API/Controllers/ReadingProfileController.cs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.Data;
|
||||
using API.Data.Repositories;
|
||||
using API.DTOs;
|
||||
using API.Extensions;
|
||||
using API.Services;
|
||||
using AutoMapper;
|
||||
using Kavita.Common;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace API.Controllers;
|
||||
|
||||
[Route("api/reading-profile")]
|
||||
public class ReadingProfileController(ILogger<ReadingProfileController> logger, IUnitOfWork unitOfWork,
|
||||
IReadingProfileService readingProfileService): BaseApiController
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Gets all non-implicit reading profiles for a user
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpGet("all")]
|
||||
public async Task<ActionResult<IList<UserReadingProfileDto>>> GetAllReadingProfiles()
|
||||
{
|
||||
return Ok(await unitOfWork.AppUserReadingProfileRepository.GetProfilesDtoForUser(User.GetUserId(), true));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the ReadingProfile that should be applied to the given series, walks up the tree.
|
||||
/// Series -> Library -> Default
|
||||
/// </summary>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="skipImplicit"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("{seriesId:int}")]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> GetProfileForSeries(int seriesId, [FromQuery] bool skipImplicit)
|
||||
{
|
||||
return Ok(await readingProfileService.GetReadingProfileDtoForSeries(User.GetUserId(), seriesId, skipImplicit));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the (potential) Reading Profile bound to the library
|
||||
/// </summary>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("library")]
|
||||
public async Task<ActionResult<UserReadingProfileDto?>> GetProfileForLibrary(int libraryId)
|
||||
{
|
||||
return Ok(await readingProfileService.GetReadingProfileDtoForLibrary(User.GetUserId(), libraryId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new reading profile for the current user
|
||||
/// </summary>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("create")]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> CreateReadingProfile([FromBody] UserReadingProfileDto dto)
|
||||
{
|
||||
return Ok(await readingProfileService.CreateReadingProfile(User.GetUserId(), dto));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Promotes the implicit profile to a user profile. Removes the series from other profiles
|
||||
/// </summary>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("promote")]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> PromoteImplicitReadingProfile([FromQuery] int profileId)
|
||||
{
|
||||
return Ok(await readingProfileService.PromoteImplicitProfile(User.GetUserId(), profileId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Update the implicit reading profile for a series, creates one if none exists
|
||||
/// </summary>
|
||||
/// <remarks>Any modification to the reader settings during reading will create an implicit profile. Use "update-parent" to save to the bound series profile.</remarks>
|
||||
/// <param name="dto"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("series")]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> UpdateReadingProfileForSeries([FromBody] UserReadingProfileDto dto, [FromQuery] int seriesId)
|
||||
{
|
||||
var updatedProfile = await readingProfileService.UpdateImplicitReadingProfile(User.GetUserId(), seriesId, dto);
|
||||
return Ok(updatedProfile);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the non-implicit reading profile for the given series, and removes implicit profiles
|
||||
/// </summary>
|
||||
/// <param name="dto"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("update-parent")]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> UpdateParentProfileForSeries([FromBody] UserReadingProfileDto dto, [FromQuery] int seriesId)
|
||||
{
|
||||
var newParentProfile = await readingProfileService.UpdateParent(User.GetUserId(), seriesId, dto);
|
||||
return Ok(newParentProfile);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the given reading profile, must belong to the current user
|
||||
/// </summary>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns>The updated reading profile</returns>
|
||||
/// <remarks>
|
||||
/// This does not update connected series and libraries.
|
||||
/// </remarks>
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<UserReadingProfileDto>> UpdateReadingProfile(UserReadingProfileDto dto)
|
||||
{
|
||||
return Ok(await readingProfileService.UpdateReadingProfile(User.GetUserId(), dto));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the given profile, requires the profile to belong to the logged-in user
|
||||
/// </summary>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="KavitaException"></exception>
|
||||
/// <exception cref="UnauthorizedAccessException"></exception>
|
||||
[HttpDelete]
|
||||
public async Task<IActionResult> DeleteReadingProfile([FromQuery] int profileId)
|
||||
{
|
||||
await readingProfileService.DeleteReadingProfile(User.GetUserId(), profileId);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the reading profile for a given series, removes the old one
|
||||
/// </summary>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("series/{seriesId:int}")]
|
||||
public async Task<IActionResult> AddProfileToSeries(int seriesId, [FromQuery] int profileId)
|
||||
{
|
||||
await readingProfileService.AddProfileToSeries(User.GetUserId(), profileId, seriesId);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the reading profile for the given series for the currently logged-in user
|
||||
/// </summary>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete("series/{seriesId:int}")]
|
||||
public async Task<IActionResult> ClearSeriesProfile(int seriesId)
|
||||
{
|
||||
await readingProfileService.ClearSeriesProfile(User.GetUserId(), seriesId);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the reading profile for a given library, removes the old one
|
||||
/// </summary>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("library/{libraryId:int}")]
|
||||
public async Task<IActionResult> AddProfileToLibrary(int libraryId, [FromQuery] int profileId)
|
||||
{
|
||||
await readingProfileService.AddProfileToLibrary(User.GetUserId(), profileId, libraryId);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the reading profile for the given library for the currently logged-in user
|
||||
/// </summary>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
[HttpDelete("library/{libraryId:int}")]
|
||||
public async Task<IActionResult> ClearLibraryProfile(int libraryId)
|
||||
{
|
||||
await readingProfileService.ClearLibraryProfile(User.GetUserId(), libraryId);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assigns the reading profile to all passes series, and deletes their implicit profiles
|
||||
/// </summary>
|
||||
/// <param name="profileId"></param>
|
||||
/// <param name="seriesIds"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("bulk")]
|
||||
public async Task<IActionResult> BulkAddReadingProfile([FromQuery] int profileId, [FromBody] IList<int> seriesIds)
|
||||
{
|
||||
await readingProfileService.BulkAddProfileToSeries(User.GetUserId(), profileId, seriesIds);
|
||||
return Ok();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -310,7 +310,7 @@ public class SeriesController : BaseApiController
|
|||
/// </summary>
|
||||
/// <param name="filterDto"></param>
|
||||
/// <param name="userParams"></param>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <param name="libraryId">This is not in use</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("all-v2")]
|
||||
public async Task<ActionResult<IEnumerable<SeriesDto>>> GetAllSeriesV2(FilterV2Dto filterDto, [FromQuery] UserParams userParams,
|
||||
|
|
@ -321,8 +321,6 @@ public class SeriesController : BaseApiController
|
|||
await _unitOfWork.SeriesRepository.GetSeriesDtoForLibraryIdV2Async(userId, userParams, filterDto, context);
|
||||
|
||||
// Apply progress/rating information (I can't work out how to do this in initial query)
|
||||
if (series == null) return BadRequest(await _localizationService.Translate(User.GetUserId(), "no-series"));
|
||||
|
||||
await _unitOfWork.SeriesRepository.AddSeriesModifiers(userId, series);
|
||||
|
||||
Response.AddPaginationHeader(series.CurrentPage, series.PageSize, series.TotalCount, series.TotalPages);
|
||||
|
|
|
|||
|
|
@ -103,38 +103,13 @@ public class UsersController : BaseApiController
|
|||
|
||||
var existingPreferences = user!.UserPreferences;
|
||||
|
||||
existingPreferences.ReadingDirection = preferencesDto.ReadingDirection;
|
||||
existingPreferences.ScalingOption = preferencesDto.ScalingOption;
|
||||
existingPreferences.PageSplitOption = preferencesDto.PageSplitOption;
|
||||
existingPreferences.AutoCloseMenu = preferencesDto.AutoCloseMenu;
|
||||
existingPreferences.ShowScreenHints = preferencesDto.ShowScreenHints;
|
||||
existingPreferences.EmulateBook = preferencesDto.EmulateBook;
|
||||
existingPreferences.ReaderMode = preferencesDto.ReaderMode;
|
||||
existingPreferences.LayoutMode = preferencesDto.LayoutMode;
|
||||
existingPreferences.BackgroundColor = string.IsNullOrEmpty(preferencesDto.BackgroundColor) ? "#000000" : preferencesDto.BackgroundColor;
|
||||
existingPreferences.BookReaderMargin = preferencesDto.BookReaderMargin;
|
||||
existingPreferences.BookReaderLineSpacing = preferencesDto.BookReaderLineSpacing;
|
||||
existingPreferences.BookReaderFontFamily = preferencesDto.BookReaderFontFamily;
|
||||
existingPreferences.BookReaderFontSize = preferencesDto.BookReaderFontSize;
|
||||
existingPreferences.BookReaderTapToPaginate = preferencesDto.BookReaderTapToPaginate;
|
||||
existingPreferences.BookReaderReadingDirection = preferencesDto.BookReaderReadingDirection;
|
||||
existingPreferences.BookReaderWritingStyle = preferencesDto.BookReaderWritingStyle;
|
||||
existingPreferences.BookThemeName = preferencesDto.BookReaderThemeName;
|
||||
existingPreferences.BookReaderLayoutMode = preferencesDto.BookReaderLayoutMode;
|
||||
existingPreferences.BookReaderImmersiveMode = preferencesDto.BookReaderImmersiveMode;
|
||||
existingPreferences.GlobalPageLayoutMode = preferencesDto.GlobalPageLayoutMode;
|
||||
existingPreferences.BlurUnreadSummaries = preferencesDto.BlurUnreadSummaries;
|
||||
existingPreferences.LayoutMode = preferencesDto.LayoutMode;
|
||||
existingPreferences.PromptForDownloadSize = preferencesDto.PromptForDownloadSize;
|
||||
existingPreferences.NoTransitions = preferencesDto.NoTransitions;
|
||||
existingPreferences.SwipeToPaginate = preferencesDto.SwipeToPaginate;
|
||||
existingPreferences.CollapseSeriesRelationships = preferencesDto.CollapseSeriesRelationships;
|
||||
existingPreferences.ShareReviews = preferencesDto.ShareReviews;
|
||||
|
||||
existingPreferences.PdfTheme = preferencesDto.PdfTheme;
|
||||
existingPreferences.PdfScrollMode = preferencesDto.PdfScrollMode;
|
||||
existingPreferences.PdfSpreadMode = preferencesDto.PdfSpreadMode;
|
||||
|
||||
if (await _licenseService.HasActiveLicense())
|
||||
{
|
||||
existingPreferences.AniListScrobblingEnabled = preferencesDto.AniListScrobblingEnabled;
|
||||
|
|
|
|||
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 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
|
||||
/// </summary>
|
||||
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
|
||||
{
|
||||
|
|
@ -6,3 +8,10 @@ public sealed record FilterStatementDto
|
|||
public FilterField Field { 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
|
||||
/// </summary>
|
||||
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 SortOptions? SortOptions { get; set; }
|
||||
|
||||
|
|
|
|||
|
|
@ -15,5 +15,9 @@ public enum MatchStateOption
|
|||
public sealed record ManageMatchFilterDto
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
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;
|
||||
|
||||
namespace API.DTOs;
|
||||
namespace API.DTOs.Metadata.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// Used to browse writers and click in to see their series
|
||||
|
|
@ -12,7 +12,7 @@ public class BrowsePersonDto : PersonDto
|
|||
/// </summary>
|
||||
public int SeriesCount { get; set; }
|
||||
/// <summary>
|
||||
/// Number or Issues this Person is the Writer for
|
||||
/// Number of Issues this Person is the Writer for
|
||||
/// </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;
|
||||
|
||||
public sealed record GenreTagDto
|
||||
public record GenreTagDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public required string Title { get; set; }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
namespace API.DTOs.Metadata;
|
||||
|
||||
public sealed record TagDto
|
||||
public record TagDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public required string Title { get; set; }
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@ public sealed record ReadingListDto : IHasCoverImage
|
|||
/// </summary>
|
||||
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()
|
||||
{
|
||||
PrimaryColor = string.Empty;
|
||||
|
|
|
|||
|
|
@ -9,61 +9,6 @@ namespace API.DTOs;
|
|||
|
||||
public sealed record UserPreferencesDto
|
||||
{
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.ReadingDirection"/>
|
||||
[Required]
|
||||
public ReadingDirection ReadingDirection { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.ScalingOption"/>
|
||||
[Required]
|
||||
public ScalingOption ScalingOption { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.PageSplitOption"/>
|
||||
[Required]
|
||||
public PageSplitOption PageSplitOption { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.ReaderMode"/>
|
||||
[Required]
|
||||
public ReaderMode ReaderMode { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.LayoutMode"/>
|
||||
[Required]
|
||||
public LayoutMode LayoutMode { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.EmulateBook"/>
|
||||
[Required]
|
||||
public bool EmulateBook { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BackgroundColor"/>
|
||||
[Required]
|
||||
public string BackgroundColor { get; set; } = "#000000";
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.SwipeToPaginate"/>
|
||||
[Required]
|
||||
public bool SwipeToPaginate { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.AutoCloseMenu"/>
|
||||
[Required]
|
||||
public bool AutoCloseMenu { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.ShowScreenHints"/>
|
||||
[Required]
|
||||
public bool ShowScreenHints { get; set; } = true;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.AllowAutomaticWebtoonReaderDetection"/>
|
||||
[Required]
|
||||
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderMargin"/>
|
||||
[Required]
|
||||
public int BookReaderMargin { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderLineSpacing"/>
|
||||
[Required]
|
||||
public int BookReaderLineSpacing { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderFontSize"/>
|
||||
[Required]
|
||||
public int BookReaderFontSize { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderFontFamily"/>
|
||||
[Required]
|
||||
public string BookReaderFontFamily { get; set; } = null!;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderTapToPaginate"/>
|
||||
[Required]
|
||||
public bool BookReaderTapToPaginate { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderReadingDirection"/>
|
||||
[Required]
|
||||
public ReadingDirection BookReaderReadingDirection { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderWritingStyle"/>
|
||||
[Required]
|
||||
public WritingStyle BookReaderWritingStyle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// UI Site Global Setting: The UI theme the user should use.
|
||||
|
|
@ -72,15 +17,6 @@ public sealed record UserPreferencesDto
|
|||
[Required]
|
||||
public SiteThemeDto? Theme { get; set; }
|
||||
|
||||
[Required] public string BookReaderThemeName { get; set; } = null!;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderLayoutMode"/>
|
||||
[Required]
|
||||
public BookPageLayoutMode BookReaderLayoutMode { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderImmersiveMode"/>
|
||||
[Required]
|
||||
public bool BookReaderImmersiveMode { get; set; } = false;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.GlobalPageLayoutMode"/>
|
||||
[Required]
|
||||
public PageLayoutMode GlobalPageLayoutMode { get; set; } = PageLayoutMode.Cards;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.BlurUnreadSummaries"/>
|
||||
[Required]
|
||||
|
|
@ -101,16 +37,6 @@ public sealed record UserPreferencesDto
|
|||
[Required]
|
||||
public string Locale { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfTheme"/>
|
||||
[Required]
|
||||
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfScrollMode"/>
|
||||
[Required]
|
||||
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfSpreadMode"/>
|
||||
[Required]
|
||||
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.AniListScrobblingEnabled"/>
|
||||
public bool AniListScrobblingEnabled { get; set; }
|
||||
/// <inheritdoc cref="API.Entities.AppUserPreferences.WantToReadSync"/>
|
||||
|
|
|
|||
132
API/DTOs/UserReadingProfileDto.cs
Normal file
132
API/DTOs/UserReadingProfileDto.cs
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Enums.UserPreferences;
|
||||
|
||||
namespace API.DTOs;
|
||||
|
||||
public sealed record UserReadingProfileDto
|
||||
{
|
||||
|
||||
public int Id { get; set; }
|
||||
public int UserId { get; init; }
|
||||
|
||||
public string Name { get; init; }
|
||||
public ReadingProfileKind Kind { get; init; }
|
||||
|
||||
#region MangaReader
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ReadingDirection"/>
|
||||
[Required]
|
||||
public ReadingDirection ReadingDirection { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ScalingOption"/>
|
||||
[Required]
|
||||
public ScalingOption ScalingOption { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PageSplitOption"/>
|
||||
[Required]
|
||||
public PageSplitOption PageSplitOption { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ReaderMode"/>
|
||||
[Required]
|
||||
public ReaderMode ReaderMode { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.AutoCloseMenu"/>
|
||||
[Required]
|
||||
public bool AutoCloseMenu { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ShowScreenHints"/>
|
||||
[Required]
|
||||
public bool ShowScreenHints { get; set; } = true;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.EmulateBook"/>
|
||||
[Required]
|
||||
public bool EmulateBook { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.LayoutMode"/>
|
||||
[Required]
|
||||
public LayoutMode LayoutMode { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BackgroundColor"/>
|
||||
[Required]
|
||||
public string BackgroundColor { get; set; } = "#000000";
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.SwipeToPaginate"/>
|
||||
[Required]
|
||||
public bool SwipeToPaginate { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.AllowAutomaticWebtoonReaderDetection"/>
|
||||
[Required]
|
||||
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
|
||||
|
||||
/// <inheritdoc cref="AppUserReadingProfile.WidthOverride"/>
|
||||
public int? WidthOverride { get; set; }
|
||||
|
||||
/// <inheritdoc cref="AppUserReadingProfile.DisableWidthOverride"/>
|
||||
public BreakPoint DisableWidthOverride { get; set; } = BreakPoint.Never;
|
||||
|
||||
#endregion
|
||||
|
||||
#region EpubReader
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderMargin"/>
|
||||
[Required]
|
||||
public int BookReaderMargin { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderLineSpacing"/>
|
||||
[Required]
|
||||
public int BookReaderLineSpacing { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderFontSize"/>
|
||||
[Required]
|
||||
public int BookReaderFontSize { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderFontFamily"/>
|
||||
[Required]
|
||||
public string BookReaderFontFamily { get; set; } = null!;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderTapToPaginate"/>
|
||||
[Required]
|
||||
public bool BookReaderTapToPaginate { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderReadingDirection"/>
|
||||
[Required]
|
||||
public ReadingDirection BookReaderReadingDirection { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderWritingStyle"/>
|
||||
[Required]
|
||||
public WritingStyle BookReaderWritingStyle { get; set; }
|
||||
|
||||
/// <inheritdoc cref="AppUserReadingProfile.BookThemeName"/>
|
||||
[Required]
|
||||
public string BookReaderThemeName { get; set; } = null!;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderLayoutMode"/>
|
||||
[Required]
|
||||
public BookPageLayoutMode BookReaderLayoutMode { get; set; }
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderImmersiveMode"/>
|
||||
[Required]
|
||||
public bool BookReaderImmersiveMode { get; set; } = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region PdfReader
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfTheme"/>
|
||||
[Required]
|
||||
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfScrollMode"/>
|
||||
[Required]
|
||||
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
|
||||
|
||||
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfSpreadMode"/>
|
||||
[Required]
|
||||
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
|
@ -81,6 +81,7 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
|
|||
public DbSet<MetadataSettings> MetadataSettings { get; set; } = null!;
|
||||
public DbSet<MetadataFieldMapping> MetadataFieldMapping { get; set; } = null!;
|
||||
public DbSet<AppUserChapterRating> AppUserChapterRating { get; set; } = null!;
|
||||
public DbSet<AppUserReadingProfile> AppUserReadingProfiles { get; set; } = null!;
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder builder)
|
||||
{
|
||||
|
|
@ -256,6 +257,32 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
|
|||
builder.Entity<MetadataSettings>()
|
||||
.Property(b => b.EnableCoverImage)
|
||||
.HasDefaultValue(true);
|
||||
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(b => b.BookThemeName)
|
||||
.HasDefaultValue("Dark");
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(b => b.BackgroundColor)
|
||||
.HasDefaultValue("#000000");
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(b => b.BookReaderWritingStyle)
|
||||
.HasDefaultValue(WritingStyle.Horizontal);
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(b => b.AllowAutomaticWebtoonReaderDetection)
|
||||
.HasDefaultValue(true);
|
||||
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(rp => rp.LibraryIds)
|
||||
.HasConversion(
|
||||
v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default),
|
||||
v => JsonSerializer.Deserialize<List<int>>(v, JsonSerializerOptions.Default) ?? new List<int>())
|
||||
.HasColumnType("TEXT");
|
||||
builder.Entity<AppUserReadingProfile>()
|
||||
.Property(rp => rp.SeriesIds)
|
||||
.HasConversion(
|
||||
v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default),
|
||||
v => JsonSerializer.Deserialize<List<int>>(v, JsonSerializerOptions.Default) ?? new List<int>())
|
||||
.HasColumnType("TEXT");
|
||||
}
|
||||
|
||||
#nullable enable
|
||||
|
|
|
|||
|
|
@ -0,0 +1,84 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.History;
|
||||
using API.Extensions;
|
||||
using API.Helpers.Builders;
|
||||
using Kavita.Common.EnvironmentInfo;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace API.Data.ManualMigrations;
|
||||
|
||||
public static class ManualMigrateReadingProfiles
|
||||
{
|
||||
public static async Task Migrate(DataContext context, ILogger<Program> logger)
|
||||
{
|
||||
if (await context.ManualMigrationHistory.AnyAsync(m => m.Name == "ManualMigrateReadingProfiles"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
logger.LogCritical("Running ManualMigrateReadingProfiles migration - Please be patient, this may take some time. This is not an error");
|
||||
|
||||
var users = await context.AppUser
|
||||
.Include(u => u.UserPreferences)
|
||||
.Include(u => u.ReadingProfiles)
|
||||
.ToListAsync();
|
||||
|
||||
foreach (var user in users)
|
||||
{
|
||||
var readingProfile = new AppUserReadingProfile
|
||||
{
|
||||
Name = "Default",
|
||||
NormalizedName = "Default".ToNormalized(),
|
||||
Kind = ReadingProfileKind.Default,
|
||||
LibraryIds = [],
|
||||
SeriesIds = [],
|
||||
BackgroundColor = user.UserPreferences.BackgroundColor,
|
||||
EmulateBook = user.UserPreferences.EmulateBook,
|
||||
AppUser = user,
|
||||
PdfTheme = user.UserPreferences.PdfTheme,
|
||||
ReaderMode = user.UserPreferences.ReaderMode,
|
||||
ReadingDirection = user.UserPreferences.ReadingDirection,
|
||||
ScalingOption = user.UserPreferences.ScalingOption,
|
||||
LayoutMode = user.UserPreferences.LayoutMode,
|
||||
WidthOverride = null,
|
||||
AppUserId = user.Id,
|
||||
AutoCloseMenu = user.UserPreferences.AutoCloseMenu,
|
||||
BookReaderMargin = user.UserPreferences.BookReaderMargin,
|
||||
PageSplitOption = user.UserPreferences.PageSplitOption,
|
||||
BookThemeName = user.UserPreferences.BookThemeName,
|
||||
PdfSpreadMode = user.UserPreferences.PdfSpreadMode,
|
||||
PdfScrollMode = user.UserPreferences.PdfScrollMode,
|
||||
SwipeToPaginate = user.UserPreferences.SwipeToPaginate,
|
||||
BookReaderFontFamily = user.UserPreferences.BookReaderFontFamily,
|
||||
BookReaderFontSize = user.UserPreferences.BookReaderFontSize,
|
||||
BookReaderImmersiveMode = user.UserPreferences.BookReaderImmersiveMode,
|
||||
BookReaderLayoutMode = user.UserPreferences.BookReaderLayoutMode,
|
||||
BookReaderLineSpacing = user.UserPreferences.BookReaderLineSpacing,
|
||||
BookReaderReadingDirection = user.UserPreferences.BookReaderReadingDirection,
|
||||
BookReaderWritingStyle = user.UserPreferences.BookReaderWritingStyle,
|
||||
AllowAutomaticWebtoonReaderDetection = user.UserPreferences.AllowAutomaticWebtoonReaderDetection,
|
||||
BookReaderTapToPaginate = user.UserPreferences.BookReaderTapToPaginate,
|
||||
ShowScreenHints = user.UserPreferences.ShowScreenHints,
|
||||
};
|
||||
user.ReadingProfiles.Add(readingProfile);
|
||||
}
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
context.ManualMigrationHistory.Add(new ManualMigrationHistory
|
||||
{
|
||||
Name = "ManualMigrateReadingProfiles",
|
||||
ProductVersion = BuildInfo.Version.ToString(),
|
||||
RanAt = DateTime.UtcNow,
|
||||
});
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
|
||||
logger.LogCritical("Running ManualMigrateReadingProfiles migration - Completed. This is not an error");
|
||||
|
||||
}
|
||||
}
|
||||
3698
API/Data/Migrations/20250601200056_ReadingProfiles.Designer.cs
generated
Normal file
3698
API/Data/Migrations/20250601200056_ReadingProfiles.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load diff
75
API/Data/Migrations/20250601200056_ReadingProfiles.cs
Normal file
75
API/Data/Migrations/20250601200056_ReadingProfiles.cs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace API.Data.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class ReadingProfiles : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "AppUserReadingProfiles",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
.Annotation("Sqlite:Autoincrement", true),
|
||||
Name = table.Column<string>(type: "TEXT", nullable: true),
|
||||
NormalizedName = table.Column<string>(type: "TEXT", nullable: true),
|
||||
AppUserId = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
Kind = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
LibraryIds = table.Column<string>(type: "TEXT", nullable: true),
|
||||
SeriesIds = table.Column<string>(type: "TEXT", nullable: true),
|
||||
ReadingDirection = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
ScalingOption = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
PageSplitOption = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
ReaderMode = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
AutoCloseMenu = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
ShowScreenHints = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
EmulateBook = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
LayoutMode = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BackgroundColor = table.Column<string>(type: "TEXT", nullable: true, defaultValue: "#000000"),
|
||||
SwipeToPaginate = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
AllowAutomaticWebtoonReaderDetection = table.Column<bool>(type: "INTEGER", nullable: false, defaultValue: true),
|
||||
WidthOverride = table.Column<int>(type: "INTEGER", nullable: true),
|
||||
BookReaderMargin = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BookReaderLineSpacing = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BookReaderFontSize = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BookReaderFontFamily = table.Column<string>(type: "TEXT", nullable: true),
|
||||
BookReaderTapToPaginate = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
BookReaderReadingDirection = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BookReaderWritingStyle = table.Column<int>(type: "INTEGER", nullable: false, defaultValue: 0),
|
||||
BookThemeName = table.Column<string>(type: "TEXT", nullable: true, defaultValue: "Dark"),
|
||||
BookReaderLayoutMode = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
BookReaderImmersiveMode = table.Column<bool>(type: "INTEGER", nullable: false),
|
||||
PdfTheme = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
PdfScrollMode = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
PdfSpreadMode = table.Column<int>(type: "INTEGER", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_AppUserReadingProfiles", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_AppUserReadingProfiles_AspNetUsers_AppUserId",
|
||||
column: x => x.AppUserId,
|
||||
principalTable: "AspNetUsers",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_AppUserReadingProfiles_AppUserId",
|
||||
table: "AppUserReadingProfiles",
|
||||
column: "AppUserId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "AppUserReadingProfiles");
|
||||
}
|
||||
}
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -609,6 +609,123 @@ namespace API.Data.Migrations
|
|||
b.ToTable("AppUserRating");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("AllowAutomaticWebtoonReaderDetection")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(true);
|
||||
|
||||
b.Property<int>("AppUserId")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("AutoCloseMenu")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("BackgroundColor")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasDefaultValue("#000000");
|
||||
|
||||
b.Property<string>("BookReaderFontFamily")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("BookReaderFontSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("BookReaderImmersiveMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("BookReaderLayoutMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("BookReaderLineSpacing")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("BookReaderMargin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("BookReaderReadingDirection")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("BookReaderTapToPaginate")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("BookReaderWritingStyle")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasDefaultValue(0);
|
||||
|
||||
b.Property<string>("BookThemeName")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT")
|
||||
.HasDefaultValue("Dark");
|
||||
|
||||
b.Property<int>("DisableWidthOverride")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("EmulateBook")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Kind")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("LayoutMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("LibraryIds")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("NormalizedName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("PageSplitOption")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PdfScrollMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PdfSpreadMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PdfTheme")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("ReaderMode")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("ReadingDirection")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("ScalingOption")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("SeriesIds")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("ShowScreenHints")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("SwipeToPaginate")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int?>("WidthOverride")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("AppUserId");
|
||||
|
||||
b.ToTable("AppUserReadingProfiles");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Entities.AppUserRole", b =>
|
||||
{
|
||||
b.Property<int>("UserId")
|
||||
|
|
@ -2841,6 +2958,17 @@ namespace API.Data.Migrations
|
|||
b.Navigation("Series");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
|
||||
{
|
||||
b.HasOne("API.Entities.AppUser", "AppUser")
|
||||
.WithMany("ReadingProfiles")
|
||||
.HasForeignKey("AppUserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("AppUser");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("API.Entities.AppUserRole", b =>
|
||||
{
|
||||
b.HasOne("API.Entities.AppRole", "Role")
|
||||
|
|
@ -3479,6 +3607,8 @@ namespace API.Data.Migrations
|
|||
|
||||
b.Navigation("ReadingLists");
|
||||
|
||||
b.Navigation("ReadingProfiles");
|
||||
|
||||
b.Navigation("ScrobbleHolds");
|
||||
|
||||
b.Navigation("SideNavStreams");
|
||||
|
|
|
|||
112
API/Data/Repositories/AppUserReadingProfileRepository.cs
Normal file
112
API/Data/Repositories/AppUserReadingProfileRepository.cs
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
#nullable enable
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.DTOs;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Extensions;
|
||||
using API.Extensions.QueryExtensions;
|
||||
using AutoMapper;
|
||||
using AutoMapper.QueryableExtensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace API.Data.Repositories;
|
||||
|
||||
|
||||
public interface IAppUserReadingProfileRepository
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Return the given profile if it belongs the user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
Task<AppUserReadingProfile?> GetUserProfile(int userId, int profileId);
|
||||
/// <summary>
|
||||
/// Returns all reading profiles for the user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool skipImplicit = false);
|
||||
/// <summary>
|
||||
/// Returns all reading profiles for the user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool skipImplicit = false);
|
||||
/// <summary>
|
||||
/// Is there a user reading profile with this name (normalized)
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="name"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> IsProfileNameInUse(int userId, string name);
|
||||
|
||||
void Add(AppUserReadingProfile readingProfile);
|
||||
void Update(AppUserReadingProfile readingProfile);
|
||||
void Remove(AppUserReadingProfile readingProfile);
|
||||
void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles);
|
||||
}
|
||||
|
||||
public class AppUserReadingProfileRepository(DataContext context, IMapper mapper): IAppUserReadingProfileRepository
|
||||
{
|
||||
public async Task<AppUserReadingProfile?> GetUserProfile(int userId, int profileId)
|
||||
{
|
||||
return await context.AppUserReadingProfiles
|
||||
.Where(rp => rp.AppUserId == userId && rp.Id == profileId)
|
||||
.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
public async Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool skipImplicit = false)
|
||||
{
|
||||
return await context.AppUserReadingProfiles
|
||||
.Where(rp => rp.AppUserId == userId)
|
||||
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns all Reading Profiles for the User
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool skipImplicit = false)
|
||||
{
|
||||
return await context.AppUserReadingProfiles
|
||||
.Where(rp => rp.AppUserId == userId)
|
||||
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
|
||||
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<bool> IsProfileNameInUse(int userId, string name)
|
||||
{
|
||||
var normalizedName = name.ToNormalized();
|
||||
|
||||
return await context.AppUserReadingProfiles
|
||||
.Where(rp => rp.NormalizedName == normalizedName && rp.AppUserId == userId)
|
||||
.AnyAsync();
|
||||
}
|
||||
|
||||
public void Add(AppUserReadingProfile readingProfile)
|
||||
{
|
||||
context.AppUserReadingProfiles.Add(readingProfile);
|
||||
}
|
||||
|
||||
public void Update(AppUserReadingProfile readingProfile)
|
||||
{
|
||||
context.AppUserReadingProfiles.Update(readingProfile).State = EntityState.Modified;
|
||||
}
|
||||
|
||||
public void Remove(AppUserReadingProfile readingProfile)
|
||||
{
|
||||
context.AppUserReadingProfiles.Remove(readingProfile);
|
||||
}
|
||||
|
||||
public void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles)
|
||||
{
|
||||
context.AppUserReadingProfiles.RemoveRange(readingProfiles);
|
||||
}
|
||||
}
|
||||
|
|
@ -108,14 +108,17 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
|||
|
||||
public async Task<bool> NeedsDataRefresh(int seriesId)
|
||||
{
|
||||
// TODO: Add unit test
|
||||
var row = await _context.ExternalSeriesMetadata
|
||||
.Where(s => s.SeriesId == seriesId)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
return row == null || row.ValidUntilUtc <= DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public async Task<SeriesDetailPlusDto?> GetSeriesDetailPlusDto(int seriesId)
|
||||
{
|
||||
// TODO: Add unit test
|
||||
var seriesDetailDto = await _context.ExternalSeriesMetadata
|
||||
.Where(m => m.SeriesId == seriesId)
|
||||
.Include(m => m.ExternalRatings)
|
||||
|
|
@ -144,7 +147,7 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
|||
.ProjectTo<SeriesDto>(_mapper.ConfigurationProvider)
|
||||
.ToListAsync();
|
||||
|
||||
IEnumerable<UserReviewDto> reviews = new List<UserReviewDto>();
|
||||
IEnumerable<UserReviewDto> reviews = [];
|
||||
if (seriesDetailDto.ExternalReviews != null && seriesDetailDto.ExternalReviews.Any())
|
||||
{
|
||||
reviews = seriesDetailDto.ExternalReviews
|
||||
|
|
@ -231,6 +234,7 @@ public class ExternalSeriesMetadataRepository : IExternalSeriesMetadataRepositor
|
|||
.Include(s => s.ExternalSeriesMetadata)
|
||||
.Where(s => !ExternalMetadataService.NonEligibleLibraryTypes.Contains(s.Library.Type))
|
||||
.Where(s => s.Library.AllowMetadataMatching)
|
||||
.WhereIf(filter.LibraryType >= 0, s => s.Library.Type == (LibraryType) filter.LibraryType)
|
||||
.FilterMatchState(filter.MatchStateOption)
|
||||
.OrderBy(s => s.NormalizedName)
|
||||
.ProjectTo<ManageMatchSeriesDto>(_mapper.ConfigurationProvider)
|
||||
|
|
|
|||
|
|
@ -3,9 +3,11 @@ using System.Collections.Generic;
|
|||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.DTOs.Metadata;
|
||||
using API.DTOs.Metadata.Browse;
|
||||
using API.Entities;
|
||||
using API.Extensions;
|
||||
using API.Extensions.QueryExtensions;
|
||||
using API.Helpers;
|
||||
using API.Services.Tasks.Scanner.Parser;
|
||||
using AutoMapper;
|
||||
using AutoMapper.QueryableExtensions;
|
||||
|
|
@ -27,6 +29,7 @@ public interface IGenreRepository
|
|||
Task<GenreTagDto> GetRandomGenre();
|
||||
Task<GenreTagDto> GetGenreById(int id);
|
||||
Task<List<string>> GetAllGenresNotInListAsync(ICollection<string> genreNames);
|
||||
Task<PagedList<BrowseGenreDto>> GetBrowseableGenre(int userId, UserParams userParams);
|
||||
}
|
||||
|
||||
public class GenreRepository : IGenreRepository
|
||||
|
|
@ -111,7 +114,7 @@ public class GenreRepository : IGenreRepository
|
|||
|
||||
/// <summary>
|
||||
/// Returns a set of Genre tags for a set of library Ids.
|
||||
/// UserId will restrict returned Genres based on user's age restriction and library access.
|
||||
/// AppUserId will restrict returned Genres based on user's age restriction and library access.
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="libraryIds"></param>
|
||||
|
|
@ -165,4 +168,28 @@ public class GenreRepository : IGenreRepository
|
|||
// Return the original non-normalized genres for the missing ones
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,19 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.Data.Misc;
|
||||
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.Entities.Enums;
|
||||
using API.Entities.Person;
|
||||
using API.Extensions;
|
||||
using API.Extensions.QueryExtensions;
|
||||
using API.Extensions.QueryExtensions.Filtering;
|
||||
using API.Helpers;
|
||||
using API.Helpers.Converters;
|
||||
using AutoMapper;
|
||||
using AutoMapper.QueryableExtensions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
|
@ -45,7 +51,7 @@ public interface IPersonRepository
|
|||
Task<string?> GetCoverImageAsync(int personId);
|
||||
Task<string?> GetCoverImageByNameAsync(string name);
|
||||
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<PersonDto?> GetPersonDtoByName(string name, int userId, PersonIncludes includes = PersonIncludes.Aliases);
|
||||
/// <summary>
|
||||
|
|
@ -194,34 +200,80 @@ public class PersonRepository : IPersonRepository
|
|||
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 query = _context.Person
|
||||
.Where(p => p.SeriesMetadataPeople.Any(smp => roles.Contains(smp.Role)) || p.ChapterPeople.Any(cmp => roles.Contains(cmp.Role)))
|
||||
.RestrictAgainstAgeRestriction(ageRating)
|
||||
.Select(p => new BrowsePersonDto
|
||||
var query = CreateFilteredPersonQueryable(userId, filter, ageRating);
|
||||
|
||||
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
|
||||
.Where(smp => roles.Contains(smp.Role))
|
||||
.Select(smp => smp.SeriesMetadata.SeriesId)
|
||||
.Distinct()
|
||||
.Count(),
|
||||
IssueCount = p.ChapterPeople
|
||||
.Where(cp => roles.Contains(cp.Role))
|
||||
ChapterCount = p.ChapterPeople
|
||||
.Select(cp => cp.Chapter.Id)
|
||||
.Distinct()
|
||||
.Count()
|
||||
})
|
||||
.OrderBy(p => p.Name);
|
||||
});
|
||||
|
||||
return await PagedList<BrowsePersonDto>.CreateAsync(query, userParams.PageNumber, userParams.PageSize);
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -735,6 +735,7 @@ public class SeriesRepository : ISeriesRepository
|
|||
{
|
||||
return await _context.Series
|
||||
.Where(s => s.Id == seriesId)
|
||||
.Include(s => s.ExternalSeriesMetadata)
|
||||
.Select(series => new PlusSeriesRequestDto()
|
||||
{
|
||||
MediaFormat = series.Library.Type.ConvertToPlusMediaFormat(series.Format),
|
||||
|
|
@ -744,6 +745,7 @@ public class SeriesRepository : ISeriesRepository
|
|||
ScrobblingService.AniListWeblinkWebsite),
|
||||
MalId = ScrobblingService.ExtractId<long?>(series.Metadata.WebLinks,
|
||||
ScrobblingService.MalWeblinkWebsite),
|
||||
CbrId = series.ExternalSeriesMetadata.CbrId,
|
||||
GoogleBooksId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
||||
ScrobblingService.GoogleBooksWeblinkWebsite),
|
||||
MangaDexId = ScrobblingService.ExtractId<string?>(series.Metadata.WebLinks,
|
||||
|
|
@ -1088,8 +1090,6 @@ public class SeriesRepository : ISeriesRepository
|
|||
return query.Where(s => false);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// First setup any FilterField.Libraries in the statements, as these don't have any traditional query statements applied here
|
||||
query = ApplyLibraryFilter(filter, query);
|
||||
|
||||
|
|
@ -1290,7 +1290,7 @@ public class SeriesRepository : ISeriesRepository
|
|||
FilterField.ReadingDate => query.HasReadingDate(true, statement.Comparison, (DateTime) value, userId),
|
||||
FilterField.ReadLast => query.HasReadLast(true, statement.Comparison, (int) value, userId),
|
||||
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.Threading.Tasks;
|
||||
using API.DTOs.Metadata;
|
||||
using API.DTOs.Metadata.Browse;
|
||||
using API.Entities;
|
||||
using API.Extensions;
|
||||
using API.Extensions.QueryExtensions;
|
||||
using API.Helpers;
|
||||
using API.Services.Tasks.Scanner.Parser;
|
||||
using AutoMapper;
|
||||
using AutoMapper.QueryableExtensions;
|
||||
|
|
@ -23,6 +25,7 @@ public interface ITagRepository
|
|||
Task RemoveAllTagNoLongerAssociated();
|
||||
Task<IList<TagDto>> GetAllTagDtosForLibrariesAsync(int userId, IList<int>? libraryIds = null);
|
||||
Task<List<string>> GetAllTagsNotInListAsync(ICollection<string> tags);
|
||||
Task<PagedList<BrowseTagDto>> GetBrowseableTag(int userId, UserParams userParams);
|
||||
}
|
||||
|
||||
public class TagRepository : ITagRepository
|
||||
|
|
@ -104,6 +107,30 @@ public class TagRepository : ITagRepository
|
|||
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()
|
||||
{
|
||||
return await _context.Tag.ToListAsync();
|
||||
|
|
|
|||
|
|
@ -757,7 +757,7 @@ public class UserRepository : IUserRepository
|
|||
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the UserId by API Key. This does not include any extra information
|
||||
/// Fetches the AppUserId by API Key. This does not include any extra information
|
||||
/// </summary>
|
||||
/// <param name="apiKey"></param>
|
||||
/// <returns></returns>
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ public static class Seed
|
|||
new AppUserSideNavStream()
|
||||
{
|
||||
Name = "browse-authors",
|
||||
StreamType = SideNavStreamType.BrowseAuthors,
|
||||
StreamType = SideNavStreamType.BrowsePeople,
|
||||
Order = 6,
|
||||
IsProvided = true,
|
||||
Visible = true
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ public interface IUnitOfWork
|
|||
IAppUserExternalSourceRepository AppUserExternalSourceRepository { get; }
|
||||
IExternalSeriesMetadataRepository ExternalSeriesMetadataRepository { get; }
|
||||
IEmailHistoryRepository EmailHistoryRepository { get; }
|
||||
IAppUserReadingProfileRepository AppUserReadingProfileRepository { get; }
|
||||
bool Commit();
|
||||
Task<bool> CommitAsync();
|
||||
bool HasChanges();
|
||||
|
|
@ -74,6 +75,7 @@ public class UnitOfWork : IUnitOfWork
|
|||
AppUserExternalSourceRepository = new AppUserExternalSourceRepository(_context, _mapper);
|
||||
ExternalSeriesMetadataRepository = new ExternalSeriesMetadataRepository(_context, _mapper);
|
||||
EmailHistoryRepository = new EmailHistoryRepository(_context, _mapper);
|
||||
AppUserReadingProfileRepository = new AppUserReadingProfileRepository(_context, _mapper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -103,6 +105,7 @@ public class UnitOfWork : IUnitOfWork
|
|||
public IAppUserExternalSourceRepository AppUserExternalSourceRepository { get; }
|
||||
public IExternalSeriesMetadataRepository ExternalSeriesMetadataRepository { get; }
|
||||
public IEmailHistoryRepository EmailHistoryRepository { get; }
|
||||
public IAppUserReadingProfileRepository AppUserReadingProfileRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Commits changes to the DB. Completes the open transaction.
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ public class AppUser : IdentityUser<int>, IHasConcurrencyToken
|
|||
public ICollection<AppUserRating> Ratings { get; set; } = null!;
|
||||
public ICollection<AppUserChapterRating> ChapterRatings { get; set; } = null!;
|
||||
public AppUserPreferences UserPreferences { get; set; } = null!;
|
||||
public ICollection<AppUserReadingProfile> ReadingProfiles { get; set; } = null!;
|
||||
/// <summary>
|
||||
/// Bookmarks associated with this User
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using API.Data;
|
||||
using System.Collections.Generic;
|
||||
using API.Data;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Enums.UserPreferences;
|
||||
|
||||
|
|
|
|||
160
API/Entities/AppUserReadingProfile.cs
Normal file
160
API/Entities/AppUserReadingProfile.cs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Enums.UserPreferences;
|
||||
|
||||
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 int Id { get; set; }
|
||||
|
||||
public string Name { get; set; }
|
||||
public string NormalizedName { get; set; }
|
||||
|
||||
public int AppUserId { get; set; }
|
||||
public AppUser AppUser { get; set; }
|
||||
|
||||
public ReadingProfileKind Kind { get; set; }
|
||||
public List<int> LibraryIds { get; set; }
|
||||
public List<int> SeriesIds { get; set; }
|
||||
|
||||
#region MangaReader
|
||||
|
||||
/// <summary>
|
||||
/// Manga Reader Option: What direction should the next/prev page buttons go
|
||||
/// </summary>
|
||||
public ReadingDirection ReadingDirection { get; set; } = ReadingDirection.LeftToRight;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: How should the image be scaled to screen
|
||||
/// </summary>
|
||||
public ScalingOption ScalingOption { get; set; } = ScalingOption.Automatic;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Which side of a split image should we show first
|
||||
/// </summary>
|
||||
public PageSplitOption PageSplitOption { get; set; } = PageSplitOption.FitSplit;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: How the manga reader should perform paging or reading of the file
|
||||
/// <example>
|
||||
/// Webtoon uses scrolling to page, MANGA_LR uses paging by clicking left/right side of reader, MANGA_UD uses paging
|
||||
/// by clicking top/bottom sides of reader.
|
||||
/// </example>
|
||||
/// </summary>
|
||||
public ReaderMode ReaderMode { get; set; }
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Allow the menu to close after 6 seconds without interaction
|
||||
/// </summary>
|
||||
public bool AutoCloseMenu { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Show screen hints to the user on some actions, ie) pagination direction change
|
||||
/// </summary>
|
||||
public bool ShowScreenHints { get; set; } = true;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Emulate a book by applying a shadow effect on the pages
|
||||
/// </summary>
|
||||
public bool EmulateBook { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: How many pages to display in the reader at once
|
||||
/// </summary>
|
||||
public LayoutMode LayoutMode { get; set; } = LayoutMode.Single;
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Background color of the reader
|
||||
/// </summary>
|
||||
public string BackgroundColor { get; set; } = "#000000";
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Should swiping trigger pagination
|
||||
/// </summary>
|
||||
public bool SwipeToPaginate { get; set; }
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Allow Automatic Webtoon detection
|
||||
/// </summary>
|
||||
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
|
||||
/// <summary>
|
||||
/// Manga Reader Option: Optional fixed width override
|
||||
/// </summary>
|
||||
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
|
||||
|
||||
#region EpubReader
|
||||
|
||||
/// <summary>
|
||||
/// Book Reader Option: Override extra Margin
|
||||
/// </summary>
|
||||
public int BookReaderMargin { get; set; } = 15;
|
||||
/// <summary>
|
||||
/// Book Reader Option: Override line-height
|
||||
/// </summary>
|
||||
public int BookReaderLineSpacing { get; set; } = 100;
|
||||
/// <summary>
|
||||
/// Book Reader Option: Override font size
|
||||
/// </summary>
|
||||
public int BookReaderFontSize { get; set; } = 100;
|
||||
/// <summary>
|
||||
/// Book Reader Option: Maps to the default Kavita font-family (inherit) or an override
|
||||
/// </summary>
|
||||
public string BookReaderFontFamily { get; set; } = "default";
|
||||
/// <summary>
|
||||
/// Book Reader Option: Allows tapping on side of screens to paginate
|
||||
/// </summary>
|
||||
public bool BookReaderTapToPaginate { get; set; } = false;
|
||||
/// <summary>
|
||||
/// Book Reader Option: What direction should the next/prev page buttons go
|
||||
/// </summary>
|
||||
public ReadingDirection BookReaderReadingDirection { get; set; } = ReadingDirection.LeftToRight;
|
||||
/// <summary>
|
||||
/// Book Reader Option: Defines the writing styles vertical/horizontal
|
||||
/// </summary>
|
||||
public WritingStyle BookReaderWritingStyle { get; set; } = WritingStyle.Horizontal;
|
||||
/// <summary>
|
||||
/// Book Reader Option: The color theme to decorate the book contents
|
||||
/// </summary>
|
||||
/// <remarks>Should default to Dark</remarks>
|
||||
public string BookThemeName { get; set; } = "Dark";
|
||||
/// <summary>
|
||||
/// Book Reader Option: The way a page from a book is rendered. Default is as book dictates, 1 column is fit to height,
|
||||
/// 2 column is fit to height, 2 columns
|
||||
/// </summary>
|
||||
/// <remarks>Defaults to Default</remarks>
|
||||
public BookPageLayoutMode BookReaderLayoutMode { get; set; } = BookPageLayoutMode.Default;
|
||||
/// <summary>
|
||||
/// Book Reader Option: A flag that hides the menu-ing system behind a click on the screen. This should be used with tap to paginate, but the app doesn't enforce this.
|
||||
/// </summary>
|
||||
/// <remarks>Defaults to false</remarks>
|
||||
public bool BookReaderImmersiveMode { get; set; } = false;
|
||||
#endregion
|
||||
|
||||
#region PdfReader
|
||||
|
||||
/// <summary>
|
||||
/// PDF Reader: Theme of the Reader
|
||||
/// </summary>
|
||||
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
|
||||
/// <summary>
|
||||
/// PDF Reader: Scroll mode of the reader
|
||||
/// </summary>
|
||||
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
|
||||
/// <summary>
|
||||
/// PDF Reader: Spread Mode of the reader
|
||||
/// </summary>
|
||||
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
|
||||
|
||||
|
||||
#endregion
|
||||
}
|
||||
17
API/Entities/Enums/ReadingProfileKind.cs
Normal file
17
API/Entities/Enums/ReadingProfileKind.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
namespace API.Entities.Enums;
|
||||
|
||||
public enum ReadingProfileKind
|
||||
{
|
||||
/// <summary>
|
||||
/// Generate by Kavita when registering a user, this is your default profile
|
||||
/// </summary>
|
||||
Default,
|
||||
/// <summary>
|
||||
/// Created by the user in the UI or via the API
|
||||
/// </summary>
|
||||
User,
|
||||
/// <summary>
|
||||
/// Automatically generated by Kavita to track changes made in the readers. Can be converted to a User Reading Profile.
|
||||
/// </summary>
|
||||
Implicit
|
||||
}
|
||||
|
|
@ -10,5 +10,5 @@ public enum SideNavStreamType
|
|||
ExternalSource = 6,
|
||||
AllSeries = 7,
|
||||
WantToRead = 8,
|
||||
BrowseAuthors = 9
|
||||
BrowsePeople = 9
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ public static class ApplicationServiceExtensions
|
|||
services.AddScoped<IStreamService, StreamService>();
|
||||
services.AddScoped<IRatingService, RatingService>();
|
||||
services.AddScoped<IPersonService, PersonService>();
|
||||
services.AddScoped<IReadingProfileService, ReadingProfileService>();
|
||||
services.AddScoped<IKoreaderService, KoreaderService>();
|
||||
|
||||
services.AddScoped<IScannerService, ScannerService>();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ using System.Linq;
|
|||
using System.Text.RegularExpressions;
|
||||
using API.Data.Misc;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Metadata;
|
||||
|
||||
namespace API.Extensions;
|
||||
#nullable enable
|
||||
|
|
@ -42,4 +43,16 @@ public static class EnumerableExtensions
|
|||
|
||||
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 API.Data.Misc;
|
||||
using API.Data.Repositories;
|
||||
using API.DTOs;
|
||||
using API.DTOs.Filtering;
|
||||
using API.DTOs.KavitaPlus.Manage;
|
||||
using API.DTOs.Metadata.Browse;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Person;
|
||||
using API.Entities.Scrobble;
|
||||
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>
|
||||
/// Performs either OrderBy or OrderByDescending on the given query based on the value of SortOptions.IsAscending.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Linq;
|
|||
using API.Data.Misc;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Entities.Metadata;
|
||||
using API.Entities.Person;
|
||||
|
||||
namespace API.Extensions.QueryExtensions;
|
||||
|
|
@ -26,6 +27,7 @@ public static class RestrictByAgeExtensions
|
|||
return q;
|
||||
}
|
||||
|
||||
|
||||
public static IQueryable<Chapter> RestrictAgainstAgeRestriction(this IQueryable<Chapter> queryable, AgeRestriction restriction)
|
||||
{
|
||||
if (restriction.AgeRating == AgeRating.NotApplicable) return queryable;
|
||||
|
|
@ -39,20 +41,6 @@ public static class RestrictByAgeExtensions
|
|||
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)
|
||||
{
|
||||
|
|
@ -74,12 +62,15 @@ public static class RestrictByAgeExtensions
|
|||
|
||||
if (restriction.IncludeUnknowns)
|
||||
{
|
||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
||||
sm.AgeRating <= restriction.AgeRating));
|
||||
return queryable.Where(c =>
|
||||
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating) ||
|
||||
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating));
|
||||
}
|
||||
|
||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
||||
sm.AgeRating <= restriction.AgeRating && sm.AgeRating > AgeRating.Unknown));
|
||||
return queryable.Where(c =>
|
||||
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)
|
||||
|
|
@ -88,12 +79,15 @@ public static class RestrictByAgeExtensions
|
|||
|
||||
if (restriction.IncludeUnknowns)
|
||||
{
|
||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
||||
sm.AgeRating <= restriction.AgeRating));
|
||||
return queryable.Where(c =>
|
||||
c.SeriesMetadatas.Any(sm => sm.AgeRating <= restriction.AgeRating) ||
|
||||
c.Chapters.Any(cp => cp.AgeRating <= restriction.AgeRating));
|
||||
}
|
||||
|
||||
return queryable.Where(c => c.SeriesMetadatas.All(sm =>
|
||||
sm.AgeRating <= restriction.AgeRating && sm.AgeRating > AgeRating.Unknown));
|
||||
return queryable.Where(c =>
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -275,19 +275,19 @@ public class AutoMapperProfiles : Profile
|
|||
CreateMap<AppUserPreferences, UserPreferencesDto>()
|
||||
.ForMember(dest => dest.Theme,
|
||||
opt =>
|
||||
opt.MapFrom(src => src.Theme))
|
||||
opt.MapFrom(src => src.Theme));
|
||||
|
||||
CreateMap<AppUserReadingProfile, UserReadingProfileDto>()
|
||||
.ForMember(dest => dest.BookReaderThemeName,
|
||||
opt =>
|
||||
opt.MapFrom(src => src.BookThemeName))
|
||||
.ForMember(dest => dest.BookReaderLayoutMode,
|
||||
opt =>
|
||||
opt.MapFrom(src => src.BookReaderLayoutMode));
|
||||
opt.MapFrom(src => src.BookThemeName));
|
||||
|
||||
|
||||
CreateMap<AppUserBookmark, BookmarkDto>();
|
||||
|
||||
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<ScrobbleError, ScrobbleErrorDto>();
|
||||
CreateMap<ChapterDto, TachiyomiChapterDto>();
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
|
|||
ApiKey = HashUtil.ApiKey(),
|
||||
UserPreferences = new AppUserPreferences
|
||||
{
|
||||
Theme = theme ?? Seed.DefaultThemes.First()
|
||||
Theme = theme ?? Seed.DefaultThemes.First(),
|
||||
},
|
||||
ReadingLists = new List<ReadingList>(),
|
||||
Bookmarks = new List<AppUserBookmark>(),
|
||||
|
|
@ -31,7 +31,8 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
|
|||
Devices = new List<Device>(),
|
||||
Id = 0,
|
||||
DashboardStreams = new List<AppUserDashboardStream>(),
|
||||
SideNavStreams = new List<AppUserSideNavStream>()
|
||||
SideNavStreams = new List<AppUserSideNavStream>(),
|
||||
ReadingProfiles = [],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
54
API/Helpers/Builders/AppUserReadingProfileBuilder.cs
Normal file
54
API/Helpers/Builders/AppUserReadingProfileBuilder.cs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Extensions;
|
||||
|
||||
namespace API.Helpers.Builders;
|
||||
|
||||
public class AppUserReadingProfileBuilder
|
||||
{
|
||||
private readonly AppUserReadingProfile _profile;
|
||||
|
||||
public AppUserReadingProfile Build() => _profile;
|
||||
|
||||
/// <summary>
|
||||
/// The profile's kind will be <see cref="ReadingProfileKind.User"/> unless overwritten with <see cref="WithKind"/>
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
public AppUserReadingProfileBuilder(int userId)
|
||||
{
|
||||
_profile = new AppUserReadingProfile
|
||||
{
|
||||
AppUserId = userId,
|
||||
Kind = ReadingProfileKind.User,
|
||||
SeriesIds = [],
|
||||
LibraryIds = []
|
||||
};
|
||||
}
|
||||
|
||||
public AppUserReadingProfileBuilder WithSeries(Series series)
|
||||
{
|
||||
_profile.SeriesIds.Add(series.Id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUserReadingProfileBuilder WithLibrary(Library library)
|
||||
{
|
||||
_profile.LibraryIds.Add(library.Id);
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUserReadingProfileBuilder WithKind(ReadingProfileKind kind)
|
||||
{
|
||||
_profile.Kind = kind;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AppUserReadingProfileBuilder WithName(string name)
|
||||
{
|
||||
_profile.Name = name;
|
||||
_profile.NormalizedName = name.ToNormalized();
|
||||
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();
|
||||
}
|
||||
}
|
||||
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-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ů",
|
||||
"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}"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -230,6 +230,8 @@
|
|||
"scan-libraries": "Scan Libraries",
|
||||
"kavita+-data-refresh": "Kavita+ Data Refresh",
|
||||
"backup": "Backup",
|
||||
"update-yearly-stats": "Update Yearly Stats"
|
||||
"update-yearly-stats": "Update Yearly Stats",
|
||||
|
||||
"generated-reading-profile-name": "Generated from {0}"
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -208,5 +208,6 @@
|
|||
"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",
|
||||
"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": "אירעה תקלה בעת עדכון הגבלת גיל",
|
||||
"generic-user-update": "אירעה תקלה בעת עדכון משתמש",
|
||||
"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",
|
||||
"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",
|
||||
"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": "Возникла проблема с генерацией токена подтверждения электронной почты. Смотрите журналы",
|
||||
"invalid-password": "Неверный пароль",
|
||||
"invalid-email-confirmation": "Неверное подтверждение электронной почты",
|
||||
|
|
@ -35,15 +35,15 @@
|
|||
"no-user": "Пользователь не существует",
|
||||
"generic-invite-user": "Возникла проблема с приглашением пользователя. Пожалуйста, проверьте журналы.",
|
||||
"permission-denied": "Вам запрещено выполнять эту операцию",
|
||||
"invalid-access": "Недопустимый доступ",
|
||||
"invalid-access": "В доступе отказано",
|
||||
"reading-list-name-exists": "Такой список для чтения уже существует",
|
||||
"perform-scan": "Пожалуйста, выполните сканирование этой серии или библиотеки и повторите попытку",
|
||||
"generic-device-create": "При создании устройства возникла ошибка",
|
||||
"generic-read-progress": "Возникла проблема с сохранением прогресса",
|
||||
"file-doesnt-exist": "Файл не существует",
|
||||
"admin-already-exists": "Администратор уже существует",
|
||||
"send-to-kavita-email": "Отправка на устройство не может быть использована с почтовым сервисом Kavita. Пожалуйста, настройте свой собственный.",
|
||||
"no-image-for-page": "Нет такого изображения для страницы {0}. Попробуйте обновить, чтобы обновить кэш.",
|
||||
"send-to-kavita-email": "Отправка на устройство не может быть использована без настройки электронной почты",
|
||||
"no-image-for-page": "Нет такого изображения для страницы {0}. Попробуйте обновить, для повторного кеширования.",
|
||||
"reading-list-permission": "У вас нет прав на этот список чтения или список не существует",
|
||||
"volume-doesnt-exist": "Том не существует",
|
||||
"generic-library": "Возникла критическая проблема. Пожалуйста, попробуйте еще раз.",
|
||||
|
|
@ -57,7 +57,7 @@
|
|||
"generic-reading-list-create": "Возникла проблема с созданием списка для чтения",
|
||||
"no-cover-image": "Изображение на обложке отсутствует",
|
||||
"collection-updated": "Коллекция успешно обновлена",
|
||||
"critical-email-migration": "Возникла проблема при переносе электронной почты. Обратитесь в службу поддержки",
|
||||
"critical-email-migration": "Возникла проблема при смене электронной почты. Обратитесь в службу поддержки",
|
||||
"cache-file-find": "Не удалось найти изображение в кэше. Перезагрузитесь и попробуйте снова.",
|
||||
"duplicate-bookmark": "Дублирующая закладка уже существует",
|
||||
"collection-tag-duplicate": "Такая коллекция уже существует",
|
||||
|
|
@ -72,7 +72,7 @@
|
|||
"pdf-doesnt-exist": "PDF не существует, когда он должен существовать",
|
||||
"generic-device-delete": "При удалении устройства возникла ошибка",
|
||||
"bookmarks-empty": "Закладки не могут быть пустыми",
|
||||
"valid-number": "Должен быть действительный номер страницы",
|
||||
"valid-number": "Номер страницы должен быть действительным",
|
||||
"series-doesnt-exist": "Серия не существует",
|
||||
"no-library-access": "Пользователь не имеет доступа к этой библиотеке",
|
||||
"reading-list-item-delete": "Не удалось удалить элемент(ы)",
|
||||
|
|
@ -155,7 +155,7 @@
|
|||
"generic-user-delete": "Не удалось удалить пользователя",
|
||||
"generic-cover-reading-list-save": "Невозможно сохранить изображение обложки в списке для чтения",
|
||||
"unable-to-register-k+": "Невозможно зарегистрировать лицензию из-за ошибки. Обратитесь в службу поддержки Кавита+",
|
||||
"encode-as-warning": "Конвертировать в PNG невозможно. Для обложек используйте Обновить Обложки. Закладки и фавиконки нельзя закодировать обратно.",
|
||||
"encode-as-warning": "Вы не можете конвертировать в формат PNG. Для обновления обложек используйте команду \"Обновить обложку\". Закладки и значки не могут быть закодированы обратно.",
|
||||
"want-to-read": "Хотите прочитать",
|
||||
"generic-user-pref": "Возникла проблема с сохранением предпочтений",
|
||||
"external-sources": "Внешние источники",
|
||||
|
|
@ -197,7 +197,7 @@
|
|||
"kavita+-data-refresh": "Обновление данных Kavita+",
|
||||
"kavitaplus-restricted": "Это доступно только для Kavita+",
|
||||
"person-doesnt-exist": "Персона не существует",
|
||||
"generic-cover-volume-save": "Не удается сохранить обложку для раздела",
|
||||
"generic-cover-volume-save": "Не удается сохранить обложку для тома",
|
||||
"generic-cover-person-save": "Не удается сохранить изображение обложки для Персоны",
|
||||
"person-name-unique": "Имя персоны должно быть уникальным",
|
||||
"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-system-name": "您不能使用系统提供的流名称",
|
||||
"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 Microsoft.Extensions.Logging;
|
||||
using NetVips;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using SixLabors.ImageSharp.Processing.Processors.Quantization;
|
||||
using Color = System.Drawing.Color;
|
||||
using Image = NetVips.Image;
|
||||
|
||||
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");
|
||||
|
||||
|
|
@ -774,7 +772,7 @@ public class ImageService : IImageService
|
|||
var g = Convert.ToInt32(hex.Substring(2, 2), 16);
|
||||
var b = Convert.ToInt32(hex.Substring(4, 2), 16);
|
||||
|
||||
return Color.FromArgb(r, g, b);
|
||||
return (r, g, b);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -200,6 +200,9 @@ public class ExternalMetadataService : IExternalMetadataService
|
|||
/// <summary>
|
||||
/// Returns the match results for a Series from UI Flow
|
||||
/// </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>
|
||||
/// <returns></returns>
|
||||
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 potentialMalId = ScrobblingService.ExtractId<long?>(dto.Query, ScrobblingService.MalWeblinkWebsite);
|
||||
|
||||
List<string> altNames = [series.LocalizedName, series.OriginalName];
|
||||
if (potentialAnilistId == null && potentialMalId == null && !string.IsNullOrEmpty(dto.Query))
|
||||
var format = series.Library.Type.ConvertToPlusMediaFormat(series.Format);
|
||||
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()
|
||||
{
|
||||
Format = series.Library.Type.ConvertToPlusMediaFormat(series.Format),
|
||||
Format = format,
|
||||
Query = dto.Query,
|
||||
SeriesName = series.Name,
|
||||
AlternativeNames = altNames.Where(s => !string.IsNullOrEmpty(s)).ToList(),
|
||||
Year = series.Metadata.ReleaseYear,
|
||||
AlternativeNames = otherNames,
|
||||
Year = year,
|
||||
AniListId = potentialAnilistId ?? ScrobblingService.GetAniListId(series),
|
||||
MalId = potentialMalId ?? ScrobblingService.GetMalId(series)
|
||||
};
|
||||
|
|
@ -254,6 +264,12 @@ public class ExternalMetadataService : IExternalMetadataService
|
|||
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>
|
||||
/// Retrieves Metadata about a Recommended External Series
|
||||
|
|
|
|||
|
|
@ -130,22 +130,23 @@ public class LicenseService(
|
|||
if (cacheValue.HasValue) return cacheValue.Value;
|
||||
}
|
||||
|
||||
var result = false;
|
||||
try
|
||||
{
|
||||
var serverSetting = await unitOfWork.SettingsRepository.GetSettingAsync(ServerSettingKey.LicenseKey);
|
||||
var result = await IsLicenseValid(serverSetting.Value);
|
||||
await provider.FlushAsync();
|
||||
await provider.SetAsync(CacheKey, result, _licenseCacheTimeout);
|
||||
return result;
|
||||
result = await IsLicenseValid(serverSetting.Value);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "There was an issue connecting to Kavita+");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await provider.FlushAsync();
|
||||
await provider.SetAsync(CacheKey, false, _licenseCacheTimeout);
|
||||
await provider.SetAsync(CacheKey, result, _licenseCacheTimeout);
|
||||
}
|
||||
|
||||
return false;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -261,7 +261,7 @@ public class ScrobblingService : IScrobblingService
|
|||
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId, SeriesIncludes.Metadata | SeriesIncludes.Library);
|
||||
if (series == null) throw new KavitaException(await _localizationService.Translate(userId, "series-doesnt-exist"));
|
||||
|
||||
_logger.LogInformation("Processing Scrobbling review event for {UserId} on {SeriesName}", userId, series.Name);
|
||||
_logger.LogInformation("Processing Scrobbling review event for {AppUserId} on {SeriesName}", userId, series.Name);
|
||||
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
|
||||
|
||||
if (IsAniListReviewValid(reviewTitle, reviewBody))
|
||||
|
|
@ -297,7 +297,7 @@ public class ScrobblingService : IScrobblingService
|
|||
};
|
||||
_unitOfWork.ScrobbleRepository.Attach(evt);
|
||||
await _unitOfWork.CommitAsync();
|
||||
_logger.LogDebug("Added Scrobbling Review update on {SeriesName} with Userid {UserId} ", series.Name, userId);
|
||||
_logger.LogDebug("Added Scrobbling Review update on {SeriesName} with Userid {AppUserId} ", series.Name, userId);
|
||||
}
|
||||
|
||||
private static bool IsAniListReviewValid(string reviewTitle, string reviewBody)
|
||||
|
|
@ -317,7 +317,7 @@ public class ScrobblingService : IScrobblingService
|
|||
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
|
||||
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
|
||||
|
||||
_logger.LogInformation("Processing Scrobbling rating event for {UserId} on {SeriesName}", userId, series.Name);
|
||||
_logger.LogInformation("Processing Scrobbling rating event for {AppUserId} on {SeriesName}", userId, series.Name);
|
||||
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
|
||||
|
||||
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
|
||||
|
|
@ -346,7 +346,7 @@ public class ScrobblingService : IScrobblingService
|
|||
};
|
||||
_unitOfWork.ScrobbleRepository.Attach(evt);
|
||||
await _unitOfWork.CommitAsync();
|
||||
_logger.LogDebug("Added Scrobbling Rating update on {SeriesName} with Userid {UserId}", series.Name, userId);
|
||||
_logger.LogDebug("Added Scrobbling Rating update on {SeriesName} with Userid {AppUserId}", series.Name, userId);
|
||||
}
|
||||
|
||||
public static long? GetMalId(Series series)
|
||||
|
|
@ -371,7 +371,7 @@ public class ScrobblingService : IScrobblingService
|
|||
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
|
||||
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
|
||||
|
||||
_logger.LogInformation("Processing Scrobbling reading event for {UserId} on {SeriesName}", userId, series.Name);
|
||||
_logger.LogInformation("Processing Scrobbling reading event for {AppUserId} on {SeriesName}", userId, series.Name);
|
||||
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
|
||||
|
||||
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
|
||||
|
|
@ -418,7 +418,7 @@ public class ScrobblingService : IScrobblingService
|
|||
|
||||
_unitOfWork.ScrobbleRepository.Attach(evt);
|
||||
await _unitOfWork.CommitAsync();
|
||||
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} - Volume: {VolumeNumber} Chapter: {ChapterNumber} for User: {UserId}", series.Name, evt.VolumeNumber, evt.ChapterNumber, userId);
|
||||
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} - Volume: {VolumeNumber} Chapter: {ChapterNumber} for User: {AppUserId}", series.Name, evt.VolumeNumber, evt.ChapterNumber, userId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -437,7 +437,7 @@ public class ScrobblingService : IScrobblingService
|
|||
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
|
||||
|
||||
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
|
||||
_logger.LogInformation("Processing Scrobbling want-to-read event for {UserId} on {SeriesName}", userId, series.Name);
|
||||
_logger.LogInformation("Processing Scrobbling want-to-read event for {AppUserId} on {SeriesName}", userId, series.Name);
|
||||
|
||||
// Get existing events for this series/user
|
||||
var existingEvents = (await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId))
|
||||
|
|
@ -463,7 +463,7 @@ public class ScrobblingService : IScrobblingService
|
|||
|
||||
_unitOfWork.ScrobbleRepository.Attach(evt);
|
||||
await _unitOfWork.CommitAsync();
|
||||
_logger.LogDebug("Added Scrobbling WantToRead update on {SeriesName} with Userid {UserId} ", series.Name, userId);
|
||||
_logger.LogDebug("Added Scrobbling WantToRead update on {SeriesName} with Userid {AppUserId} ", series.Name, userId);
|
||||
}
|
||||
|
||||
private async Task<bool> CheckIfCannotScrobble(int userId, int seriesId, Series series)
|
||||
|
|
@ -471,7 +471,7 @@ public class ScrobblingService : IScrobblingService
|
|||
if (series.DontMatch) return true;
|
||||
if (await _unitOfWork.UserRepository.HasHoldOnSeries(userId, seriesId))
|
||||
{
|
||||
_logger.LogInformation("Series {SeriesName} is on UserId {UserId}'s hold list. Not scrobbling", series.Name,
|
||||
_logger.LogInformation("Series {SeriesName} is on AppUserId {AppUserId}'s hold list. Not scrobbling", series.Name,
|
||||
userId);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -750,7 +750,7 @@ public class ScrobblingService : IScrobblingService
|
|||
/// <param name="seriesId"></param>
|
||||
public async Task ClearEventsForSeries(int userId, int seriesId)
|
||||
{
|
||||
_logger.LogInformation("Clearing Pre-existing Scrobble events for Series {SeriesId} by User {UserId} as Series is now on hold list", seriesId, userId);
|
||||
_logger.LogInformation("Clearing Pre-existing Scrobble events for Series {SeriesId} by User {AppUserId} as Series is now on hold list", seriesId, userId);
|
||||
var events = await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId);
|
||||
foreach (var scrobble in events)
|
||||
{
|
||||
|
|
@ -1109,7 +1109,7 @@ public class ScrobblingService : IScrobblingService
|
|||
{
|
||||
if (ex.Message.Contains("Access token is invalid"))
|
||||
{
|
||||
_logger.LogCritical(ex, "Access Token for UserId: {UserId} needs to be regenerated/renewed to continue scrobbling", evt.AppUser.Id);
|
||||
_logger.LogCritical(ex, "Access Token for AppUserId: {AppUserId} needs to be regenerated/renewed to continue scrobbling", evt.AppUser.Id);
|
||||
evt.IsErrored = true;
|
||||
evt.ErrorDetails = AccessTokenErrorMessage;
|
||||
_unitOfWork.ScrobbleRepository.Update(evt);
|
||||
|
|
|
|||
454
API/Services/ReadingProfileService.cs
Normal file
454
API/Services/ReadingProfileService.cs
Normal file
|
|
@ -0,0 +1,454 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using API.Data;
|
||||
using API.Data.Repositories;
|
||||
using API.DTOs;
|
||||
using API.Entities;
|
||||
using API.Entities.Enums;
|
||||
using API.Extensions;
|
||||
using API.Helpers.Builders;
|
||||
using AutoMapper;
|
||||
using Kavita.Common;
|
||||
|
||||
namespace API.Services;
|
||||
#nullable enable
|
||||
|
||||
public interface IReadingProfileService
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the ReadingProfile that should be applied to the given series, walks up the tree.
|
||||
/// Series (Implicit) -> Series (User) -> Library (User) -> Default
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="skipImplicit"></param>
|
||||
/// <returns></returns>
|
||||
Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId, bool skipImplicit = false);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new reading profile for a user. Name must be unique per user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns></returns>
|
||||
Task<UserReadingProfileDto> CreateReadingProfile(int userId, UserReadingProfileDto dto);
|
||||
Task<UserReadingProfileDto> PromoteImplicitProfile(int userId, int profileId);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the implicit reading profile for a series, creates one if none exists
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns></returns>
|
||||
Task<UserReadingProfileDto> UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the non-implicit reading profile for the given series, and removes implicit profiles
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns></returns>
|
||||
Task<UserReadingProfileDto> UpdateParent(int userId, int seriesId, UserReadingProfileDto dto);
|
||||
|
||||
/// <summary>
|
||||
/// Updates a given reading profile for a user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="dto"></param>
|
||||
/// <returns></returns>
|
||||
/// <remarks>Does not update connected series and libraries</remarks>
|
||||
Task<UserReadingProfileDto> UpdateReadingProfile(int userId, UserReadingProfileDto dto);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a given profile for a user
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="UnauthorizedAccessException"></exception>
|
||||
/// <exception cref="KavitaException">The default profile for the user cannot be deleted</exception>
|
||||
Task DeleteReadingProfile(int userId, int profileId);
|
||||
|
||||
/// <summary>
|
||||
/// Binds the reading profile to the series, and remove the implicit RP from the series if it exists
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <returns></returns>
|
||||
Task AddProfileToSeries(int userId, int profileId, int seriesId);
|
||||
/// <summary>
|
||||
/// Binds the reading profile to many series, and remove the implicit RP from the series if it exists
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <param name="seriesIds"></param>
|
||||
/// <returns></returns>
|
||||
Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds);
|
||||
/// <summary>
|
||||
/// Remove all reading profiles bound to the series
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <returns></returns>
|
||||
Task ClearSeriesProfile(int userId, int seriesId);
|
||||
|
||||
/// <summary>
|
||||
/// Bind the reading profile to the library
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <returns></returns>
|
||||
Task AddProfileToLibrary(int userId, int profileId, int libraryId);
|
||||
/// <summary>
|
||||
/// Remove the reading profile bound to the library, if it exists
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <returns></returns>
|
||||
Task ClearLibraryProfile(int userId, int libraryId);
|
||||
/// <summary>
|
||||
/// Returns the bound Reading Profile to a Library
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="libraryId"></param>
|
||||
/// <returns></returns>
|
||||
Task<UserReadingProfileDto?> GetReadingProfileDtoForLibrary(int userId, int libraryId);
|
||||
}
|
||||
|
||||
public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService localizationService, IMapper mapper): IReadingProfileService
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to resolve the Reading Profile for a given Series. Will first check (optionally) Implicit profiles, then check for a bound Series profile, then a bound
|
||||
/// Library profile, then default to the default profile.
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="seriesId"></param>
|
||||
/// <param name="skipImplicit"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="KavitaException"></exception>
|
||||
public async Task<AppUserReadingProfile> GetReadingProfileForSeries(int userId, int seriesId, bool skipImplicit = false)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, skipImplicit);
|
||||
|
||||
// If there is an implicit, send back
|
||||
var implicitProfile =
|
||||
profiles.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind == ReadingProfileKind.Implicit);
|
||||
if (implicitProfile != null) return implicitProfile;
|
||||
|
||||
// Next check for a bound Series profile
|
||||
var seriesProfile = profiles
|
||||
.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind != ReadingProfileKind.Implicit);
|
||||
if (seriesProfile != null) return seriesProfile;
|
||||
|
||||
// Check for a library bound profile
|
||||
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
|
||||
if (series == null) throw new KavitaException(await localizationService.Translate(userId, "series-doesnt-exist"));
|
||||
|
||||
var libraryProfile = profiles
|
||||
.FirstOrDefault(p => p.LibraryIds.Contains(series.LibraryId) && p.Kind != ReadingProfileKind.Implicit);
|
||||
if (libraryProfile != null) return libraryProfile;
|
||||
|
||||
// Fallback to the default profile
|
||||
return profiles.First(p => p.Kind == ReadingProfileKind.Default);
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId, bool skipImplicit = false)
|
||||
{
|
||||
return mapper.Map<UserReadingProfileDto>(await GetReadingProfileForSeries(userId, seriesId, skipImplicit));
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto> UpdateParent(int userId, int seriesId, UserReadingProfileDto dto)
|
||||
{
|
||||
var parentProfile = await GetReadingProfileForSeries(userId, seriesId, true);
|
||||
|
||||
UpdateReaderProfileFields(parentProfile, dto, false);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(parentProfile);
|
||||
|
||||
// Remove the implicit profile when we UpdateParent (from reader) as it is implied that we are already bound with a non-implicit profile
|
||||
await DeleteImplicateReadingProfilesForSeries(userId, [seriesId]);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
return mapper.Map<UserReadingProfileDto>(parentProfile);
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto> UpdateReadingProfile(int userId, UserReadingProfileDto dto)
|
||||
{
|
||||
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, dto.Id);
|
||||
if (profile == null) throw new KavitaException("profile-does-not-exist");
|
||||
|
||||
UpdateReaderProfileFields(profile, dto);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profile);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
return mapper.Map<UserReadingProfileDto>(profile);
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto> CreateReadingProfile(int userId, UserReadingProfileDto dto)
|
||||
{
|
||||
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
|
||||
if (user == null) throw new UnauthorizedAccessException();
|
||||
|
||||
if (await unitOfWork.AppUserReadingProfileRepository.IsProfileNameInUse(userId, dto.Name)) throw new KavitaException("name-already-in-use");
|
||||
|
||||
var newProfile = new AppUserReadingProfileBuilder(user.Id).Build();
|
||||
UpdateReaderProfileFields(newProfile, dto);
|
||||
|
||||
unitOfWork.AppUserReadingProfileRepository.Add(newProfile);
|
||||
user.ReadingProfiles.Add(newProfile);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
|
||||
return mapper.Map<UserReadingProfileDto>(newProfile);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Promotes the implicit profile to a user profile. Removes the series from other profiles.
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="profileId"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<UserReadingProfileDto> PromoteImplicitProfile(int userId, int profileId)
|
||||
{
|
||||
// Get all the user's profiles including the implicit
|
||||
var allUserProfiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, false);
|
||||
var profileToPromote = allUserProfiles.First(r => r.Id == profileId);
|
||||
var seriesId = profileToPromote.SeriesIds[0]; // An Implicit series can only be bound to 1 Series
|
||||
|
||||
// Check if there are any reading profiles (Series) already bound to the series
|
||||
var existingSeriesProfile = allUserProfiles.FirstOrDefault(r => r.SeriesIds.Contains(seriesId) && r.Kind == ReadingProfileKind.User);
|
||||
if (existingSeriesProfile != null)
|
||||
{
|
||||
existingSeriesProfile.SeriesIds.Remove(seriesId);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(existingSeriesProfile);
|
||||
}
|
||||
|
||||
// Convert the implicit profile into a proper Series
|
||||
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
|
||||
if (series == null) throw new KavitaException("series-doesnt-exist"); // Shouldn't happen
|
||||
|
||||
profileToPromote.Kind = ReadingProfileKind.User;
|
||||
profileToPromote.Name = await localizationService.Translate(userId, "generated-reading-profile-name", series.Name);
|
||||
profileToPromote.Name = EnsureUniqueProfileName(allUserProfiles, profileToPromote.Name);
|
||||
profileToPromote.NormalizedName = profileToPromote.Name.ToNormalized();
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profileToPromote);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
|
||||
return mapper.Map<UserReadingProfileDto>(profileToPromote);
|
||||
}
|
||||
|
||||
private static string EnsureUniqueProfileName(IList<AppUserReadingProfile> allUserProfiles, string name)
|
||||
{
|
||||
var counter = 1;
|
||||
var newName = name;
|
||||
while (allUserProfiles.Any(p => p.Name == newName))
|
||||
{
|
||||
newName = $"{name} ({counter})";
|
||||
counter++;
|
||||
}
|
||||
|
||||
return newName;
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto> UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto)
|
||||
{
|
||||
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
|
||||
if (user == null) throw new UnauthorizedAccessException();
|
||||
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
|
||||
var existingProfile = profiles.FirstOrDefault(rp => rp.Kind == ReadingProfileKind.Implicit && rp.SeriesIds.Contains(seriesId));
|
||||
|
||||
// Series already had an implicit profile, update it
|
||||
if (existingProfile is {Kind: ReadingProfileKind.Implicit})
|
||||
{
|
||||
UpdateReaderProfileFields(existingProfile, dto, false);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(existingProfile);
|
||||
await unitOfWork.CommitAsync();
|
||||
|
||||
return mapper.Map<UserReadingProfileDto>(existingProfile);
|
||||
}
|
||||
|
||||
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId) ?? throw new KeyNotFoundException();
|
||||
var newProfile = new AppUserReadingProfileBuilder(userId)
|
||||
.WithSeries(series)
|
||||
.WithKind(ReadingProfileKind.Implicit)
|
||||
.Build();
|
||||
|
||||
// Set name to something fitting for debugging if needed
|
||||
UpdateReaderProfileFields(newProfile, dto, false);
|
||||
newProfile.Name = $"Implicit Profile for {seriesId}";
|
||||
newProfile.NormalizedName = newProfile.Name.ToNormalized();
|
||||
|
||||
user.ReadingProfiles.Add(newProfile);
|
||||
await unitOfWork.CommitAsync();
|
||||
|
||||
return mapper.Map<UserReadingProfileDto>(newProfile);
|
||||
}
|
||||
|
||||
public async Task DeleteReadingProfile(int userId, int profileId)
|
||||
{
|
||||
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
|
||||
if (profile == null) throw new KavitaException("profile-doesnt-exist");
|
||||
|
||||
if (profile.Kind == ReadingProfileKind.Default) throw new KavitaException("cant-delete-default-profile");
|
||||
|
||||
unitOfWork.AppUserReadingProfileRepository.Remove(profile);
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task AddProfileToSeries(int userId, int profileId, int seriesId)
|
||||
{
|
||||
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
|
||||
if (profile == null) throw new KavitaException("profile-doesnt-exist");
|
||||
|
||||
await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
|
||||
|
||||
profile.SeriesIds.Add(seriesId);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profile);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds)
|
||||
{
|
||||
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
|
||||
if (profile == null) throw new KavitaException("profile-doesnt-exist");
|
||||
|
||||
await DeleteImplicitAndRemoveFromUserProfiles(userId, seriesIds, []);
|
||||
|
||||
profile.SeriesIds.AddRange(seriesIds.Except(profile.SeriesIds));
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profile);
|
||||
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task ClearSeriesProfile(int userId, int seriesId)
|
||||
{
|
||||
await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task AddProfileToLibrary(int userId, int profileId, int libraryId)
|
||||
{
|
||||
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
|
||||
if (profile == null) throw new KavitaException("profile-doesnt-exist");
|
||||
|
||||
await DeleteImplicitAndRemoveFromUserProfiles(userId, [], [libraryId]);
|
||||
|
||||
profile.LibraryIds.Add(libraryId);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profile);
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
public async Task ClearLibraryProfile(int userId, int libraryId)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
|
||||
var libraryProfile = profiles.FirstOrDefault(p => p.LibraryIds.Contains(libraryId));
|
||||
if (libraryProfile != null)
|
||||
{
|
||||
libraryProfile.LibraryIds.Remove(libraryId);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(libraryProfile);
|
||||
}
|
||||
|
||||
|
||||
if (unitOfWork.HasChanges())
|
||||
{
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<UserReadingProfileDto?> GetReadingProfileDtoForLibrary(int userId, int libraryId)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, true);
|
||||
return mapper.Map<UserReadingProfileDto>(profiles.FirstOrDefault(p => p.LibraryIds.Contains(libraryId)));
|
||||
}
|
||||
|
||||
private async Task DeleteImplicitAndRemoveFromUserProfiles(int userId, IList<int> seriesIds, IList<int> libraryIds)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
|
||||
var implicitProfiles = profiles
|
||||
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
|
||||
.Where(rp => rp.Kind == ReadingProfileKind.Implicit)
|
||||
.ToList();
|
||||
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
|
||||
|
||||
var nonImplicitProfiles = profiles
|
||||
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any() || rp.LibraryIds.Intersect(libraryIds).Any())
|
||||
.Where(rp => rp.Kind != ReadingProfileKind.Implicit);
|
||||
|
||||
foreach (var profile in nonImplicitProfiles)
|
||||
{
|
||||
profile.SeriesIds.RemoveAll(seriesIds.Contains);
|
||||
profile.LibraryIds.RemoveAll(libraryIds.Contains);
|
||||
unitOfWork.AppUserReadingProfileRepository.Update(profile);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DeleteImplicateReadingProfilesForSeries(int userId, IList<int> seriesIds)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
|
||||
var implicitProfiles = profiles
|
||||
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
|
||||
.Where(rp => rp.Kind == ReadingProfileKind.Implicit)
|
||||
.ToList();
|
||||
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
|
||||
}
|
||||
|
||||
private async Task RemoveSeriesFromUserProfiles(int userId, IList<int> seriesIds)
|
||||
{
|
||||
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
|
||||
var userProfiles = profiles
|
||||
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
|
||||
.Where(rp => rp.Kind == ReadingProfileKind.User)
|
||||
.ToList();
|
||||
|
||||
unitOfWork.AppUserReadingProfileRepository.RemoveRange(userProfiles);
|
||||
}
|
||||
|
||||
public static void UpdateReaderProfileFields(AppUserReadingProfile existingProfile, UserReadingProfileDto dto, bool updateName = true)
|
||||
{
|
||||
if (updateName && !string.IsNullOrEmpty(dto.Name) && existingProfile.NormalizedName != dto.Name.ToNormalized())
|
||||
{
|
||||
existingProfile.Name = dto.Name;
|
||||
existingProfile.NormalizedName = dto.Name.ToNormalized();
|
||||
}
|
||||
|
||||
// Manga Reader
|
||||
existingProfile.ReadingDirection = dto.ReadingDirection;
|
||||
existingProfile.ScalingOption = dto.ScalingOption;
|
||||
existingProfile.PageSplitOption = dto.PageSplitOption;
|
||||
existingProfile.ReaderMode = dto.ReaderMode;
|
||||
existingProfile.AutoCloseMenu = dto.AutoCloseMenu;
|
||||
existingProfile.ShowScreenHints = dto.ShowScreenHints;
|
||||
existingProfile.EmulateBook = dto.EmulateBook;
|
||||
existingProfile.LayoutMode = dto.LayoutMode;
|
||||
existingProfile.BackgroundColor = string.IsNullOrEmpty(dto.BackgroundColor) ? "#000000" : dto.BackgroundColor;
|
||||
existingProfile.SwipeToPaginate = dto.SwipeToPaginate;
|
||||
existingProfile.AllowAutomaticWebtoonReaderDetection = dto.AllowAutomaticWebtoonReaderDetection;
|
||||
existingProfile.WidthOverride = dto.WidthOverride;
|
||||
existingProfile.DisableWidthOverride = dto.DisableWidthOverride;
|
||||
|
||||
// Book Reader
|
||||
existingProfile.BookReaderMargin = dto.BookReaderMargin;
|
||||
existingProfile.BookReaderLineSpacing = dto.BookReaderLineSpacing;
|
||||
existingProfile.BookReaderFontSize = dto.BookReaderFontSize;
|
||||
existingProfile.BookReaderFontFamily = dto.BookReaderFontFamily;
|
||||
existingProfile.BookReaderTapToPaginate = dto.BookReaderTapToPaginate;
|
||||
existingProfile.BookReaderReadingDirection = dto.BookReaderReadingDirection;
|
||||
existingProfile.BookReaderWritingStyle = dto.BookReaderWritingStyle;
|
||||
existingProfile.BookThemeName = dto.BookReaderThemeName;
|
||||
existingProfile.BookReaderLayoutMode = dto.BookReaderLayoutMode;
|
||||
existingProfile.BookReaderImmersiveMode = dto.BookReaderImmersiveMode;
|
||||
|
||||
// PDF Reading
|
||||
existingProfile.PdfTheme = dto.PdfTheme;
|
||||
existingProfile.PdfScrollMode = dto.PdfScrollMode;
|
||||
existingProfile.PdfSpreadMode = dto.PdfSpreadMode;
|
||||
}
|
||||
}
|
||||
|
|
@ -206,17 +206,12 @@ public class CoverDbService : ICoverDbService
|
|||
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
|
||||
using var image = Image.NewFromStream(publisherStream);
|
||||
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());
|
||||
|
||||
return filename;
|
||||
|
|
@ -302,7 +297,27 @@ public class CoverDbService : ICoverDbService
|
|||
.GetStreamAsync();
|
||||
|
||||
using var image = Image.NewFromStream(imageStream);
|
||||
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;
|
||||
}
|
||||
|
|
@ -385,14 +400,13 @@ public class CoverDbService : ICoverDbService
|
|||
private async Task<string> FallbackToKavitaReaderPublisher(string publisherName)
|
||||
{
|
||||
const string publisherFileName = "publishers.txt";
|
||||
var externalLink = string.Empty;
|
||||
var allOverrides = await GetCachedData(publisherFileName) ??
|
||||
await $"{NewHost}publishers/{publisherFileName}".GetStringAsync();
|
||||
|
||||
// Cache immediately
|
||||
await CacheDataAsync(publisherFileName, allOverrides);
|
||||
|
||||
if (string.IsNullOrEmpty(allOverrides)) return externalLink;
|
||||
if (string.IsNullOrEmpty(allOverrides)) return string.Empty;
|
||||
|
||||
var externalFile = allOverrides
|
||||
.Split("\n")
|
||||
|
|
@ -415,7 +429,7 @@ public class CoverDbService : ICoverDbService
|
|||
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)
|
||||
|
|
@ -572,8 +586,7 @@ public class CoverDbService : ICoverDbService
|
|||
var choseNewImage = string.Equals(betterImage, tempFullPath, StringComparison.OrdinalIgnoreCase);
|
||||
if (choseNewImage)
|
||||
{
|
||||
|
||||
// Don't delete series cover, unless it's an override, otherwise the first chapter cover will be null
|
||||
// Don't delete the Series cover unless it is an override, otherwise the first chapter will be null
|
||||
if (existingPath.Contains(ImageService.GetSeriesFormat(series.Id)))
|
||||
{
|
||||
_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)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(url))
|
||||
|
|
|
|||
|
|
@ -1159,6 +1159,12 @@ public static partial class Parser
|
|||
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)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name)) return string.Empty;
|
||||
|
|
|
|||
|
|
@ -293,6 +293,9 @@ public class Startup
|
|||
await ManualMigrateScrobbleSpecials.Migrate(dataContext, logger);
|
||||
await ManualMigrateScrobbleEventGen.Migrate(dataContext, logger);
|
||||
|
||||
// v0.8.7
|
||||
await ManualMigrateReadingProfiles.Migrate(dataContext, logger);
|
||||
|
||||
#endregion
|
||||
|
||||
// Update the version in the DB after all migrations are run
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Company>kavitareader.com</Company>
|
||||
<Product>Kavita</Product>
|
||||
<AssemblyVersion>0.8.6.11</AssemblyVersion>
|
||||
<AssemblyVersion>0.8.6.15</AssemblyVersion>
|
||||
<NeutralLanguage>en</NeutralLanguage>
|
||||
<TieredPGO>true</TieredPGO>
|
||||
</PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -107,13 +107,10 @@ Support this project by becoming a sponsor. Your logo will show up here with a l
|
|||
## Mega Sponsors
|
||||
<img src="https://opencollective.com/Kavita/tiers/mega-sponsor.svg?width=890"></a>
|
||||
|
||||
## JetBrains
|
||||
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.
|
||||
|
||||
* [<img src="/Logo/rider.svg" alt="" width="32"> Rider](http://www.jetbrains.com/rider/)
|
||||
## Powered By
|
||||
[](https://jb.gg/OpenSource)
|
||||
|
||||
### License
|
||||
|
||||
* [GNU GPL v3](http://www.gnu.org/licenses/gpl.html)
|
||||
* 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 {LibraryType} from "../library/library";
|
||||
|
||||
export interface ManageMatchFilter {
|
||||
matchStateOption: MatchStateOption;
|
||||
libraryType: LibraryType | -1;
|
||||
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 allKavitaPlusMetadataApplicableTypes = [LibraryType.Manga, LibraryType.LightNovel, LibraryType.ComicVine, LibraryType.Comic];
|
||||
export const allKavitaPlusScrobbleEligibleTypes = [LibraryType.Manga, LibraryType.LightNovel];
|
||||
|
||||
export interface Library {
|
||||
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 {
|
||||
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 {
|
||||
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;
|
||||
translationCompletion: number;
|
||||
isRtL: boolean;
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import {IHasCover} from "../common/i-has-cover";
|
|||
|
||||
export enum PersonRole {
|
||||
Other = 1,
|
||||
Artist = 2,
|
||||
Writer = 3,
|
||||
Penciller = 4,
|
||||
Inker = 5,
|
||||
|
|
@ -32,3 +31,22 @@ export interface Person extends IHasCover {
|
|||
primaryColor: 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 {SeriesFilterV2} from "./v2/series-filter-v2";
|
||||
import {FilterV2} from "./v2/filter-v2";
|
||||
|
||||
export interface FilterItem<T> {
|
||||
title: string;
|
||||
|
|
@ -7,10 +7,6 @@ export interface FilterItem<T> {
|
|||
selected: boolean;
|
||||
}
|
||||
|
||||
export interface SortOptions {
|
||||
sortField: SortField;
|
||||
isAscending: boolean;
|
||||
}
|
||||
|
||||
export enum SortField {
|
||||
SortName = 1,
|
||||
|
|
@ -27,7 +23,7 @@ export enum SortField {
|
|||
Random = 9
|
||||
}
|
||||
|
||||
export const allSortFields = Object.keys(SortField)
|
||||
export const allSeriesSortFields = Object.keys(SortField)
|
||||
.filter(key => !isNaN(Number(key)) && parseInt(key, 10) >= 0)
|
||||
.map(key => parseInt(key, 10)) as SortField[];
|
||||
|
||||
|
|
@ -54,8 +50,8 @@ export const mangaFormatFilters = [
|
|||
}
|
||||
];
|
||||
|
||||
export interface FilterEvent {
|
||||
filterV2: SeriesFilterV2;
|
||||
export interface FilterEvent<TFilter extends number = number, TSort extends number = number> {
|
||||
filterV2: FilterV2<TFilter, TSort>;
|
||||
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));
|
||||
|
||||
export const allFields = enumArray
|
||||
export const allSeriesFilterFields = enumArray
|
||||
.map(key => parseInt(key.key, 10))as FilterField[];
|
||||
|
||||
export const allPeople = [
|
||||
|
|
@ -66,7 +66,6 @@ export const allPeople = [
|
|||
|
||||
export const personRoleForFilterField = (role: PersonRole) => {
|
||||
switch (role) {
|
||||
case PersonRole.Artist: return FilterField.CoverArtist;
|
||||
case PersonRole.Character: return FilterField.Characters;
|
||||
case PersonRole.Colorist: return FilterField.Colorist;
|
||||
case PersonRole.CoverArtist: return FilterField.CoverArtist;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import { FilterComparison } from "./filter-comparison";
|
||||
import { FilterField } from "./filter-field";
|
||||
import {FilterComparison} from "./filter-comparison";
|
||||
|
||||
export interface FilterStatement {
|
||||
export interface FilterStatement<T extends number = number> {
|
||||
comparison: FilterComparison;
|
||||
field: FilterField;
|
||||
field: T;
|
||||
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;
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { ThemeProvider } from "./site-theme";
|
||||
import {ThemeProvider} from "./site-theme";
|
||||
|
||||
/**
|
||||
* Theme for the the book reader contents
|
||||
* Theme for the book reader contents
|
||||
*/
|
||||
export interface BookTheme {
|
||||
name: string;
|
||||
|
|
|
|||
|
|
@ -1,47 +1,7 @@
|
|||
import {LayoutMode} from 'src/app/manga-reader/_models/layout-mode';
|
||||
import {BookPageLayoutMode} from '../readers/book-page-layout-mode';
|
||||
import {PageLayoutMode} from '../page-layout-mode';
|
||||
import {PageSplitOption} from './page-split-option';
|
||||
import {ReaderMode} from './reader-mode';
|
||||
import {ReadingDirection} from './reading-direction';
|
||||
import {ScalingOption} from './scaling-option';
|
||||
import {SiteTheme} from './site-theme';
|
||||
import {WritingStyle} from "./writing-style";
|
||||
import {PdfTheme} from "./pdf-theme";
|
||||
import {PdfScrollMode} from "./pdf-scroll-mode";
|
||||
import {PdfLayoutMode} from "./pdf-layout-mode";
|
||||
import {PdfSpreadMode} from "./pdf-spread-mode";
|
||||
|
||||
export interface Preferences {
|
||||
// Manga Reader
|
||||
readingDirection: ReadingDirection;
|
||||
scalingOption: ScalingOption;
|
||||
pageSplitOption: PageSplitOption;
|
||||
readerMode: ReaderMode;
|
||||
autoCloseMenu: boolean;
|
||||
layoutMode: LayoutMode;
|
||||
backgroundColor: string;
|
||||
showScreenHints: boolean;
|
||||
emulateBook: boolean;
|
||||
swipeToPaginate: boolean;
|
||||
allowAutomaticWebtoonReaderDetection: boolean;
|
||||
|
||||
// Book Reader
|
||||
bookReaderMargin: number;
|
||||
bookReaderLineSpacing: number;
|
||||
bookReaderFontSize: number;
|
||||
bookReaderFontFamily: string;
|
||||
bookReaderTapToPaginate: boolean;
|
||||
bookReaderReadingDirection: ReadingDirection;
|
||||
bookReaderWritingStyle: WritingStyle;
|
||||
bookReaderThemeName: string;
|
||||
bookReaderLayoutMode: BookPageLayoutMode;
|
||||
bookReaderImmersiveMode: boolean;
|
||||
|
||||
// PDF Reader
|
||||
pdfTheme: PdfTheme;
|
||||
pdfScrollMode: PdfScrollMode;
|
||||
pdfSpreadMode: PdfSpreadMode;
|
||||
|
||||
// Global
|
||||
theme: SiteTheme;
|
||||
|
|
@ -58,15 +18,3 @@ export interface Preferences {
|
|||
wantToReadSync: boolean;
|
||||
}
|
||||
|
||||
export const readingDirections = [{text: 'left-to-right', value: ReadingDirection.LeftToRight}, {text: 'right-to-left', value: ReadingDirection.RightToLeft}];
|
||||
export const bookWritingStyles = [{text: 'horizontal', value: WritingStyle.Horizontal}, {text: 'vertical', value: WritingStyle.Vertical}];
|
||||
export const scalingOptions = [{text: 'automatic', value: ScalingOption.Automatic}, {text: 'fit-to-height', value: ScalingOption.FitToHeight}, {text: 'fit-to-width', value: ScalingOption.FitToWidth}, {text: 'original', value: ScalingOption.Original}];
|
||||
export const pageSplitOptions = [{text: 'fit-to-screen', value: PageSplitOption.FitSplit}, {text: 'right-to-left', value: PageSplitOption.SplitRightToLeft}, {text: 'left-to-right', value: PageSplitOption.SplitLeftToRight}, {text: 'no-split', value: PageSplitOption.NoSplit}];
|
||||
export const readingModes = [{text: 'left-to-right', value: ReaderMode.LeftRight}, {text: 'up-to-down', value: ReaderMode.UpDown}, {text: 'webtoon', value: ReaderMode.Webtoon}];
|
||||
export const layoutModes = [{text: 'single', value: LayoutMode.Single}, {text: 'double', value: LayoutMode.Double}, {text: 'double-manga', value: LayoutMode.DoubleReversed}]; // TODO: Build this, {text: 'Double (No Cover)', value: LayoutMode.DoubleNoCover}
|
||||
export const bookLayoutModes = [{text: 'scroll', value: BookPageLayoutMode.Default}, {text: '1-column', value: BookPageLayoutMode.Column1}, {text: '2-column', value: BookPageLayoutMode.Column2}];
|
||||
export const pageLayoutModes = [{text: 'cards', value: PageLayoutMode.Cards}, {text: 'list', value: PageLayoutMode.List}];
|
||||
export const pdfLayoutModes = [{text: 'pdf-multiple', value: PdfLayoutMode.Multiple}, {text: 'pdf-book', value: PdfLayoutMode.Book}];
|
||||
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 pdfThemes = [{text: 'pdf-light', value: PdfTheme.Light}, {text: 'pdf-dark', value: PdfTheme.Dark}];
|
||||
|
|
|
|||
80
UI/Web/src/app/_models/preferences/reading-profiles.ts
Normal file
80
UI/Web/src/app/_models/preferences/reading-profiles.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import {LayoutMode} from 'src/app/manga-reader/_models/layout-mode';
|
||||
import {BookPageLayoutMode} from '../readers/book-page-layout-mode';
|
||||
import {PageLayoutMode} from '../page-layout-mode';
|
||||
import {PageSplitOption} from './page-split-option';
|
||||
import {ReaderMode} from './reader-mode';
|
||||
import {ReadingDirection} from './reading-direction';
|
||||
import {ScalingOption} from './scaling-option';
|
||||
import {WritingStyle} from "./writing-style";
|
||||
import {PdfTheme} from "./pdf-theme";
|
||||
import {PdfScrollMode} from "./pdf-scroll-mode";
|
||||
import {PdfLayoutMode} from "./pdf-layout-mode";
|
||||
import {PdfSpreadMode} from "./pdf-spread-mode";
|
||||
import {Series} from "../series";
|
||||
import {Library} from "../library/library";
|
||||
import {UserBreakpoint} from "../../shared/_services/utility.service";
|
||||
|
||||
export enum ReadingProfileKind {
|
||||
Default = 0,
|
||||
User = 1,
|
||||
Implicit = 2,
|
||||
}
|
||||
|
||||
export interface ReadingProfile {
|
||||
|
||||
id: number;
|
||||
name: string;
|
||||
normalizedName: string;
|
||||
kind: ReadingProfileKind;
|
||||
|
||||
// Manga Reader
|
||||
readingDirection: ReadingDirection;
|
||||
scalingOption: ScalingOption;
|
||||
pageSplitOption: PageSplitOption;
|
||||
readerMode: ReaderMode;
|
||||
autoCloseMenu: boolean;
|
||||
layoutMode: LayoutMode;
|
||||
backgroundColor: string;
|
||||
showScreenHints: boolean;
|
||||
emulateBook: boolean;
|
||||
swipeToPaginate: boolean;
|
||||
allowAutomaticWebtoonReaderDetection: boolean;
|
||||
widthOverride?: number;
|
||||
disableWidthOverride: UserBreakpoint;
|
||||
|
||||
// Book Reader
|
||||
bookReaderMargin: number;
|
||||
bookReaderLineSpacing: number;
|
||||
bookReaderFontSize: number;
|
||||
bookReaderFontFamily: string;
|
||||
bookReaderTapToPaginate: boolean;
|
||||
bookReaderReadingDirection: ReadingDirection;
|
||||
bookReaderWritingStyle: WritingStyle;
|
||||
bookReaderThemeName: string;
|
||||
bookReaderLayoutMode: BookPageLayoutMode;
|
||||
bookReaderImmersiveMode: boolean;
|
||||
|
||||
// PDF Reader
|
||||
pdfTheme: PdfTheme;
|
||||
pdfScrollMode: PdfScrollMode;
|
||||
pdfSpreadMode: PdfSpreadMode;
|
||||
|
||||
// relations
|
||||
seriesIds: number[];
|
||||
libraryIds: number[];
|
||||
|
||||
}
|
||||
|
||||
export const readingDirections = [{text: 'left-to-right', value: ReadingDirection.LeftToRight}, {text: 'right-to-left', value: ReadingDirection.RightToLeft}];
|
||||
export const bookWritingStyles = [{text: 'horizontal', value: WritingStyle.Horizontal}, {text: 'vertical', value: WritingStyle.Vertical}];
|
||||
export const scalingOptions = [{text: 'automatic', value: ScalingOption.Automatic}, {text: 'fit-to-height', value: ScalingOption.FitToHeight}, {text: 'fit-to-width', value: ScalingOption.FitToWidth}, {text: 'original', value: ScalingOption.Original}];
|
||||
export const pageSplitOptions = [{text: 'fit-to-screen', value: PageSplitOption.FitSplit}, {text: 'right-to-left', value: PageSplitOption.SplitRightToLeft}, {text: 'left-to-right', value: PageSplitOption.SplitLeftToRight}, {text: 'no-split', value: PageSplitOption.NoSplit}];
|
||||
export const readingModes = [{text: 'left-to-right', value: ReaderMode.LeftRight}, {text: 'up-to-down', value: ReaderMode.UpDown}, {text: 'webtoon', value: ReaderMode.Webtoon}];
|
||||
export const layoutModes = [{text: 'single', value: LayoutMode.Single}, {text: 'double', value: LayoutMode.Double}, {text: 'double-manga', value: LayoutMode.DoubleReversed}]; // TODO: Build this, {text: 'Double (No Cover)', value: LayoutMode.DoubleNoCover}
|
||||
export const bookLayoutModes = [{text: 'scroll', value: BookPageLayoutMode.Default}, {text: '1-column', value: BookPageLayoutMode.Column1}, {text: '2-column', value: BookPageLayoutMode.Column2}];
|
||||
export const pageLayoutModes = [{text: 'cards', value: PageLayoutMode.Cards}, {text: 'list', value: PageLayoutMode.List}];
|
||||
export const pdfLayoutModes = [{text: 'pdf-multiple', value: PdfLayoutMode.Multiple}, {text: 'pdf-book', value: PdfLayoutMode.Book}];
|
||||
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 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',
|
||||
UpdateDocker = 'https://wiki.kavitareader.com/guides/updating/updating-docker',
|
||||
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 { PersonRole } from '../_models/metadata/person';
|
||||
import {translate, TranslocoService} from "@jsverse/transloco";
|
||||
import {Pipe, PipeTransform} from '@angular/core';
|
||||
import {PersonRole} from '../_models/metadata/person';
|
||||
import {translate} from "@jsverse/transloco";
|
||||
|
||||
@Pipe({
|
||||
name: 'personRole',
|
||||
|
|
@ -10,8 +10,6 @@ export class PersonRolePipe implements PipeTransform {
|
|||
|
||||
transform(value: PersonRole): string {
|
||||
switch (value) {
|
||||
case PersonRole.Artist:
|
||||
return translate('person-role-pipe.artist');
|
||||
case PersonRole.Character:
|
||||
return translate('person-role-pipe.character');
|
||||
case PersonRole.Colorist:
|
||||
|
|
|
|||
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