Use JSON columns instead of junction tables

This commit is contained in:
Amelia 2025-06-01 22:47:12 +02:00
parent 8fd50d030b
commit b36f6c8f0b
35 changed files with 471 additions and 1103 deletions

View file

@ -4,7 +4,6 @@ using API.Data.Repositories;
using API.DTOs; using API.DTOs;
using API.Entities; using API.Entities;
using API.Entities.Enums; using API.Entities.Enums;
using API.Extensions.QueryExtensions;
using API.Helpers.Builders; using API.Helpers.Builders;
using API.Services; using API.Services;
using API.Tests.Helpers; using API.Tests.Helpers;
@ -18,7 +17,11 @@ namespace API.Tests.Services;
public class ReadingProfileServiceTest: AbstractDbTest public class ReadingProfileServiceTest: AbstractDbTest
{ {
public async Task<(IReadingProfileService, AppUser, Library, Series)> Setup() /// <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(); var user = new AppUserBuilder("amelia", "amelia@localhost").Build();
Context.AppUser.Add(user); Context.AppUser.Add(user);
@ -33,7 +36,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
user.Libraries.Add(library); user.Libraries.Add(library);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var rps = new ReadingProfileService(UnitOfWork, Substitute.For<ILocalizationService>()); var rps = new ReadingProfileService(UnitOfWork, Substitute.For<ILocalizationService>(), Mapper);
user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.UserPreferences); user = await UnitOfWork.UserRepository.GetUserByIdAsync(1, AppUserIncludes.UserPreferences);
return (rps, user, library, series); return (rps, user, library, series);
@ -46,7 +49,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
var (rps, user, library, series) = await Setup(); var (rps, user, library, series) = await Setup();
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithImplicit(true) .WithKind(ReadingProfileKind.Implicit)
.WithSeries(series) .WithSeries(series)
.WithName("Implicit Profile") .WithName("Implicit Profile")
.Build(); .Build();
@ -56,31 +59,23 @@ public class ReadingProfileServiceTest: AbstractDbTest
.WithName("Non-implicit Profile") .WithName("Non-implicit Profile")
.Build(); .Build();
user.UserPreferences.ReadingProfiles.Add(profile); user.ReadingProfiles.Add(profile);
user.UserPreferences.ReadingProfiles.Add(profile2); user.ReadingProfiles.Add(profile2);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var seriesProfile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(user.Id, series.Id); var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.Equal("Implicit Profile", seriesProfile.Name); Assert.Equal("Implicit Profile", seriesProfile.Name);
var seriesProfileDto = await UnitOfWork.AppUserReadingProfileRepository.GetProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfileDto);
Assert.Equal("Implicit Profile", seriesProfileDto.Name);
await rps.UpdateReadingProfile(user.Id, new UserReadingProfileDto await rps.UpdateReadingProfile(user.Id, new UserReadingProfileDto
{ {
Id = profile2.Id, Id = profile2.Id,
WidthOverride = 23, WidthOverride = 23,
}); });
seriesProfile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(user.Id, series.Id); seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.Equal("Non-implicit Profile", seriesProfile.Name); Assert.Equal("Non-implicit Profile", seriesProfile.Name);
seriesProfileDto = await UnitOfWork.AppUserReadingProfileRepository.GetProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfileDto);
Assert.Equal("Non-implicit Profile", seriesProfileDto.Name);
} }
[Fact] [Fact]
@ -89,11 +84,10 @@ public class ReadingProfileServiceTest: AbstractDbTest
await ResetDb(); await ResetDb();
var (rps, user, _, _) = await Setup(); var (rps, user, _, _) = await Setup();
var profile = new AppUserReadingProfileBuilder(user.Id).Build(); var profile = new AppUserReadingProfileBuilder(user.Id)
Context.AppUserReadingProfile.Add(profile); .WithKind(ReadingProfileKind.Default)
await UnitOfWork.CommitAsync(); .Build();
Context.AppUserReadingProfiles.Add(profile);
user.UserPreferences.DefaultReadingProfileId = profile.Id;
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await Assert.ThrowsAsync<KavitaException>(async () => await Assert.ThrowsAsync<KavitaException>(async () =>
@ -102,13 +96,13 @@ public class ReadingProfileServiceTest: AbstractDbTest
}); });
var profile2 = new AppUserReadingProfileBuilder(user.Id).Build(); var profile2 = new AppUserReadingProfileBuilder(user.Id).Build();
Context.AppUserReadingProfile.Add(profile2); Context.AppUserReadingProfiles.Add(profile2);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.DeleteReadingProfile(user.Id, profile2.Id); await rps.DeleteReadingProfile(user.Id, profile2.Id);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var allProfiles = await Context.AppUserReadingProfile.ToListAsync(); var allProfiles = await Context.AppUserReadingProfiles.ToListAsync();
Assert.Single(allProfiles); Assert.Single(allProfiles);
} }
@ -127,14 +121,14 @@ public class ReadingProfileServiceTest: AbstractDbTest
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto); await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
var profile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(user.Id, series.Id); var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
Assert.NotNull(profile); Assert.NotNull(profile);
Assert.Contains(profile.Series, s => s.SeriesId == series.Id); Assert.Contains(profile.SeriesIds, s => s == series.Id);
Assert.True(profile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
} }
[Fact] [Fact]
public async Task UpdateImplicitReadingProfile_DoesnotCreateNew() public async Task UpdateImplicitReadingProfile_DoesNotCreateNew()
{ {
await ResetDb(); await ResetDb();
var (rps, user, _, series) = await Setup(); var (rps, user, _, series) = await Setup();
@ -148,10 +142,10 @@ public class ReadingProfileServiceTest: AbstractDbTest
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto); await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
var profile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(user.Id, series.Id); var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
Assert.NotNull(profile); Assert.NotNull(profile);
Assert.Contains(profile.Series, s => s.SeriesId == series.Id); Assert.Contains(profile.SeriesIds, s => s == series.Id);
Assert.True(profile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
dto = new UserReadingProfileDto dto = new UserReadingProfileDto
{ {
@ -159,14 +153,15 @@ public class ReadingProfileServiceTest: AbstractDbTest
}; };
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto); await rps.UpdateImplicitReadingProfile(user.Id, series.Id, dto);
profile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(user.Id, series.Id); profile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
Assert.NotNull(profile); Assert.NotNull(profile);
Assert.Contains(profile.Series, s => s.SeriesId == series.Id); Assert.Contains(profile.SeriesIds, s => s == series.Id);
Assert.True(profile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, profile.Kind);
Assert.Equal(ReaderMode.LeftRight, profile.ReaderMode); Assert.Equal(ReaderMode.LeftRight, profile.ReaderMode);
var implicitCount = await Context.AppUserReadingProfile var implicitCount = await Context.AppUserReadingProfiles
.Where(p => p.Implicit).CountAsync(); .Where(p => p.Kind == ReadingProfileKind.Implicit)
.CountAsync();
Assert.Equal(1, implicitCount); Assert.Equal(1, implicitCount);
} }
@ -185,11 +180,12 @@ public class ReadingProfileServiceTest: AbstractDbTest
.WithName("Library Specific") .WithName("Library Specific")
.Build(); .Build();
var profile3 = new AppUserReadingProfileBuilder(user.Id) var profile3 = new AppUserReadingProfileBuilder(user.Id)
.WithKind(ReadingProfileKind.Default)
.WithName("Global") .WithName("Global")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
Context.AppUserReadingProfile.Add(profile2); Context.AppUserReadingProfiles.Add(profile2);
Context.AppUserReadingProfile.Add(profile3); Context.AppUserReadingProfiles.Add(profile3);
var series2 = new SeriesBuilder("Rainbows After Storms").Build(); var series2 = new SeriesBuilder("Rainbows After Storms").Build();
lib.Series.Add(series2); lib.Series.Add(series2);
@ -201,18 +197,15 @@ public class ReadingProfileServiceTest: AbstractDbTest
user.Libraries.Add(lib2); user.Libraries.Add(lib2);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
user.UserPreferences.DefaultReadingProfileId = profile3.Id; var p = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
await UnitOfWork.CommitAsync();
var p = await rps.GetReadingProfileForSeries(user.Id, series.Id);
Assert.NotNull(p); Assert.NotNull(p);
Assert.Equal("Series Specific", p.Name); Assert.Equal("Series Specific", p.Name);
p = await rps.GetReadingProfileForSeries(user.Id, series2.Id); p = await rps.GetReadingProfileDtoForSeries(user.Id, series2.Id);
Assert.NotNull(p); Assert.NotNull(p);
Assert.Equal("Library Specific", p.Name); Assert.Equal("Library Specific", p.Name);
p = await rps.GetReadingProfileForSeries(user.Id, series3.Id); p = await rps.GetReadingProfileDtoForSeries(user.Id, series3.Id);
Assert.NotNull(p); Assert.NotNull(p);
Assert.Equal("Global", p.Name); Assert.Equal("Global", p.Name);
} }
@ -232,16 +225,16 @@ public class ReadingProfileServiceTest: AbstractDbTest
.WithName("Profile 2") .WithName("Profile 2")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile1); Context.AppUserReadingProfiles.Add(profile1);
Context.AppUserReadingProfile.Add(profile2); Context.AppUserReadingProfiles.Add(profile2);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id); var profile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(profile); Assert.NotNull(profile);
Assert.Equal("Profile 1", profile.Name); Assert.Equal("Profile 1", profile.Name);
await rps.AddProfileToSeries(user.Id, profile2.Id, series.Id); await rps.AddProfileToSeries(user.Id, profile2.Id, series.Id);
profile = await rps.GetReadingProfileForSeries(user.Id, series.Id); profile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(profile); Assert.NotNull(profile);
Assert.Equal("Profile 2", profile.Name); Assert.Equal("Profile 2", profile.Name);
} }
@ -257,12 +250,12 @@ public class ReadingProfileServiceTest: AbstractDbTest
.WithName("Profile 1") .WithName("Profile 1")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile1); Context.AppUserReadingProfiles.Add(profile1);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.ClearSeriesProfile(user.Id, series.Id); await rps.ClearSeriesProfile(user.Id, series.Id);
var profile = await rps.GetReadingProfileForSeries(user.Id, series.Id); var profiles = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
Assert.Null(profile); Assert.DoesNotContain(profiles, rp => rp.SeriesIds.Contains(series.Id));
} }
@ -282,13 +275,13 @@ public class ReadingProfileServiceTest: AbstractDbTest
.WithSeries(series) .WithSeries(series)
.WithName("Profile") .WithName("Profile")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
var profile2 = new AppUserReadingProfileBuilder(user.Id) var profile2 = new AppUserReadingProfileBuilder(user.Id)
.WithSeries(series) .WithSeries(series)
.WithName("Profile2") .WithName("Profile2")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile2); Context.AppUserReadingProfiles.Add(profile2);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
@ -297,7 +290,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
foreach (var id in someSeriesIds) foreach (var id in someSeriesIds)
{ {
var foundProfile = await rps.GetReadingProfileForSeries(user.Id, id); var foundProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
Assert.NotNull(foundProfile); Assert.NotNull(foundProfile);
Assert.Equal(profile.Id, foundProfile.Id); Assert.Equal(profile.Id, foundProfile.Id);
} }
@ -307,7 +300,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
foreach (var id in allIds) foreach (var id in allIds)
{ {
var foundProfile = await rps.GetReadingProfileForSeries(user.Id, id); var foundProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
Assert.NotNull(foundProfile); Assert.NotNull(foundProfile);
Assert.Equal(profile2.Id, foundProfile.Id); Assert.Equal(profile2.Id, foundProfile.Id);
} }
@ -327,26 +320,27 @@ public class ReadingProfileServiceTest: AbstractDbTest
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Profile 1") .WithName("Profile 1")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.AddProfileToSeries(user.Id, profile.Id, series.Id); await rps.AddProfileToSeries(user.Id, profile.Id, series.Id);
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, implicitProfile); await rps.UpdateImplicitReadingProfile(user.Id, series.Id, implicitProfile);
var seriesProfile = await rps.GetReadingProfileForSeries(user.Id, series.Id); var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.True(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, seriesProfile.Kind);
var profileDto = Mapper.Map<UserReadingProfileDto>(profile); var profileDto = Mapper.Map<UserReadingProfileDto>(profile);
await rps.UpdateReadingProfile(user.Id, profileDto); await rps.UpdateReadingProfile(user.Id, profileDto);
seriesProfile = await rps.GetReadingProfileForSeries(user.Id, series.Id); seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.False(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.User, seriesProfile.Kind);
var implicitCount = await Context.AppUserReadingProfile var implicitCount = await Context.AppUserReadingProfiles
.Where(p => p.Implicit).CountAsync(); .Where(p => p.Kind == ReadingProfileKind.Implicit)
.CountAsync();
Assert.Equal(0, implicitCount); Assert.Equal(0, implicitCount);
} }
@ -362,7 +356,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Profile 1") .WithName("Profile 1")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
for (var i = 0; i < 10; i++) for (var i = 0; i < 10; i++)
{ {
@ -376,22 +370,23 @@ public class ReadingProfileServiceTest: AbstractDbTest
foreach (var id in ids) foreach (var id in ids)
{ {
await rps.UpdateImplicitReadingProfile(user.Id, id, implicitProfile); await rps.UpdateImplicitReadingProfile(user.Id, id, implicitProfile);
var seriesProfile = await rps.GetReadingProfileForSeries(user.Id, id); var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.True(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, seriesProfile.Kind);
} }
await rps.BulkAddProfileToSeries(user.Id, profile.Id, ids); await rps.BulkAddProfileToSeries(user.Id, profile.Id, ids);
foreach (var id in ids) foreach (var id in ids)
{ {
var seriesProfile = await rps.GetReadingProfileForSeries(user.Id, id); var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.False(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.User, seriesProfile.Kind);
} }
var implicitCount = await Context.AppUserReadingProfile var implicitCount = await Context.AppUserReadingProfiles
.Where(p => p.Implicit).CountAsync(); .Where(p => p.Kind == ReadingProfileKind.Implicit)
.CountAsync();
Assert.Equal(0, implicitCount); Assert.Equal(0, implicitCount);
} }
@ -402,55 +397,33 @@ public class ReadingProfileServiceTest: AbstractDbTest
var (rps, user, lib, series) = await Setup(); var (rps, user, lib, series) = await Setup();
var implicitProfile = Mapper.Map<UserReadingProfileDto>(new AppUserReadingProfileBuilder(user.Id) var implicitProfile = Mapper.Map<UserReadingProfileDto>(new AppUserReadingProfileBuilder(user.Id)
.WithKind(ReadingProfileKind.Implicit)
.Build()); .Build());
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Profile 1") .WithName("Profile 1")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.UpdateImplicitReadingProfile(user.Id, series.Id, implicitProfile); await rps.UpdateImplicitReadingProfile(user.Id, series.Id, implicitProfile);
var seriesProfile = await rps.GetReadingProfileForSeries(user.Id, series.Id); var seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.True(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.Implicit, seriesProfile.Kind);
await rps.AddProfileToSeries(user.Id, profile.Id, series.Id); await rps.AddProfileToSeries(user.Id, profile.Id, series.Id);
seriesProfile = await rps.GetReadingProfileForSeries(user.Id, series.Id); seriesProfile = await rps.GetReadingProfileDtoForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile); Assert.NotNull(seriesProfile);
Assert.False(seriesProfile.Implicit); Assert.Equal(ReadingProfileKind.User, seriesProfile.Kind);
var implicitCount = await Context.AppUserReadingProfile var implicitCount = await Context.AppUserReadingProfiles
.Where(p => p.Implicit).CountAsync(); .Where(p => p.Kind == ReadingProfileKind.Implicit)
.CountAsync();
Assert.Equal(0, implicitCount); Assert.Equal(0, implicitCount);
} }
[Fact]
public async Task SetDefault()
{
await ResetDb();
var (rps, user, lib, series) = await Setup();
var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Profile 1")
.Build();
Context.AppUserReadingProfile.Add(profile);
await UnitOfWork.CommitAsync();
await rps.SetDefaultReadingProfile(user.Id, profile.Id);
var newSeries = new SeriesBuilder("New Series").Build();
lib.Series.Add(newSeries);
await UnitOfWork.CommitAsync();
var seriesProfile = await rps.GetReadingProfileForSeries(user.Id, series.Id);
Assert.NotNull(seriesProfile);
Assert.Equal(profile.Id, seriesProfile.Id);
}
[Fact] [Fact]
public async Task CreateReadingProfile() public async Task CreateReadingProfile()
{ {
@ -487,7 +460,7 @@ public class ReadingProfileServiceTest: AbstractDbTest
await rps.CreateReadingProfile(user.Id, dto3); await rps.CreateReadingProfile(user.Id, dto3);
}); });
var allProfiles = Context.AppUserReadingProfile.ToList(); var allProfiles = Context.AppUserReadingProfiles.ToList();
Assert.Equal(2, allProfiles.Count); Assert.Equal(2, allProfiles.Count);
} }
@ -499,32 +472,31 @@ public class ReadingProfileServiceTest: AbstractDbTest
var implicitProfile = new AppUserReadingProfileBuilder(user.Id) var implicitProfile = new AppUserReadingProfileBuilder(user.Id)
.WithSeries(series) .WithSeries(series)
.WithImplicit(true) .WithKind(ReadingProfileKind.Implicit)
.WithName("Implicit Profile") .WithName("Implicit Profile")
.Build(); .Build();
var explicitProfile = new AppUserReadingProfileBuilder(user.Id) var explicitProfile = new AppUserReadingProfileBuilder(user.Id)
.WithSeries(series) .WithSeries(series)
.WithImplicit(false)
.WithName("Explicit Profile") .WithName("Explicit Profile")
.Build(); .Build();
Context.AppUserReadingProfile.Add(implicitProfile); Context.AppUserReadingProfiles.Add(implicitProfile);
Context.AppUserReadingProfile.Add(explicitProfile); Context.AppUserReadingProfiles.Add(explicitProfile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var allBefore = await UnitOfWork.AppUserReadingProfileRepository.GetAllProfilesForSeries(user.Id, series.Id, ReadingProfileIncludes.Series); var allBefore = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
Assert.Equal(2, allBefore.Count); Assert.Equal(2, allBefore.Count(rp => rp.SeriesIds.Contains(series.Id)));
await rps.ClearSeriesProfile(user.Id, series.Id); await rps.ClearSeriesProfile(user.Id, series.Id);
var remainingProfiles = await Context.AppUserReadingProfile.Includes(ReadingProfileIncludes.Series).ToListAsync(); var remainingProfiles = await Context.AppUserReadingProfiles.ToListAsync();
Assert.Single(remainingProfiles); Assert.Single(remainingProfiles);
Assert.Equal("Explicit Profile", remainingProfiles[0].Name); Assert.Equal("Explicit Profile", remainingProfiles[0].Name);
Assert.Empty(remainingProfiles[0].Series); Assert.Empty(remainingProfiles[0].SeriesIds);
var profilesForSeries = await UnitOfWork.AppUserReadingProfileRepository.GetAllProfilesForSeries(user.Id, series.Id, ReadingProfileIncludes.Series); var profilesForSeries = await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id);
Assert.Empty(profilesForSeries); Assert.DoesNotContain(profilesForSeries, rp => rp.SeriesIds.Contains(series.Id));
} }
[Fact] [Fact]
@ -536,26 +508,28 @@ public class ReadingProfileServiceTest: AbstractDbTest
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Library Profile") .WithName("Library Profile")
.Build(); .Build();
Context.AppUserReadingProfile.Add(profile); Context.AppUserReadingProfiles.Add(profile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.AddProfileToLibrary(user.Id, profile.Id, lib.Id); await rps.AddProfileToLibrary(user.Id, profile.Id, lib.Id);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
var linkedProfile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForLibrary(user.Id, lib.Id, ReadingProfileIncludes.Library); var linkedProfile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
Assert.NotNull(linkedProfile); Assert.NotNull(linkedProfile);
Assert.Equal(profile.Id, linkedProfile.Id); Assert.Equal(profile.Id, linkedProfile.Id);
var newProfile = new AppUserReadingProfileBuilder(user.Id) var newProfile = new AppUserReadingProfileBuilder(user.Id)
.WithName("New Profile") .WithName("New Profile")
.Build(); .Build();
Context.AppUserReadingProfile.Add(newProfile); Context.AppUserReadingProfiles.Add(newProfile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.AddProfileToLibrary(user.Id, newProfile.Id, lib.Id); await rps.AddProfileToLibrary(user.Id, newProfile.Id, lib.Id);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
linkedProfile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForLibrary(user.Id, lib.Id, ReadingProfileIncludes.Library); linkedProfile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
Assert.NotNull(linkedProfile); Assert.NotNull(linkedProfile);
Assert.Equal(newProfile.Id, linkedProfile.Id); Assert.Equal(newProfile.Id, linkedProfile.Id);
} }
@ -567,27 +541,29 @@ public class ReadingProfileServiceTest: AbstractDbTest
var (rps, user, lib, _) = await Setup(); var (rps, user, lib, _) = await Setup();
var implicitProfile = new AppUserReadingProfileBuilder(user.Id) var implicitProfile = new AppUserReadingProfileBuilder(user.Id)
.WithImplicit(true) .WithKind(ReadingProfileKind.Implicit)
.WithLibrary(lib) .WithLibrary(lib)
.Build(); .Build();
Context.AppUserReadingProfile.Add(implicitProfile); Context.AppUserReadingProfiles.Add(implicitProfile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.ClearLibraryProfile(user.Id, lib.Id); await rps.ClearLibraryProfile(user.Id, lib.Id);
var profile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForLibrary(user.Id, lib.Id, ReadingProfileIncludes.Library); var profile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
Assert.Null(profile); Assert.Null(profile);
var explicitProfile = new AppUserReadingProfileBuilder(user.Id) var explicitProfile = new AppUserReadingProfileBuilder(user.Id)
.WithLibrary(lib) .WithLibrary(lib)
.Build(); .Build();
Context.AppUserReadingProfile.Add(explicitProfile); Context.AppUserReadingProfiles.Add(explicitProfile);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
await rps.ClearLibraryProfile(user.Id, lib.Id); await rps.ClearLibraryProfile(user.Id, lib.Id);
profile = await UnitOfWork.AppUserReadingProfileRepository.GetProfileForLibrary(user.Id, lib.Id, ReadingProfileIncludes.Library); profile = (await UnitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(user.Id))
.FirstOrDefault(rp => rp.LibraryIds.Contains(lib.Id));
Assert.Null(profile); Assert.Null(profile);
var stillExists = await Context.AppUserReadingProfile.FindAsync(explicitProfile.Id); var stillExists = await Context.AppUserReadingProfiles.FindAsync(explicitProfile.Id);
Assert.NotNull(stillExists); Assert.NotNull(stillExists);
} }
@ -609,14 +585,14 @@ public class ReadingProfileServiceTest: AbstractDbTest
var newDto = Mapper.Map<UserReadingProfileDto>(profile); var newDto = Mapper.Map<UserReadingProfileDto>(profile);
Assert.True(RandfHelper.AreSimpleFieldsEqual(dto, newDto, Assert.True(RandfHelper.AreSimpleFieldsEqual(dto, newDto,
["<Id>k__BackingField", "<UserId>k__BackingField", "<Implicit>k__BackingField"])); ["<Id>k__BackingField", "<AppUserId>k__BackingField", "<Implicit>k__BackingField"]));
} }
protected override async Task ResetDb() protected override async Task ResetDb()
{ {
Context.AppUserReadingProfile.RemoveRange(Context.AppUserReadingProfile); Context.AppUserReadingProfiles.RemoveRange(Context.AppUserReadingProfiles);
await UnitOfWork.CommitAsync(); await UnitOfWork.CommitAsync();
} }
} }

View file

@ -612,7 +612,7 @@ public class AccountController : BaseApiController
} }
/// <summary> /// <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> /// </summary>
/// <param name="userId"></param> /// <param name="userId"></param>
/// <param name="withBaseUrl">Include the "https://ip:port/" in the generated link</param> /// <param name="withBaseUrl">Include the "https://ip:port/" in the generated link</param>
@ -789,12 +789,10 @@ public class AccountController : BaseApiController
{ {
var profile = new AppUserReadingProfileBuilder(user.Id) var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Default Profile") .WithName("Default Profile")
.WithKind(ReadingProfileKind.Default)
.Build(); .Build();
_unitOfWork.AppUserReadingProfileRepository.Add(profile); _unitOfWork.AppUserReadingProfileRepository.Add(profile);
await _unitOfWork.CommitAsync(); await _unitOfWork.CommitAsync();
user.UserPreferences.ReadingProfiles.Add(profile);
user.UserPreferences.DefaultReadingProfileId = profile.Id;
} }
/// <summary> /// <summary>

View file

@ -45,7 +45,7 @@ public class PluginController(IUnitOfWork unitOfWork, ITokenService tokenService
throw new KavitaUnauthenticatedUserException(); throw new KavitaUnauthenticatedUserException();
} }
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId); 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 return new UserDto
{ {

View file

@ -26,10 +26,7 @@ public class ReadingProfileController(ILogger<ReadingProfileController> logger,
[HttpGet("all")] [HttpGet("all")]
public async Task<ActionResult<IList<UserReadingProfileDto>>> GetAllReadingProfiles() public async Task<ActionResult<IList<UserReadingProfileDto>>> GetAllReadingProfiles()
{ {
var profiles = await unitOfWork.AppUserReadingProfileRepository var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesDtoForUser(User.GetUserId());
.GetProfilesDtoForUser(User.GetUserId(), true,
ReadingProfileIncludes.Series | ReadingProfileIncludes.Library);
return Ok(profiles); return Ok(profiles);
} }
@ -42,7 +39,7 @@ public class ReadingProfileController(ILogger<ReadingProfileController> logger,
[HttpGet("{seriesId}")] [HttpGet("{seriesId}")]
public async Task<ActionResult<UserReadingProfileDto>> GetProfileForSeries(int seriesId) public async Task<ActionResult<UserReadingProfileDto>> GetProfileForSeries(int seriesId)
{ {
return Ok(await readingProfileService.GetReadingProfileForSeries(User.GetUserId(), seriesId)); return Ok(await readingProfileService.GetReadingProfileDtoForSeries(User.GetUserId(), seriesId));
} }
/// <summary> /// <summary>
@ -85,20 +82,6 @@ public class ReadingProfileController(ILogger<ReadingProfileController> logger,
return Ok(); return Ok();
} }
/// <summary>
/// Sets the given profile as the global default
/// </summary>
/// <param name="profileId"></param>
/// <returns></returns>
/// <exception cref="KavitaException"></exception>
/// <exception cref="UnauthorizedAccessException"></exception>
[HttpPost("set-default")]
public async Task<IActionResult> SetDefault([FromQuery] int profileId)
{
await readingProfileService.SetDefaultReadingProfile(User.GetUserId(), profileId);
return Ok();
}
/// <summary> /// <summary>
/// Deletes the given profile, requires the profile to belong to the logged-in user /// Deletes the given profile, requires the profile to belong to the logged-in user
/// </summary> /// </summary>

View file

@ -9,8 +9,6 @@ namespace API.DTOs;
public sealed record UserPreferencesDto public sealed record UserPreferencesDto
{ {
/// <inheritdoc cref="AppUserPreferences.DefaultReadingProfileId"/>
public int DefaultReadingProfileId { get; init; }
/// <summary> /// <summary>
/// UI Site Global Setting: The UI theme the user should use. /// UI Site Global Setting: The UI theme the user should use.

View file

@ -10,13 +10,10 @@ public sealed record UserReadingProfileDto
{ {
public int Id { get; set; } public int Id { get; set; }
public int UserId { get; init; } public int UserId { get; init; }
public string Name { get; init; } public string Name { get; init; }
public ReadingProfileKind Kind { get; init; }
/// <inheritdoc cref="AppUserReadingProfile.Implicit"/>
public bool Implicit { get; set; } = false;
#region MangaReader #region MangaReader
@ -129,12 +126,4 @@ public sealed record UserReadingProfileDto
#endregion #endregion
#region Relations
public IList<int> SeriesIds { get; set; } = [];
public IList<int> LibraryIds { get; set; } = [];
#endregion
} }

View file

@ -81,9 +81,7 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
public DbSet<MetadataSettings> MetadataSettings { get; set; } = null!; public DbSet<MetadataSettings> MetadataSettings { get; set; } = null!;
public DbSet<MetadataFieldMapping> MetadataFieldMapping { get; set; } = null!; public DbSet<MetadataFieldMapping> MetadataFieldMapping { get; set; } = null!;
public DbSet<AppUserChapterRating> AppUserChapterRating { get; set; } = null!; public DbSet<AppUserChapterRating> AppUserChapterRating { get; set; } = null!;
public DbSet<AppUserReadingProfile> AppUserReadingProfile { get; set; } = null!; public DbSet<AppUserReadingProfile> AppUserReadingProfiles { get; set; } = null!;
public DbSet<SeriesReadingProfile> SeriesReadingProfile { get; set; } = null!;
public DbSet<LibraryReadingProfile> LibraryReadingProfile { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder builder) protected override void OnModelCreating(ModelBuilder builder)
{ {
@ -272,6 +270,19 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
builder.Entity<AppUserReadingProfile>() builder.Entity<AppUserReadingProfile>()
.Property(b => b.AllowAutomaticWebtoonReaderDetection) .Property(b => b.AllowAutomaticWebtoonReaderDetection)
.HasDefaultValue(true); .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 #nullable enable

View file

@ -1,6 +1,7 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.Entities; using API.Entities;
using API.Entities.Enums;
using API.Entities.History; using API.Entities.History;
using API.Extensions; using API.Extensions;
using API.Helpers.Builders; using API.Helpers.Builders;
@ -23,7 +24,7 @@ public static class ManualMigrateReadingProfiles
var users = await context.AppUser var users = await context.AppUser
.Include(u => u.UserPreferences) .Include(u => u.UserPreferences)
.Include(u => u.UserPreferences.ReadingProfiles) .Include(u => u.ReadingProfiles)
.ToListAsync(); .ToListAsync();
foreach (var user in users) foreach (var user in users)
@ -32,16 +33,19 @@ public static class ManualMigrateReadingProfiles
{ {
Name = "Default", Name = "Default",
NormalizedName = "Default".ToNormalized(), NormalizedName = "Default".ToNormalized(),
Kind = ReadingProfileKind.Default,
LibraryIds = [],
SeriesIds = [],
BackgroundColor = user.UserPreferences.BackgroundColor, BackgroundColor = user.UserPreferences.BackgroundColor,
EmulateBook = user.UserPreferences.EmulateBook, EmulateBook = user.UserPreferences.EmulateBook,
User = user, AppUser = user,
PdfTheme = user.UserPreferences.PdfTheme, PdfTheme = user.UserPreferences.PdfTheme,
ReaderMode = user.UserPreferences.ReaderMode, ReaderMode = user.UserPreferences.ReaderMode,
ReadingDirection = user.UserPreferences.ReadingDirection, ReadingDirection = user.UserPreferences.ReadingDirection,
ScalingOption = user.UserPreferences.ScalingOption, ScalingOption = user.UserPreferences.ScalingOption,
LayoutMode = user.UserPreferences.LayoutMode, LayoutMode = user.UserPreferences.LayoutMode,
WidthOverride = null, WidthOverride = null,
UserId = user.Id, AppUserId = user.Id,
AutoCloseMenu = user.UserPreferences.AutoCloseMenu, AutoCloseMenu = user.UserPreferences.AutoCloseMenu,
BookReaderMargin = user.UserPreferences.BookReaderMargin, BookReaderMargin = user.UserPreferences.BookReaderMargin,
PageSplitOption = user.UserPreferences.PageSplitOption, PageSplitOption = user.UserPreferences.PageSplitOption,
@ -60,16 +64,10 @@ public static class ManualMigrateReadingProfiles
BookReaderTapToPaginate = user.UserPreferences.BookReaderTapToPaginate, BookReaderTapToPaginate = user.UserPreferences.BookReaderTapToPaginate,
ShowScreenHints = user.UserPreferences.ShowScreenHints, ShowScreenHints = user.UserPreferences.ShowScreenHints,
}; };
user.UserPreferences.ReadingProfiles.Add(readingProfile); user.ReadingProfiles.Add(readingProfile);
} }
await context.SaveChangesAsync(); await context.SaveChangesAsync();
foreach (var user in users)
{
user.UserPreferences.DefaultReadingProfileId =
(await context.AppUserReadingProfile
.FirstAsync(rp => rp.UserId == user.Id)).Id;
}
context.ManualMigrationHistory.Add(new ManualMigrationHistory context.ManualMigrationHistory.Add(new ManualMigrationHistory
{ {

View file

@ -1,198 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace API.Data.Migrations
{
/// <inheritdoc />
public partial class AppUserReadingProfiles : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "DefaultReadingProfileId",
table: "AppUserPreferences",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "AppUserReadingProfile",
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),
UserId = table.Column<int>(type: "INTEGER", nullable: false),
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),
Implicit = table.Column<bool>(type: "INTEGER", nullable: false),
AppUserPreferencesId = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AppUserReadingProfile", x => x.Id);
table.ForeignKey(
name: "FK_AppUserReadingProfile_AppUserPreferences_AppUserPreferencesId",
column: x => x.AppUserPreferencesId,
principalTable: "AppUserPreferences",
principalColumn: "Id");
table.ForeignKey(
name: "FK_AppUserReadingProfile_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "LibraryReadingProfile",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
AppUserId = table.Column<int>(type: "INTEGER", nullable: false),
LibraryId = table.Column<int>(type: "INTEGER", nullable: false),
ReadingProfileId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LibraryReadingProfile", x => x.Id);
table.ForeignKey(
name: "FK_LibraryReadingProfile_AppUserReadingProfile_ReadingProfileId",
column: x => x.ReadingProfileId,
principalTable: "AppUserReadingProfile",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_LibraryReadingProfile_AspNetUsers_AppUserId",
column: x => x.AppUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_LibraryReadingProfile_Library_LibraryId",
column: x => x.LibraryId,
principalTable: "Library",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "SeriesReadingProfile",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
AppUserId = table.Column<int>(type: "INTEGER", nullable: false),
SeriesId = table.Column<int>(type: "INTEGER", nullable: false),
ReadingProfileId = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SeriesReadingProfile", x => x.Id);
table.ForeignKey(
name: "FK_SeriesReadingProfile_AppUserReadingProfile_ReadingProfileId",
column: x => x.ReadingProfileId,
principalTable: "AppUserReadingProfile",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SeriesReadingProfile_AspNetUsers_AppUserId",
column: x => x.AppUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_SeriesReadingProfile_Series_SeriesId",
column: x => x.SeriesId,
principalTable: "Series",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AppUserReadingProfile_AppUserPreferencesId",
table: "AppUserReadingProfile",
column: "AppUserPreferencesId");
migrationBuilder.CreateIndex(
name: "IX_AppUserReadingProfile_UserId",
table: "AppUserReadingProfile",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_LibraryReadingProfile_AppUserId",
table: "LibraryReadingProfile",
column: "AppUserId");
migrationBuilder.CreateIndex(
name: "IX_LibraryReadingProfile_LibraryId_AppUserId",
table: "LibraryReadingProfile",
columns: new[] { "LibraryId", "AppUserId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_LibraryReadingProfile_ReadingProfileId",
table: "LibraryReadingProfile",
column: "ReadingProfileId");
migrationBuilder.CreateIndex(
name: "IX_SeriesReadingProfile_AppUserId",
table: "SeriesReadingProfile",
column: "AppUserId");
migrationBuilder.CreateIndex(
name: "IX_SeriesReadingProfile_ReadingProfileId",
table: "SeriesReadingProfile",
column: "ReadingProfileId");
migrationBuilder.CreateIndex(
name: "IX_SeriesReadingProfile_SeriesId",
table: "SeriesReadingProfile",
column: "SeriesId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "LibraryReadingProfile");
migrationBuilder.DropTable(
name: "SeriesReadingProfile");
migrationBuilder.DropTable(
name: "AppUserReadingProfile");
migrationBuilder.DropColumn(
name: "DefaultReadingProfileId",
table: "AppUserPreferences");
}
}
}

View file

@ -11,8 +11,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace API.Data.Migrations namespace API.Data.Migrations
{ {
[DbContext(typeof(DataContext))] [DbContext(typeof(DataContext))]
[Migration("20250519113715_AppUserReadingProfiles")] [Migration("20250601200056_ReadingProfiles")]
partial class AppUserReadingProfiles partial class ReadingProfiles
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -458,9 +458,6 @@ namespace API.Data.Migrations
b.Property<bool>("CollapseSeriesRelationships") b.Property<bool>("CollapseSeriesRelationships")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("DefaultReadingProfileId")
.HasColumnType("INTEGER");
b.Property<bool>("EmulateBook") b.Property<bool>("EmulateBook")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@ -626,7 +623,7 @@ namespace API.Data.Migrations
.HasColumnType("INTEGER") .HasColumnType("INTEGER")
.HasDefaultValue(true); .HasDefaultValue(true);
b.Property<int?>("AppUserPreferencesId") b.Property<int>("AppUserId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("AutoCloseMenu") b.Property<bool>("AutoCloseMenu")
@ -674,12 +671,15 @@ namespace API.Data.Migrations
b.Property<bool>("EmulateBook") b.Property<bool>("EmulateBook")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("Implicit") b.Property<int>("Kind")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("LayoutMode") b.Property<int>("LayoutMode")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<string>("LibraryIds")
.HasColumnType("TEXT");
b.Property<string>("Name") b.Property<string>("Name")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@ -707,25 +707,23 @@ namespace API.Data.Migrations
b.Property<int>("ScalingOption") b.Property<int>("ScalingOption")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.PrimitiveCollection<string>("SeriesIds")
.HasColumnType("TEXT");
b.Property<bool>("ShowScreenHints") b.Property<bool>("ShowScreenHints")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("SwipeToPaginate") b.Property<bool>("SwipeToPaginate")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.Property<int?>("WidthOverride") b.Property<int?>("WidthOverride")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("AppUserPreferencesId"); b.HasIndex("AppUserId");
b.HasIndex("UserId"); b.ToTable("AppUserReadingProfiles");
b.ToTable("AppUserReadingProfile");
}); });
modelBuilder.Entity("API.Entities.AppUserRole", b => modelBuilder.Entity("API.Entities.AppUserRole", b =>
@ -1380,33 +1378,6 @@ namespace API.Data.Migrations
b.ToTable("LibraryFileTypeGroup"); b.ToTable("LibraryFileTypeGroup");
}); });
modelBuilder.Entity("API.Entities.LibraryReadingProfile", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<int>("LibraryId")
.HasColumnType("INTEGER");
b.Property<int>("ReadingProfileId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.HasIndex("ReadingProfileId");
b.HasIndex("LibraryId", "AppUserId")
.IsUnique();
b.ToTable("LibraryReadingProfile");
});
modelBuilder.Entity("API.Entities.MangaFile", b => modelBuilder.Entity("API.Entities.MangaFile", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -2394,32 +2365,6 @@ namespace API.Data.Migrations
b.ToTable("Series"); b.ToTable("Series");
}); });
modelBuilder.Entity("API.Entities.SeriesReadingProfile", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<int>("ReadingProfileId")
.HasColumnType("INTEGER");
b.Property<int>("SeriesId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.HasIndex("ReadingProfileId");
b.HasIndex("SeriesId");
b.ToTable("SeriesReadingProfile");
});
modelBuilder.Entity("API.Entities.ServerSetting", b => modelBuilder.Entity("API.Entities.ServerSetting", b =>
{ {
b.Property<int>("Key") b.Property<int>("Key")
@ -3012,17 +2957,13 @@ namespace API.Data.Migrations
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b => modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{ {
b.HasOne("API.Entities.AppUserPreferences", null) b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany("ReadingProfiles") .WithMany("ReadingProfiles")
.HasForeignKey("AppUserPreferencesId"); .HasForeignKey("AppUserId")
b.HasOne("API.Entities.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("User"); b.Navigation("AppUser");
}); });
modelBuilder.Entity("API.Entities.AppUserRole", b => modelBuilder.Entity("API.Entities.AppUserRole", b =>
@ -3184,33 +3125,6 @@ namespace API.Data.Migrations
b.Navigation("Library"); b.Navigation("Library");
}); });
modelBuilder.Entity("API.Entities.LibraryReadingProfile", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany()
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.Library", "Library")
.WithMany("ReadingProfiles")
.HasForeignKey("LibraryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.AppUserReadingProfile", "ReadingProfile")
.WithMany("Libraries")
.HasForeignKey("ReadingProfileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
b.Navigation("Library");
b.Navigation("ReadingProfile");
});
modelBuilder.Entity("API.Entities.MangaFile", b => modelBuilder.Entity("API.Entities.MangaFile", b =>
{ {
b.HasOne("API.Entities.Chapter", "Chapter") b.HasOne("API.Entities.Chapter", "Chapter")
@ -3468,33 +3382,6 @@ namespace API.Data.Migrations
b.Navigation("Library"); b.Navigation("Library");
}); });
modelBuilder.Entity("API.Entities.SeriesReadingProfile", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany()
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.AppUserReadingProfile", "ReadingProfile")
.WithMany("Series")
.HasForeignKey("ReadingProfileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.Series", "Series")
.WithMany("ReadingProfiles")
.HasForeignKey("SeriesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
b.Navigation("ReadingProfile");
b.Navigation("Series");
});
modelBuilder.Entity("API.Entities.Volume", b => modelBuilder.Entity("API.Entities.Volume", b =>
{ {
b.HasOne("API.Entities.Series", "Series") b.HasOne("API.Entities.Series", "Series")
@ -3717,6 +3604,8 @@ namespace API.Data.Migrations
b.Navigation("ReadingLists"); b.Navigation("ReadingLists");
b.Navigation("ReadingProfiles");
b.Navigation("ScrobbleHolds"); b.Navigation("ScrobbleHolds");
b.Navigation("SideNavStreams"); b.Navigation("SideNavStreams");
@ -3732,18 +3621,6 @@ namespace API.Data.Migrations
b.Navigation("WantToRead"); b.Navigation("WantToRead");
}); });
modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
{
b.Navigation("ReadingProfiles");
});
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{
b.Navigation("Libraries");
b.Navigation("Series");
});
modelBuilder.Entity("API.Entities.Chapter", b => modelBuilder.Entity("API.Entities.Chapter", b =>
{ {
b.Navigation("ExternalRatings"); b.Navigation("ExternalRatings");
@ -3767,8 +3644,6 @@ namespace API.Data.Migrations
b.Navigation("LibraryFileTypes"); b.Navigation("LibraryFileTypes");
b.Navigation("ReadingProfiles");
b.Navigation("Series"); b.Navigation("Series");
}); });
@ -3806,8 +3681,6 @@ namespace API.Data.Migrations
b.Navigation("Ratings"); b.Navigation("Ratings");
b.Navigation("ReadingProfiles");
b.Navigation("RelationOf"); b.Navigation("RelationOf");
b.Navigation("Relations"); b.Navigation("Relations");

View 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");
}
}
}

View file

@ -455,9 +455,6 @@ namespace API.Data.Migrations
b.Property<bool>("CollapseSeriesRelationships") b.Property<bool>("CollapseSeriesRelationships")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("DefaultReadingProfileId")
.HasColumnType("INTEGER");
b.Property<bool>("EmulateBook") b.Property<bool>("EmulateBook")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@ -623,7 +620,7 @@ namespace API.Data.Migrations
.HasColumnType("INTEGER") .HasColumnType("INTEGER")
.HasDefaultValue(true); .HasDefaultValue(true);
b.Property<int?>("AppUserPreferencesId") b.Property<int>("AppUserId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("AutoCloseMenu") b.Property<bool>("AutoCloseMenu")
@ -671,12 +668,15 @@ namespace API.Data.Migrations
b.Property<bool>("EmulateBook") b.Property<bool>("EmulateBook")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("Implicit") b.Property<int>("Kind")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("LayoutMode") b.Property<int>("LayoutMode")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<string>("LibraryIds")
.HasColumnType("TEXT");
b.Property<string>("Name") b.Property<string>("Name")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@ -704,25 +704,23 @@ namespace API.Data.Migrations
b.Property<int>("ScalingOption") b.Property<int>("ScalingOption")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.PrimitiveCollection<string>("SeriesIds")
.HasColumnType("TEXT");
b.Property<bool>("ShowScreenHints") b.Property<bool>("ShowScreenHints")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<bool>("SwipeToPaginate") b.Property<bool>("SwipeToPaginate")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.Property<int?>("WidthOverride") b.Property<int?>("WidthOverride")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("AppUserPreferencesId"); b.HasIndex("AppUserId");
b.HasIndex("UserId"); b.ToTable("AppUserReadingProfiles");
b.ToTable("AppUserReadingProfile");
}); });
modelBuilder.Entity("API.Entities.AppUserRole", b => modelBuilder.Entity("API.Entities.AppUserRole", b =>
@ -1377,33 +1375,6 @@ namespace API.Data.Migrations
b.ToTable("LibraryFileTypeGroup"); b.ToTable("LibraryFileTypeGroup");
}); });
modelBuilder.Entity("API.Entities.LibraryReadingProfile", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<int>("LibraryId")
.HasColumnType("INTEGER");
b.Property<int>("ReadingProfileId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.HasIndex("ReadingProfileId");
b.HasIndex("LibraryId", "AppUserId")
.IsUnique();
b.ToTable("LibraryReadingProfile");
});
modelBuilder.Entity("API.Entities.MangaFile", b => modelBuilder.Entity("API.Entities.MangaFile", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -2391,32 +2362,6 @@ namespace API.Data.Migrations
b.ToTable("Series"); b.ToTable("Series");
}); });
modelBuilder.Entity("API.Entities.SeriesReadingProfile", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<int>("ReadingProfileId")
.HasColumnType("INTEGER");
b.Property<int>("SeriesId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.HasIndex("ReadingProfileId");
b.HasIndex("SeriesId");
b.ToTable("SeriesReadingProfile");
});
modelBuilder.Entity("API.Entities.ServerSetting", b => modelBuilder.Entity("API.Entities.ServerSetting", b =>
{ {
b.Property<int>("Key") b.Property<int>("Key")
@ -3009,17 +2954,13 @@ namespace API.Data.Migrations
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b => modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{ {
b.HasOne("API.Entities.AppUserPreferences", null) b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany("ReadingProfiles") .WithMany("ReadingProfiles")
.HasForeignKey("AppUserPreferencesId"); .HasForeignKey("AppUserId")
b.HasOne("API.Entities.AppUser", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("User"); b.Navigation("AppUser");
}); });
modelBuilder.Entity("API.Entities.AppUserRole", b => modelBuilder.Entity("API.Entities.AppUserRole", b =>
@ -3181,33 +3122,6 @@ namespace API.Data.Migrations
b.Navigation("Library"); b.Navigation("Library");
}); });
modelBuilder.Entity("API.Entities.LibraryReadingProfile", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany()
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.Library", "Library")
.WithMany("ReadingProfiles")
.HasForeignKey("LibraryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.AppUserReadingProfile", "ReadingProfile")
.WithMany("Libraries")
.HasForeignKey("ReadingProfileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
b.Navigation("Library");
b.Navigation("ReadingProfile");
});
modelBuilder.Entity("API.Entities.MangaFile", b => modelBuilder.Entity("API.Entities.MangaFile", b =>
{ {
b.HasOne("API.Entities.Chapter", "Chapter") b.HasOne("API.Entities.Chapter", "Chapter")
@ -3465,33 +3379,6 @@ namespace API.Data.Migrations
b.Navigation("Library"); b.Navigation("Library");
}); });
modelBuilder.Entity("API.Entities.SeriesReadingProfile", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany()
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.AppUserReadingProfile", "ReadingProfile")
.WithMany("Series")
.HasForeignKey("ReadingProfileId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("API.Entities.Series", "Series")
.WithMany("ReadingProfiles")
.HasForeignKey("SeriesId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
b.Navigation("ReadingProfile");
b.Navigation("Series");
});
modelBuilder.Entity("API.Entities.Volume", b => modelBuilder.Entity("API.Entities.Volume", b =>
{ {
b.HasOne("API.Entities.Series", "Series") b.HasOne("API.Entities.Series", "Series")
@ -3714,6 +3601,8 @@ namespace API.Data.Migrations
b.Navigation("ReadingLists"); b.Navigation("ReadingLists");
b.Navigation("ReadingProfiles");
b.Navigation("ScrobbleHolds"); b.Navigation("ScrobbleHolds");
b.Navigation("SideNavStreams"); b.Navigation("SideNavStreams");
@ -3729,18 +3618,6 @@ namespace API.Data.Migrations
b.Navigation("WantToRead"); b.Navigation("WantToRead");
}); });
modelBuilder.Entity("API.Entities.AppUserPreferences", b =>
{
b.Navigation("ReadingProfiles");
});
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{
b.Navigation("Libraries");
b.Navigation("Series");
});
modelBuilder.Entity("API.Entities.Chapter", b => modelBuilder.Entity("API.Entities.Chapter", b =>
{ {
b.Navigation("ExternalRatings"); b.Navigation("ExternalRatings");
@ -3764,8 +3641,6 @@ namespace API.Data.Migrations
b.Navigation("LibraryFileTypes"); b.Navigation("LibraryFileTypes");
b.Navigation("ReadingProfiles");
b.Navigation("Series"); b.Navigation("Series");
}); });
@ -3803,8 +3678,6 @@ namespace API.Data.Migrations
b.Navigation("Ratings"); b.Navigation("Ratings");
b.Navigation("ReadingProfiles");
b.Navigation("RelationOf"); b.Navigation("RelationOf");
b.Navigation("Relations"); b.Navigation("Relations");

View file

@ -1,10 +1,10 @@
#nullable enable #nullable enable
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using API.DTOs; using API.DTOs;
using API.Entities; using API.Entities;
using API.Entities.Enums;
using API.Extensions; using API.Extensions;
using API.Extensions.QueryExtensions; using API.Extensions.QueryExtensions;
using AutoMapper; using AutoMapper;
@ -13,210 +13,94 @@ using Microsoft.EntityFrameworkCore;
namespace API.Data.Repositories; namespace API.Data.Repositories;
[Flags]
public enum ReadingProfileIncludes
{
None = 0,
Series = 1 << 1,
Library = 1 << 2
}
public interface IAppUserReadingProfileRepository public interface IAppUserReadingProfileRepository
{ {
Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool nonImplicitOnly, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool nonImplicitOnly, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<AppUserReadingProfile?> GetProfileForSeries(int userId, int seriesId, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
/// <summary> /// <summary>
/// Returns both implicit and "real" reading profiles /// Return the given profile if it belongs the user
/// </summary> /// </summary>
/// <param name="userId"></param> /// <param name="userId"></param>
/// <param name="seriesId"></param> /// <param name="profileId"></param>
/// <param name="includes"></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);
/// <summary>
/// Returns all non-implicit reading profiles for the user
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId);
/// <summary>
/// Find a profile by name, belonging to a specific user
/// </summary>
/// <param name="userId"></param>
/// <param name="name"></param>
/// <returns></returns> /// <returns></returns>
Task<IList<AppUserReadingProfile>> GetAllProfilesForSeries(int userId, int seriesId, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<IList<AppUserReadingProfile>> GetProfilesForSeries(int userId, IList<int> seriesIds, bool implicitOnly, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<UserReadingProfileDto?> GetProfileDtoForSeries(int userId, int seriesId);
Task<AppUserReadingProfile?> GetProfileForLibrary(int userId, int libraryId, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<UserReadingProfileDto?> GetProfileDtoForLibrary(int userId, int libraryId);
Task<AppUserReadingProfile?> GetProfile(int profileId, ReadingProfileIncludes includes = ReadingProfileIncludes.None);
Task<UserReadingProfileDto?> GetProfileDto(int profileId);
Task<AppUserReadingProfile?> GetProfileByName(int userId, string name); Task<AppUserReadingProfile?> GetProfileByName(int userId, string name);
Task<SeriesReadingProfile?> GetSeriesProfile(int userId, int seriesId);
Task<IList<SeriesReadingProfile>> GetSeriesProfilesForSeries(int userId, IList<int> seriesIds);
Task<LibraryReadingProfile?> GetLibraryProfile(int userId, int libraryId);
void Add(AppUserReadingProfile readingProfile); void Add(AppUserReadingProfile readingProfile);
void Add(SeriesReadingProfile readingProfile);
void Add(LibraryReadingProfile readingProfile);
void Attach(AppUserReadingProfile readingProfile);
void Update(AppUserReadingProfile readingProfile); void Update(AppUserReadingProfile readingProfile);
void Update(SeriesReadingProfile readingProfile);
void Remove(AppUserReadingProfile readingProfile); void Remove(AppUserReadingProfile readingProfile);
void Remove(SeriesReadingProfile readingProfile);
void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles); void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles);
} }
public class AppUserReadingProfileRepository(DataContext context, IMapper mapper): IAppUserReadingProfileRepository public class AppUserReadingProfileRepository(DataContext context, IMapper mapper): IAppUserReadingProfileRepository
{ {
public async Task<AppUserReadingProfile?> GetUserProfile(int userId, int profileId)
public async Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool nonImplicitOnly, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{ {
return await context.AppUserReadingProfile return await context.AppUserReadingProfiles
.Where(rp => rp.UserId == userId && !(nonImplicitOnly && rp.Implicit)) .Where(rp => rp.AppUserId == userId && rp.Id == profileId)
.Includes(includes) .FirstOrDefaultAsync();
}
public async Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId)
.ToListAsync(); .ToListAsync();
} }
public async Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool nonImplicitOnly, public async Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId)
ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{ {
return await context.AppUserReadingProfile return await context.AppUserReadingProfiles
.Where(rp => rp.UserId == userId && !(nonImplicitOnly && rp.Implicit)) .Where(rp => rp.AppUserId == userId)
.Includes(includes) .Where(rp => rp.Kind !=ReadingProfileKind.Implicit)
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider) .ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
.ToListAsync(); .ToListAsync();
} }
public async Task<AppUserReadingProfile?> GetProfileForSeries(int userId, int seriesId, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{
return await context.AppUserReadingProfile
.Where(rp => rp.UserId == userId && rp.Series.Any(s => s.SeriesId == seriesId))
.Includes(includes)
.OrderByDescending(rp => rp.Implicit) // Get implicit profiles first
.FirstOrDefaultAsync();
}
public async Task<IList<AppUserReadingProfile>> GetAllProfilesForSeries(int userId, int seriesId, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{
return await context.AppUserReadingProfile
.Where(rp => rp.UserId == userId && rp.Series.Any(s => s.SeriesId == seriesId))
.Includes(includes)
.ToListAsync();
}
public async Task<IList<AppUserReadingProfile>> GetProfilesForSeries(int userId, IList<int> seriesIds, bool implicitOnly, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{
return await context.AppUserReadingProfile
.Where(rp
=> rp.UserId == userId
&& rp.Series.Any(s => seriesIds.Contains(s.SeriesId))
&& (!implicitOnly || rp.Implicit))
.Includes(includes)
.ToListAsync();
}
public async Task<UserReadingProfileDto?> GetProfileDtoForSeries(int userId, int seriesId)
{
return await context.AppUserReadingProfile
.Where(rp => rp.UserId == userId && rp.Series.Any(s => s.SeriesId == seriesId))
.OrderByDescending(rp => rp.Implicit) // Get implicit profiles first
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
}
public async Task<AppUserReadingProfile?> GetProfileForLibrary(int userId, int libraryId, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{
return await context.AppUserReadingProfile
.Where(rp => rp.UserId == userId && rp.Libraries.Any(s => s.LibraryId == libraryId))
.Includes(includes)
.FirstOrDefaultAsync();
}
public async Task<UserReadingProfileDto?> GetProfileDtoForLibrary(int userId, int libraryId)
{
return await context.AppUserReadingProfile
.Where(rp => rp.UserId == userId && rp.Libraries.Any(s => s.LibraryId == libraryId))
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
}
public async Task<AppUserReadingProfile?> GetProfile(int profileId, ReadingProfileIncludes includes = ReadingProfileIncludes.None)
{
return await context.AppUserReadingProfile
.Where(rp => rp.Id == profileId)
.Includes(includes)
.FirstOrDefaultAsync();
}
public async Task<UserReadingProfileDto?> GetProfileDto(int profileId)
{
return await context.AppUserReadingProfile
.Where(rp => rp.Id == profileId)
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
.FirstOrDefaultAsync();
}
public async Task<AppUserReadingProfile?> GetProfileByName(int userId, string name) public async Task<AppUserReadingProfile?> GetProfileByName(int userId, string name)
{ {
var normalizedName = name.ToNormalized(); var normalizedName = name.ToNormalized();
return await context.AppUserReadingProfile return await context.AppUserReadingProfiles
.Where(rp => rp.NormalizedName == normalizedName && rp.UserId == userId) .Where(rp => rp.NormalizedName == normalizedName && rp.AppUserId == userId)
.FirstOrDefaultAsync();
}
public async Task<SeriesReadingProfile?> GetSeriesProfile(int userId, int seriesId)
{
return await context.SeriesReadingProfile
.Where(rp => rp.SeriesId == seriesId && rp.AppUserId == userId)
.FirstOrDefaultAsync();
}
public async Task<IList<SeriesReadingProfile>> GetSeriesProfilesForSeries(int userId, IList<int> seriesIds)
{
return await context.SeriesReadingProfile
.Where(rp => seriesIds.Contains(rp.SeriesId) && rp.AppUserId == userId)
.ToListAsync();
}
public async Task<LibraryReadingProfile?> GetLibraryProfile(int userId, int libraryId)
{
return await context.LibraryReadingProfile
.Where(rp => rp.LibraryId == libraryId && rp.AppUserId == userId)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
} }
public void Add(AppUserReadingProfile readingProfile) public void Add(AppUserReadingProfile readingProfile)
{ {
context.AppUserReadingProfile.Add(readingProfile); context.AppUserReadingProfiles.Add(readingProfile);
}
public void Add(SeriesReadingProfile readingProfile)
{
context.SeriesReadingProfile.Add(readingProfile);
}
public void Add(LibraryReadingProfile readingProfile)
{
context.LibraryReadingProfile.Add(readingProfile);
}
public void Attach(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfile.Attach(readingProfile);
} }
public void Update(AppUserReadingProfile readingProfile) public void Update(AppUserReadingProfile readingProfile)
{ {
context.AppUserReadingProfile.Update(readingProfile).State = EntityState.Modified; context.AppUserReadingProfiles.Update(readingProfile).State = EntityState.Modified;
}
public void Update(SeriesReadingProfile readingProfile)
{
context.SeriesReadingProfile.Update(readingProfile).State = EntityState.Modified;
} }
public void Remove(AppUserReadingProfile readingProfile) public void Remove(AppUserReadingProfile readingProfile)
{ {
context.AppUserReadingProfile.Remove(readingProfile); context.AppUserReadingProfiles.Remove(readingProfile);
}
public void Remove(SeriesReadingProfile readingProfile)
{
context.SeriesReadingProfile.Remove(readingProfile);
} }
public void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles) public void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles)
{ {
context.AppUserReadingProfile.RemoveRange(readingProfiles); context.AppUserReadingProfiles.RemoveRange(readingProfiles);
} }
} }

View file

@ -111,7 +111,7 @@ public class GenreRepository : IGenreRepository
/// <summary> /// <summary>
/// Returns a set of Genre tags for a set of library Ids. /// 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> /// </summary>
/// <param name="userId"></param> /// <param name="userId"></param>
/// <param name="libraryIds"></param> /// <param name="libraryIds"></param>

View file

@ -757,7 +757,7 @@ public class UserRepository : IUserRepository
/// <summary> /// <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> /// </summary>
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <returns></returns> /// <returns></returns>

View file

@ -21,6 +21,7 @@ public class AppUser : IdentityUser<int>, IHasConcurrencyToken
public ICollection<AppUserRating> Ratings { get; set; } = null!; public ICollection<AppUserRating> Ratings { get; set; } = null!;
public ICollection<AppUserChapterRating> ChapterRatings { get; set; } = null!; public ICollection<AppUserChapterRating> ChapterRatings { get; set; } = null!;
public AppUserPreferences UserPreferences { get; set; } = null!; public AppUserPreferences UserPreferences { get; set; } = null!;
public ICollection<AppUserReadingProfile> ReadingProfiles { get; set; } = null!;
/// <summary> /// <summary>
/// Bookmarks associated with this User /// Bookmarks associated with this User
/// </summary> /// </summary>

View file

@ -9,14 +9,6 @@ public class AppUserPreferences
{ {
public int Id { get; set; } public int Id { get; set; }
#region ReadingProfiles
public int DefaultReadingProfileId { get; set; }
public ICollection<AppUserReadingProfile> ReadingProfiles { get; set; } = null!;
#endregion
#region MangaReader #region MangaReader
/// <summary> /// <summary>

View file

@ -11,11 +11,12 @@ public class AppUserReadingProfile
public string Name { get; set; } public string Name { get; set; }
public string NormalizedName { get; set; } public string NormalizedName { get; set; }
public int UserId { get; set; } public int AppUserId { get; set; }
public AppUser User { get; set; } public AppUser AppUser { get; set; }
public ICollection<SeriesReadingProfile> Series { get; set; } public ReadingProfileKind Kind { get; set; }
public ICollection<LibraryReadingProfile> Libraries { get; set; } public List<int> LibraryIds { get; set; }
public List<int> SeriesIds { get; set; }
#region MangaReader #region MangaReader
@ -139,10 +140,4 @@ public class AppUserReadingProfile
#endregion #endregion
/// <summary>
/// If the profile has been created in the background after a user modified a series settings
/// </summary>
/// <remarks>A profile can be made non-implicit by a user, but not implicit</remarks>
public bool Implicit { get; set; } = false;
} }

View 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 tracked changes made in the readers
/// </summary>
Implicit
}

View file

@ -65,7 +65,6 @@ public class Library : IEntityDate, IHasCoverImage
public ICollection<Series> Series { get; set; } = null!; public ICollection<Series> Series { get; set; } = null!;
public ICollection<LibraryFileTypeGroup> LibraryFileTypes { get; set; } = new List<LibraryFileTypeGroup>(); public ICollection<LibraryFileTypeGroup> LibraryFileTypes { get; set; } = new List<LibraryFileTypeGroup>();
public ICollection<LibraryExcludePattern> LibraryExcludePatterns { get; set; } = new List<LibraryExcludePattern>(); public ICollection<LibraryExcludePattern> LibraryExcludePatterns { get; set; } = new List<LibraryExcludePattern>();
public ICollection<LibraryReadingProfile> ReadingProfiles { get; set; } = null!;
public void UpdateLastModified() public void UpdateLastModified()
{ {

View file

@ -1,20 +0,0 @@
using Microsoft.EntityFrameworkCore;
namespace API.Entities;
[Index(nameof(LibraryId), nameof(AppUserId), IsUnique = true)]
public class LibraryReadingProfile
{
public int Id { get; set; }
public int AppUserId { get; set; }
public AppUser AppUser { get; set; }
public int LibraryId { get; set; }
public Library Library { get; set; }
public int ReadingProfileId { get; set; }
public AppUserReadingProfile ReadingProfile { get; set; }
}

View file

@ -1,17 +0,0 @@
namespace API.Entities;
public class SeriesReadingProfile
{
public int Id { get; set; }
public int AppUserId { get; set; }
public AppUser AppUser { get; set; }
public int SeriesId { get; set; }
public Series Series { get; set; }
public int ReadingProfileId { get; set; }
public AppUserReadingProfile ReadingProfile { get; set; }
}

View file

@ -135,7 +135,6 @@ public class Series : IEntityDate, IHasReadTimeEstimate, IHasCoverImage
public List<Volume> Volumes { get; set; } = null!; public List<Volume> Volumes { get; set; } = null!;
public Library Library { get; set; } = null!; public Library Library { get; set; } = null!;
public int LibraryId { get; set; } public int LibraryId { get; set; }
public ICollection<SeriesReadingProfile> ReadingProfiles { get; set; } = null!;
public void UpdateLastFolderScanned() public void UpdateLastFolderScanned()

View file

@ -220,8 +220,7 @@ public static class IncludesExtensions
{ {
query = query query = query
.Include(u => u.UserPreferences) .Include(u => u.UserPreferences)
.ThenInclude(p => p.Theme) .ThenInclude(p => p.Theme);
.Include(u => u.UserPreferences.ReadingProfiles);
} }
if (includeFlags.HasFlag(AppUserIncludes.WantToRead)) if (includeFlags.HasFlag(AppUserIncludes.WantToRead))
@ -343,20 +342,4 @@ public static class IncludesExtensions
return queryable; return queryable;
} }
public static IQueryable<AppUserReadingProfile> Includes(this IQueryable<AppUserReadingProfile> queryable, ReadingProfileIncludes includeFlags)
{
if (includeFlags.HasFlag(ReadingProfileIncludes.Series))
{
queryable = queryable.Include(r => r.Series);
}
if (includeFlags.HasFlag(ReadingProfileIncludes.Library))
{
queryable = queryable.Include(r => r.Libraries);
}
return queryable;
}
} }

View file

@ -280,16 +280,7 @@ public class AutoMapperProfiles : Profile
CreateMap<AppUserReadingProfile, UserReadingProfileDto>() CreateMap<AppUserReadingProfile, UserReadingProfileDto>()
.ForMember(dest => dest.BookReaderThemeName, .ForMember(dest => dest.BookReaderThemeName,
opt => opt =>
opt.MapFrom(src => src.BookThemeName)) opt.MapFrom(src => src.BookThemeName));
.ForMember(dest => dest.BookReaderLayoutMode,
opt =>
opt.MapFrom(src => src.BookReaderLayoutMode))
.ForMember(dest => dest.SeriesIds,
opt =>
opt.MapFrom(src => src.Series.Select(s => s.SeriesId).ToList()))
.ForMember(dest => dest.LibraryIds,
opt =>
opt.MapFrom(src => src.Libraries.Select(s => s.LibraryId).ToList()));
CreateMap<AppUserBookmark, BookmarkDto>(); CreateMap<AppUserBookmark, BookmarkDto>();

View file

@ -22,7 +22,6 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
UserPreferences = new AppUserPreferences UserPreferences = new AppUserPreferences
{ {
Theme = theme ?? Seed.DefaultThemes.First(), Theme = theme ?? Seed.DefaultThemes.First(),
ReadingProfiles = [],
}, },
ReadingLists = new List<ReadingList>(), ReadingLists = new List<ReadingList>(),
Bookmarks = new List<AppUserBookmark>(), Bookmarks = new List<AppUserBookmark>(),
@ -33,6 +32,7 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
Id = 0, Id = 0,
DashboardStreams = new List<AppUserDashboardStream>(), DashboardStreams = new List<AppUserDashboardStream>(),
SideNavStreams = new List<AppUserSideNavStream>(), SideNavStreams = new List<AppUserSideNavStream>(),
ReadingProfiles = [],
}; };
} }

View file

@ -1,4 +1,5 @@
using API.Entities; using API.Entities;
using API.Entities.Enums;
using API.Extensions; using API.Extensions;
namespace API.Helpers.Builders; namespace API.Helpers.Builders;
@ -9,39 +10,36 @@ public class AppUserReadingProfileBuilder
public AppUserReadingProfile Build() => _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) public AppUserReadingProfileBuilder(int userId)
{ {
_profile = new AppUserReadingProfile _profile = new AppUserReadingProfile
{ {
UserId = userId, AppUserId = userId,
Series = [], Kind = ReadingProfileKind.User,
Libraries = [], SeriesIds = [],
LibraryIds = []
}; };
} }
public AppUserReadingProfileBuilder WithSeries(Series series) public AppUserReadingProfileBuilder WithSeries(Series series)
{ {
_profile.Series.Add(new SeriesReadingProfile _profile.SeriesIds.Add(series.Id);
{
Series = series,
AppUserId = _profile.UserId,
});
return this; return this;
} }
public AppUserReadingProfileBuilder WithLibrary(Library library) public AppUserReadingProfileBuilder WithLibrary(Library library)
{ {
_profile.Libraries.Add(new LibraryReadingProfile _profile.LibraryIds.Add(library.Id);
{
Library = library,
AppUserId = _profile.UserId,
});
return this; return this;
} }
public AppUserReadingProfileBuilder WithImplicit(bool b) public AppUserReadingProfileBuilder WithKind(ReadingProfileKind kind)
{ {
_profile.Implicit = b; _profile.Kind = kind;
return this; return this;
} }

View file

@ -261,7 +261,7 @@ public class ScrobblingService : IScrobblingService
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId, SeriesIncludes.Metadata | SeriesIncludes.Library); var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId, SeriesIncludes.Metadata | SeriesIncludes.Library);
if (series == null) throw new KavitaException(await _localizationService.Translate(userId, "series-doesnt-exist")); 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 (await CheckIfCannotScrobble(userId, seriesId, series)) return;
if (IsAniListReviewValid(reviewTitle, reviewBody)) if (IsAniListReviewValid(reviewTitle, reviewBody))
@ -297,7 +297,7 @@ public class ScrobblingService : IScrobblingService
}; };
_unitOfWork.ScrobbleRepository.Attach(evt); _unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync(); 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) 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); var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return; 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; if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id, var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
@ -346,7 +346,7 @@ public class ScrobblingService : IScrobblingService
}; };
_unitOfWork.ScrobbleRepository.Attach(evt); _unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync(); 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) public static long? GetMalId(Series series)
@ -371,7 +371,7 @@ public class ScrobblingService : IScrobblingService
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences); var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return; 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; if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id, var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
@ -418,7 +418,7 @@ public class ScrobblingService : IScrobblingService
_unitOfWork.ScrobbleRepository.Attach(evt); _unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync(); 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) catch (Exception ex)
{ {
@ -437,7 +437,7 @@ public class ScrobblingService : IScrobblingService
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return; if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
if (await CheckIfCannotScrobble(userId, seriesId, series)) 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 // Get existing events for this series/user
var existingEvents = (await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId)) var existingEvents = (await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId))
@ -463,7 +463,7 @@ public class ScrobblingService : IScrobblingService
_unitOfWork.ScrobbleRepository.Attach(evt); _unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync(); 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) 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 (series.DontMatch) return true;
if (await _unitOfWork.UserRepository.HasHoldOnSeries(userId, seriesId)) 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); userId);
return true; return true;
} }
@ -750,7 +750,7 @@ public class ScrobblingService : IScrobblingService
/// <param name="seriesId"></param> /// <param name="seriesId"></param>
public async Task ClearEventsForSeries(int userId, int seriesId) 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); var events = await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId);
foreach (var scrobble in events) foreach (var scrobble in events)
{ {
@ -1109,7 +1109,7 @@ public class ScrobblingService : IScrobblingService
{ {
if (ex.Message.Contains("Access token is invalid")) 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.IsErrored = true;
evt.ErrorDetails = AccessTokenErrorMessage; evt.ErrorDetails = AccessTokenErrorMessage;
_unitOfWork.ScrobbleRepository.Update(evt); _unitOfWork.ScrobbleRepository.Update(evt);

View file

@ -6,8 +6,10 @@ using API.Data;
using API.Data.Repositories; using API.Data.Repositories;
using API.DTOs; using API.DTOs;
using API.Entities; using API.Entities;
using API.Entities.Enums;
using API.Extensions; using API.Extensions;
using API.Helpers.Builders; using API.Helpers.Builders;
using AutoMapper;
using Kavita.Common; using Kavita.Common;
namespace API.Services; namespace API.Services;
@ -16,12 +18,12 @@ public interface IReadingProfileService
{ {
/// <summary> /// <summary>
/// Returns the ReadingProfile that should be applied to the given series, walks up the tree. /// Returns the ReadingProfile that should be applied to the given series, walks up the tree.
/// Series (implicit) -> Series (Assigned) -> Library -> Default /// Series (Implicit) -> Series (User) -> Library (User) -> Default
/// </summary> /// </summary>
/// <param name="userId"></param> /// <param name="userId"></param>
/// <param name="seriesId"></param> /// <param name="seriesId"></param>
/// <returns></returns> /// <returns></returns>
Task<UserReadingProfileDto> GetReadingProfileForSeries(int userId, int seriesId); Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId);
/// <summary> /// <summary>
/// Updates a given reading profile for a user, and deletes all implicit profiles /// Updates a given reading profile for a user, and deletes all implicit profiles
@ -60,59 +62,87 @@ public interface IReadingProfileService
Task DeleteReadingProfile(int userId, int profileId); Task DeleteReadingProfile(int userId, int profileId);
/// <summary> /// <summary>
/// Sets the given profile as global default /// Assigns the reading profile to the series, and remove the implicit RP from the series if it exists
/// </summary> /// </summary>
/// <param name="userId"></param> /// <param name="userId"></param>
/// <param name="profileId"></param> /// <param name="profileId"></param>
/// <param name="seriesId"></param>
/// <returns></returns> /// <returns></returns>
Task SetDefaultReadingProfile(int userId, int profileId);
Task AddProfileToSeries(int userId, int profileId, int seriesId); Task AddProfileToSeries(int userId, int profileId, int seriesId);
/// <summary>
/// Assigns 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); Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds);
/// <summary>
/// Remove all reading profiles from the series
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <returns></returns>
Task ClearSeriesProfile(int userId, int seriesId); Task ClearSeriesProfile(int userId, int seriesId);
/// <summary>
/// Assign 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); Task AddProfileToLibrary(int userId, int profileId, int libraryId);
/// <summary>
/// Remove the reading profile from the library, if it exists
/// </summary>
/// <param name="userId"></param>
/// <param name="libraryId"></param>
/// <returns></returns>
Task ClearLibraryProfile(int userId, int libraryId); Task ClearLibraryProfile(int userId, int libraryId);
} }
public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService localizationService): IReadingProfileService public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService localizationService, IMapper mapper): IReadingProfileService
{ {
public async Task<UserReadingProfileDto> GetReadingProfileForSeries(int userId, int seriesId) public async Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId)
{ {
var seriesProfile = await unitOfWork.AppUserReadingProfileRepository.GetProfileDtoForSeries(userId, seriesId); return mapper.Map<UserReadingProfileDto>(await GetReadingProfileForSeries(userId, seriesId));
}
public async Task<AppUserReadingProfile> GetReadingProfileForSeries(int userId, int seriesId)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var implicitSeriesProfile = profiles
.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind == ReadingProfileKind.Implicit);
if (implicitSeriesProfile != null) return implicitSeriesProfile;
var seriesProfile = profiles
.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind != ReadingProfileKind.Implicit);
if (seriesProfile != null) return seriesProfile; if (seriesProfile != null) return seriesProfile;
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId); var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
if (series == null) throw new KavitaException(await localizationService.Translate(userId, "series-doesnt-exist")); if (series == null) throw new KavitaException(await localizationService.Translate(userId, "series-doesnt-exist"));
var libraryProfile = await unitOfWork.AppUserReadingProfileRepository.GetProfileDtoForLibrary(userId, series.LibraryId); var libraryProfile = profiles
.FirstOrDefault(p => p.LibraryIds.Contains(series.LibraryId) && p.Kind != ReadingProfileKind.Implicit);
if (libraryProfile != null) return libraryProfile; if (libraryProfile != null) return libraryProfile;
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences); return profiles.First(p => p.Kind == ReadingProfileKind.Default);
if (user == null) throw new UnauthorizedAccessException();
return await unitOfWork.AppUserReadingProfileRepository.GetProfileDto(user.UserPreferences.DefaultReadingProfileId);
} }
public async Task UpdateReadingProfile(int userId, UserReadingProfileDto dto) public async Task UpdateReadingProfile(int userId, UserReadingProfileDto dto)
{ {
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences); var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, dto.Id);
if (user == null) throw new UnauthorizedAccessException();
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(dto.Id, ReadingProfileIncludes.Series);
if (profile == null) throw new KavitaException("profile-does-not-exist"); if (profile == null) throw new KavitaException("profile-does-not-exist");
if (profile.UserId != userId) throw new UnauthorizedAccessException();
UpdateReaderProfileFields(profile, dto); UpdateReaderProfileFields(profile, dto);
unitOfWork.AppUserReadingProfileRepository.Update(profile); unitOfWork.AppUserReadingProfileRepository.Update(profile);
// Remove all implicit profiles for series using this profile await DeleteImplicateReadingProfilesForSeries(userId, profile.SeriesIds);
var allLinkedSeries = profile.Series.Select(sp => sp.SeriesId).ToList();
var implicitProfiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForSeries(userId, allLinkedSeries, true);
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
@ -128,11 +158,11 @@ public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService
var newProfile = new AppUserReadingProfileBuilder(user.Id).Build(); var newProfile = new AppUserReadingProfileBuilder(user.Id).Build();
UpdateReaderProfileFields(newProfile, dto); UpdateReaderProfileFields(newProfile, dto);
unitOfWork.AppUserReadingProfileRepository.Add(newProfile); unitOfWork.AppUserReadingProfileRepository.Add(newProfile);
user.UserPreferences.ReadingProfiles.Add(newProfile); user.ReadingProfiles.Add(newProfile);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
return await unitOfWork.AppUserReadingProfileRepository.GetProfileDto(newProfile.Id); return mapper.Map<UserReadingProfileDto>(newProfile);
} }
public async Task UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto) public async Task UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto)
@ -140,10 +170,11 @@ public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences); var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null) throw new UnauthorizedAccessException(); if (user == null) throw new UnauthorizedAccessException();
var existingProfile = await unitOfWork.AppUserReadingProfileRepository.GetProfileForSeries(userId, seriesId); 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 // Series already had an implicit profile, update it
if (existingProfile is {Implicit: true}) if (existingProfile is {Kind: ReadingProfileKind.Implicit})
{ {
UpdateReaderProfileFields(existingProfile, dto, false); UpdateReaderProfileFields(existingProfile, dto, false);
unitOfWork.AppUserReadingProfileRepository.Update(existingProfile); unitOfWork.AppUserReadingProfileRepository.Update(existingProfile);
@ -154,7 +185,7 @@ public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId) ?? throw new KeyNotFoundException(); var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId) ?? throw new KeyNotFoundException();
var newProfile = new AppUserReadingProfileBuilder(userId) var newProfile = new AppUserReadingProfileBuilder(userId)
.WithSeries(series) .WithSeries(series)
.WithImplicit(true) .WithKind(ReadingProfileKind.Implicit)
.Build(); .Build();
// Set name to something fitting for debugging if needed // Set name to something fitting for debugging if needed
@ -162,165 +193,111 @@ public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService
newProfile.Name = $"Implicit Profile for {seriesId}"; newProfile.Name = $"Implicit Profile for {seriesId}";
newProfile.NormalizedName = newProfile.Name.ToNormalized(); newProfile.NormalizedName = newProfile.Name.ToNormalized();
user.UserPreferences.ReadingProfiles.Add(newProfile); user.ReadingProfiles.Add(newProfile);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task DeleteReadingProfile(int userId, int profileId) public async Task DeleteReadingProfile(int userId, int profileId)
{ {
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(profileId); var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-doesnt-exist"); if (profile == null) throw new KavitaException("profile-doesnt-exist");
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences); if (profile.Kind == ReadingProfileKind.Default) throw new KavitaException("cant-delete-default-profile");
if (user == null || profile.UserId != userId) throw new UnauthorizedAccessException();
if (user.UserPreferences.DefaultReadingProfileId == profileId) throw new KavitaException("cant-delete-default-profile");
unitOfWork.AppUserReadingProfileRepository.Remove(profile); unitOfWork.AppUserReadingProfileRepository.Remove(profile);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task SetDefaultReadingProfile(int userId, int profileId)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(profileId);
if (profile == null) throw new KavitaException("profile-not-found");
if (profile.UserId != userId) throw new UnauthorizedAccessException();
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null) throw new UnauthorizedAccessException();
user.UserPreferences.DefaultReadingProfileId = profile.Id;
await unitOfWork.CommitAsync();
}
public async Task AddProfileToSeries(int userId, int profileId, int seriesId) public async Task AddProfileToSeries(int userId, int profileId, int seriesId)
{ {
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(profileId); var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-not-found"); if (profile == null) throw new KavitaException("profile-doesnt-exist");
if (profile.UserId != userId) throw new UnauthorizedAccessException(); await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
// Remove all implicit profiles profile.SeriesIds.Add(seriesId);
var implicitProfiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForSeries(userId, [seriesId], true); unitOfWork.AppUserReadingProfileRepository.Update(profile);
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
var seriesProfile = await unitOfWork.AppUserReadingProfileRepository.GetSeriesProfile(userId, seriesId);
if (seriesProfile != null)
{
seriesProfile.ReadingProfile = profile;
await unitOfWork.CommitAsync();
return;
}
seriesProfile = new SeriesReadingProfile
{
AppUserId = userId,
SeriesId = seriesId,
ReadingProfileId = profile.Id
};
unitOfWork.AppUserReadingProfileRepository.Add(seriesProfile);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds) public async Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds)
{ {
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(profileId, ReadingProfileIncludes.Series); var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-not-found"); if (profile == null) throw new KavitaException("profile-doesnt-exist");
if (profile.UserId != userId) throw new UnauthorizedAccessException(); await DeleteImplicitAndRemoveFromUserProfiles(userId, seriesIds, []);
var seriesProfiles = await unitOfWork.AppUserReadingProfileRepository.GetSeriesProfilesForSeries(userId, seriesIds); profile.SeriesIds.AddRange(seriesIds.Except(profile.SeriesIds));
var newSeriesIds = seriesIds.Except(seriesProfiles.Select(p => p.SeriesId)).ToList(); unitOfWork.AppUserReadingProfileRepository.Update(profile);
// Update existing
foreach (var seriesProfile in seriesProfiles)
{
seriesProfile.ReadingProfile = profile;
}
// Create new ones
foreach (var seriesId in newSeriesIds)
{
var seriesProfile = new SeriesReadingProfile
{
AppUserId = userId,
SeriesId = seriesId,
ReadingProfile = profile,
};
unitOfWork.AppUserReadingProfileRepository.Add(seriesProfile);
}
// Remove all implicit profiles
var implicitProfiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForSeries(userId, seriesIds, true);
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task ClearSeriesProfile(int userId, int seriesId) public async Task ClearSeriesProfile(int userId, int seriesId)
{ {
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetAllProfilesForSeries(userId, seriesId, ReadingProfileIncludes.Series); await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
if (!profiles.Any()) return;
foreach (var profile in profiles)
{
if (profile.Implicit)
{
unitOfWork.AppUserReadingProfileRepository.Remove(profile);
}
else
{
profile.Series = profile.Series.Where(s => !(s.SeriesId == seriesId && s.AppUserId == userId)).ToList();
}
}
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task AddProfileToLibrary(int userId, int profileId, int libraryId) public async Task AddProfileToLibrary(int userId, int profileId, int libraryId)
{ {
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfile(profileId); var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-not-found"); if (profile == null) throw new KavitaException("profile-doesnt-exist");
if (profile.UserId != userId) throw new UnauthorizedAccessException(); await DeleteImplicitAndRemoveFromUserProfiles(userId, [], [libraryId]);
var libraryProfile = await unitOfWork.AppUserReadingProfileRepository.GetLibraryProfile(userId, libraryId); profile.LibraryIds.Add(libraryId);
if (libraryProfile != null) unitOfWork.AppUserReadingProfileRepository.Update(profile);
{
libraryProfile.ReadingProfile = profile;
await unitOfWork.CommitAsync();
return;
}
libraryProfile = new LibraryReadingProfile
{
AppUserId = userId,
LibraryId = libraryId,
ReadingProfile = profile,
};
unitOfWork.AppUserReadingProfileRepository.Add(libraryProfile);
await unitOfWork.CommitAsync(); await unitOfWork.CommitAsync();
} }
public async Task ClearLibraryProfile(int userId, int libraryId) public async Task ClearLibraryProfile(int userId, int libraryId)
{ {
var profile = await unitOfWork.AppUserReadingProfileRepository.GetProfileForLibrary(userId, libraryId, ReadingProfileIncludes.Library); var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
if (profile == null) return; var libraryProfile = profiles.FirstOrDefault(p => p.LibraryIds.Contains(libraryId));
if (libraryProfile != null)
if (profile.Implicit)
{ {
unitOfWork.AppUserReadingProfileRepository.Remove(profile); libraryProfile.LibraryIds.Remove(libraryId);
await unitOfWork.CommitAsync(); unitOfWork.AppUserReadingProfileRepository.Update(libraryProfile);
return;
} }
profile.Libraries = profile.Libraries
.Where(s => !(s.LibraryId == libraryId && s.AppUserId == userId)) if (unitOfWork.HasChanges())
{
await unitOfWork.CommitAsync();
}
}
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(); .ToList();
await unitOfWork.CommitAsync(); 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);
} }
public static void UpdateReaderProfileFields(AppUserReadingProfile existingProfile, UserReadingProfileDto dto, bool updateName = true) public static void UpdateReaderProfileFields(AppUserReadingProfile existingProfile, UserReadingProfileDto dto, bool updateName = true)

View file

@ -2,7 +2,6 @@ import {PageLayoutMode} from '../page-layout-mode';
import {SiteTheme} from './site-theme'; import {SiteTheme} from './site-theme';
export interface Preferences { export interface Preferences {
defaultReadingProfileId: number;
// Global // Global
theme: SiteTheme; theme: SiteTheme;

View file

@ -13,11 +13,18 @@ import {PdfSpreadMode} from "./pdf-spread-mode";
import {Series} from "../series"; import {Series} from "../series";
import {Library} from "../library/library"; import {Library} from "../library/library";
export enum ReadingProfileKind {
Default = 0,
User = 1,
Implicit = 2,
}
export interface ReadingProfile { export interface ReadingProfile {
id: number; id: number;
name: string; name: string;
normalizedName: string; normalizedName: string;
kind: ReadingProfileKind;
// Manga Reader // Manga Reader
readingDirection: ReadingDirection; readingDirection: ReadingDirection;

View file

@ -36,10 +36,6 @@ export class ReadingProfileService {
return this.httpClient.delete(this.baseUrl + "ReadingProfile?profileId="+id); return this.httpClient.delete(this.baseUrl + "ReadingProfile?profileId="+id);
} }
setDefault(id: number) {
return this.httpClient.post(this.baseUrl + "ReadingProfile/set-default?profileId=" + id, {});
}
addToSeries(id: number, seriesId: number) { addToSeries(id: number, seriesId: number) {
return this.httpClient.post(this.baseUrl + `ReadingProfile/series/${seriesId}?profileId=${id}`, {}); return this.httpClient.post(this.baseUrl + `ReadingProfile/series/${seriesId}?profileId=${id}`, {});
} }

View file

@ -55,10 +55,7 @@
@if (selectedProfile.id !== 0) { @if (selectedProfile.id !== 0) {
<div class="d-flex justify-content-between"> <div class="d-flex justify-content-between">
<button class="me-2 btn btn-primary" [disabled]="selectedProfile.id === user.preferences.defaultReadingProfileId" (click)="setDefault(selectedProfile!.id)"> <button class="btn btn-danger" (click)="delete(selectedProfile!.id)" [disabled]="selectedProfile.kind === ReadingProfileKind.Default">
<span>{{t('make-default')}}</span>
</button>
<button class="btn btn-danger" (click)="delete(selectedProfile!.id)" [disabled]="selectedProfile.id === user.preferences.defaultReadingProfileId">
<i class="fa fa-trash" aria-hidden="true"></i> <i class="fa fa-trash" aria-hidden="true"></i>
</button> </button>
</div> </div>
@ -501,7 +498,7 @@
> >
<div class="fw-bold">{{profile.name | sentenceCase}}</div> <div class="fw-bold">{{profile.name | sentenceCase}}</div>
@if (profile.id === user.preferences.defaultReadingProfileId) { @if (profile.kind === ReadingProfileKind.Default) {
<span class="pill p-1 ms-1">{{t('default-profile')}}</span> <span class="pill p-1 ms-1">{{t('default-profile')}}</span>
} }

View file

@ -1,11 +1,18 @@
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, OnInit} from '@angular/core'; import {ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, OnInit} from '@angular/core';
import {ReadingProfileService} from "../../_services/reading-profile.service"; import {ReadingProfileService} from "../../_services/reading-profile.service";
import { import {
bookLayoutModes, bookWritingStyles, layoutModes, bookLayoutModes,
pageSplitOptions, pdfScrollModes, bookWritingStyles,
pdfSpreadModes, pdfThemes, layoutModes,
readingDirections, readingModes, pageSplitOptions,
ReadingProfile, scalingOptions pdfScrollModes,
pdfSpreadModes,
pdfThemes,
readingDirections,
readingModes,
ReadingProfile,
ReadingProfileKind,
scalingOptions
} from "../../_models/preferences/reading-profiles"; } from "../../_models/preferences/reading-profiles";
import {translate, TranslocoDirective} from "@jsverse/transloco"; import {translate, TranslocoDirective} from "@jsverse/transloco";
import {NgStyle, NgTemplateOutlet, TitleCasePipe} from "@angular/common"; import {NgStyle, NgTemplateOutlet, TitleCasePipe} from "@angular/common";
@ -34,13 +41,7 @@ import {SettingItemComponent} from "../../settings/_components/setting-item/sett
import {SettingSwitchComponent} from "../../settings/_components/setting-switch/setting-switch.component"; import {SettingSwitchComponent} from "../../settings/_components/setting-switch/setting-switch.component";
import {WritingStylePipe} from "../../_pipes/writing-style.pipe"; import {WritingStylePipe} from "../../_pipes/writing-style.pipe";
import {ColorPickerDirective} from "ngx-color-picker"; import {ColorPickerDirective} from "ngx-color-picker";
import { import {NgbNav, NgbNavContent, NgbNavItem, NgbNavLinkBase, NgbNavOutlet} from "@ng-bootstrap/ng-bootstrap";
NgbNav,
NgbNavItem,
NgbNavLinkBase,
NgbNavContent,
NgbNavOutlet
} from "@ng-bootstrap/ng-bootstrap";
import {filter} from "rxjs"; import {filter} from "rxjs";
import {takeUntilDestroyed} from "@angular/core/rxjs-interop"; import {takeUntilDestroyed} from "@angular/core/rxjs-interop";
import {LoadingComponent} from "../../shared/loading/loading.component"; import {LoadingComponent} from "../../shared/loading/loading.component";
@ -141,13 +142,6 @@ export class ManageReadingProfilesComponent implements OnInit {
}); });
} }
setDefault(id: number) {
this.readingProfileService.setDefault(id).subscribe(() => {
this.user.preferences.defaultReadingProfileId = id;
this.cdRef.markForCheck();
})
}
get widthOverwriteLabel() { get widthOverwriteLabel() {
const rawVal = this.readingProfileForm?.get('widthOverride')!.value; const rawVal = this.readingProfileForm?.get('widthOverride')!.value;
if (!rawVal) { if (!rawVal) {
@ -286,7 +280,7 @@ export class ManageReadingProfilesComponent implements OnInit {
} }
addNew() { addNew() {
const defaultProfile = this.readingProfiles.find(f => f.id === this.user.preferences.defaultReadingProfileId); const defaultProfile = this.readingProfiles.find(f => f.kind === ReadingProfileKind.Default);
this.selectedProfile = {...defaultProfile!}; this.selectedProfile = {...defaultProfile!};
this.selectedProfile.id = 0; this.selectedProfile.id = 0;
this.selectedProfile.name = "New Profile #" + (this.readingProfiles.length + 1); this.selectedProfile.name = "New Profile #" + (this.readingProfiles.length + 1);
@ -306,4 +300,5 @@ export class ManageReadingProfilesComponent implements OnInit {
protected readonly pdfScrollModes = pdfScrollModes; protected readonly pdfScrollModes = pdfScrollModes;
protected readonly TabId = TabId; protected readonly TabId = TabId;
protected readonly ReadingProfileKind = ReadingProfileKind;
} }

View file

@ -243,7 +243,6 @@ export class ManageUserPreferencesComponent implements OnInit {
//pdfSpreadMode: parseInt(modelSettings.pdfSpreadMode, 10), //pdfSpreadMode: parseInt(modelSettings.pdfSpreadMode, 10),
aniListScrobblingEnabled: modelSettings.aniListScrobblingEnabled, aniListScrobblingEnabled: modelSettings.aniListScrobblingEnabled,
wantToReadSync: modelSettings.wantToReadSync, wantToReadSync: modelSettings.wantToReadSync,
defaultReadingProfileId: this.user!.preferences.defaultReadingProfileId,
}; };
} }
} }