Reading Profiles (#3845)

Co-authored-by: Joseph Milazzo <joseph.v.milazzo@gmail.com>
This commit is contained in:
Fesaa 2025-06-08 16:16:44 +02:00 committed by GitHub
parent ea28d64302
commit 1856b01a46
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
67 changed files with 8118 additions and 1159 deletions

View file

@ -153,6 +153,9 @@ public class AccountController : BaseApiController
// Assign default streams
AddDefaultStreamsToUser(user);
// Assign default reading profile
await AddDefaultReadingProfileToUser(user);
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
if (string.IsNullOrEmpty(token)) return BadRequest(await _localizationService.Get("en", "confirm-token-gen"));
if (!await ConfirmEmailToken(token, user)) return BadRequest(await _localizationService.Get("en", "validate-email", token));
@ -609,7 +612,7 @@ public class AccountController : BaseApiController
}
/// <summary>
/// Requests the Invite Url for the UserId. Will return error if user is already validated.
/// Requests the Invite Url for the AppUserId. Will return error if user is already validated.
/// </summary>
/// <param name="userId"></param>
/// <param name="withBaseUrl">Include the "https://ip:port/" in the generated link</param>
@ -669,6 +672,9 @@ public class AccountController : BaseApiController
// Assign default streams
AddDefaultStreamsToUser(user);
// Assign default reading profile
await AddDefaultReadingProfileToUser(user);
// Assign Roles
var roles = dto.Roles;
var hasAdminRole = dto.Roles.Contains(PolicyConstants.AdminRole);
@ -779,6 +785,16 @@ public class AccountController : BaseApiController
}
}
private async Task AddDefaultReadingProfileToUser(AppUser user)
{
var profile = new AppUserReadingProfileBuilder(user.Id)
.WithName("Default Profile")
.WithKind(ReadingProfileKind.Default)
.Build();
_unitOfWork.AppUserReadingProfileRepository.Add(profile);
await _unitOfWork.CommitAsync();
}
/// <summary>
/// Last step in authentication flow, confirms the email token for email
/// </summary>

View file

@ -45,7 +45,7 @@ public class PluginController(IUnitOfWork unitOfWork, ITokenService tokenService
throw new KavitaUnauthenticatedUserException();
}
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId);
logger.LogInformation("Plugin {PluginName} has authenticated with {UserName} ({UserId})'s API Key", pluginName.Replace(Environment.NewLine, string.Empty), user!.UserName, userId);
logger.LogInformation("Plugin {PluginName} has authenticated with {UserName} ({AppUserId})'s API Key", pluginName.Replace(Environment.NewLine, string.Empty), user!.UserName, userId);
return new UserDto
{

View file

@ -0,0 +1,198 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Data.Repositories;
using API.DTOs;
using API.Extensions;
using API.Services;
using AutoMapper;
using Kavita.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace API.Controllers;
[Route("api/reading-profile")]
public class ReadingProfileController(ILogger<ReadingProfileController> logger, IUnitOfWork unitOfWork,
IReadingProfileService readingProfileService): BaseApiController
{
/// <summary>
/// Gets all non-implicit reading profiles for a user
/// </summary>
/// <returns></returns>
[HttpGet("all")]
public async Task<ActionResult<IList<UserReadingProfileDto>>> GetAllReadingProfiles()
{
return Ok(await unitOfWork.AppUserReadingProfileRepository.GetProfilesDtoForUser(User.GetUserId(), true));
}
/// <summary>
/// Returns the ReadingProfile that should be applied to the given series, walks up the tree.
/// Series -> Library -> Default
/// </summary>
/// <param name="seriesId"></param>
/// <param name="skipImplicit"></param>
/// <returns></returns>
[HttpGet("{seriesId:int}")]
public async Task<ActionResult<UserReadingProfileDto>> GetProfileForSeries(int seriesId, [FromQuery] bool skipImplicit)
{
return Ok(await readingProfileService.GetReadingProfileDtoForSeries(User.GetUserId(), seriesId, skipImplicit));
}
/// <summary>
/// Returns the (potential) Reading Profile bound to the library
/// </summary>
/// <param name="libraryId"></param>
/// <returns></returns>
[HttpGet("library")]
public async Task<ActionResult<UserReadingProfileDto?>> GetProfileForLibrary(int libraryId)
{
return Ok(await readingProfileService.GetReadingProfileDtoForLibrary(User.GetUserId(), libraryId));
}
/// <summary>
/// Creates a new reading profile for the current user
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost("create")]
public async Task<ActionResult<UserReadingProfileDto>> CreateReadingProfile([FromBody] UserReadingProfileDto dto)
{
return Ok(await readingProfileService.CreateReadingProfile(User.GetUserId(), dto));
}
/// <summary>
/// Promotes the implicit profile to a user profile. Removes the series from other profiles
/// </summary>
/// <param name="profileId"></param>
/// <returns></returns>
[HttpPost("promote")]
public async Task<ActionResult<UserReadingProfileDto>> PromoteImplicitReadingProfile([FromQuery] int profileId)
{
return Ok(await readingProfileService.PromoteImplicitProfile(User.GetUserId(), profileId));
}
/// <summary>
/// Update the implicit reading profile for a series, creates one if none exists
/// </summary>
/// <remarks>Any modification to the reader settings during reading will create an implicit profile. Use "update-parent" to save to the bound series profile.</remarks>
/// <param name="dto"></param>
/// <param name="seriesId"></param>
/// <returns></returns>
[HttpPost("series")]
public async Task<ActionResult<UserReadingProfileDto>> UpdateReadingProfileForSeries([FromBody] UserReadingProfileDto dto, [FromQuery] int seriesId)
{
var updatedProfile = await readingProfileService.UpdateImplicitReadingProfile(User.GetUserId(), seriesId, dto);
return Ok(updatedProfile);
}
/// <summary>
/// Updates the non-implicit reading profile for the given series, and removes implicit profiles
/// </summary>
/// <param name="dto"></param>
/// <param name="seriesId"></param>
/// <returns></returns>
[HttpPost("update-parent")]
public async Task<ActionResult<UserReadingProfileDto>> UpdateParentProfileForSeries([FromBody] UserReadingProfileDto dto, [FromQuery] int seriesId)
{
var newParentProfile = await readingProfileService.UpdateParent(User.GetUserId(), seriesId, dto);
return Ok(newParentProfile);
}
/// <summary>
/// Updates the given reading profile, must belong to the current user
/// </summary>
/// <param name="dto"></param>
/// <returns>The updated reading profile</returns>
/// <remarks>
/// This does not update connected series and libraries.
/// </remarks>
[HttpPost]
public async Task<ActionResult<UserReadingProfileDto>> UpdateReadingProfile(UserReadingProfileDto dto)
{
return Ok(await readingProfileService.UpdateReadingProfile(User.GetUserId(), dto));
}
/// <summary>
/// Deletes the given profile, requires the profile to belong to the logged-in user
/// </summary>
/// <param name="profileId"></param>
/// <returns></returns>
/// <exception cref="KavitaException"></exception>
/// <exception cref="UnauthorizedAccessException"></exception>
[HttpDelete]
public async Task<IActionResult> DeleteReadingProfile([FromQuery] int profileId)
{
await readingProfileService.DeleteReadingProfile(User.GetUserId(), profileId);
return Ok();
}
/// <summary>
/// Sets the reading profile for a given series, removes the old one
/// </summary>
/// <param name="seriesId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
[HttpPost("series/{seriesId:int}")]
public async Task<IActionResult> AddProfileToSeries(int seriesId, [FromQuery] int profileId)
{
await readingProfileService.AddProfileToSeries(User.GetUserId(), profileId, seriesId);
return Ok();
}
/// <summary>
/// Clears the reading profile for the given series for the currently logged-in user
/// </summary>
/// <param name="seriesId"></param>
/// <returns></returns>
[HttpDelete("series/{seriesId:int}")]
public async Task<IActionResult> ClearSeriesProfile(int seriesId)
{
await readingProfileService.ClearSeriesProfile(User.GetUserId(), seriesId);
return Ok();
}
/// <summary>
/// Sets the reading profile for a given library, removes the old one
/// </summary>
/// <param name="libraryId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
[HttpPost("library/{libraryId:int}")]
public async Task<IActionResult> AddProfileToLibrary(int libraryId, [FromQuery] int profileId)
{
await readingProfileService.AddProfileToLibrary(User.GetUserId(), profileId, libraryId);
return Ok();
}
/// <summary>
/// Clears the reading profile for the given library for the currently logged-in user
/// </summary>
/// <param name="libraryId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
[HttpDelete("library/{libraryId:int}")]
public async Task<IActionResult> ClearLibraryProfile(int libraryId)
{
await readingProfileService.ClearLibraryProfile(User.GetUserId(), libraryId);
return Ok();
}
/// <summary>
/// Assigns the reading profile to all passes series, and deletes their implicit profiles
/// </summary>
/// <param name="profileId"></param>
/// <param name="seriesIds"></param>
/// <returns></returns>
[HttpPost("bulk")]
public async Task<IActionResult> BulkAddReadingProfile([FromQuery] int profileId, [FromBody] IList<int> seriesIds)
{
await readingProfileService.BulkAddProfileToSeries(User.GetUserId(), profileId, seriesIds);
return Ok();
}
}

View file

@ -103,39 +103,13 @@ public class UsersController : BaseApiController
var existingPreferences = user!.UserPreferences;
existingPreferences.ReadingDirection = preferencesDto.ReadingDirection;
existingPreferences.ScalingOption = preferencesDto.ScalingOption;
existingPreferences.PageSplitOption = preferencesDto.PageSplitOption;
existingPreferences.AutoCloseMenu = preferencesDto.AutoCloseMenu;
existingPreferences.ShowScreenHints = preferencesDto.ShowScreenHints;
existingPreferences.EmulateBook = preferencesDto.EmulateBook;
existingPreferences.ReaderMode = preferencesDto.ReaderMode;
existingPreferences.LayoutMode = preferencesDto.LayoutMode;
existingPreferences.BackgroundColor = string.IsNullOrEmpty(preferencesDto.BackgroundColor) ? "#000000" : preferencesDto.BackgroundColor;
existingPreferences.BookReaderMargin = preferencesDto.BookReaderMargin;
existingPreferences.BookReaderLineSpacing = preferencesDto.BookReaderLineSpacing;
existingPreferences.BookReaderFontFamily = preferencesDto.BookReaderFontFamily;
existingPreferences.BookReaderFontSize = preferencesDto.BookReaderFontSize;
existingPreferences.BookReaderTapToPaginate = preferencesDto.BookReaderTapToPaginate;
existingPreferences.BookReaderReadingDirection = preferencesDto.BookReaderReadingDirection;
existingPreferences.BookReaderWritingStyle = preferencesDto.BookReaderWritingStyle;
existingPreferences.BookThemeName = preferencesDto.BookReaderThemeName;
existingPreferences.BookReaderLayoutMode = preferencesDto.BookReaderLayoutMode;
existingPreferences.BookReaderImmersiveMode = preferencesDto.BookReaderImmersiveMode;
existingPreferences.GlobalPageLayoutMode = preferencesDto.GlobalPageLayoutMode;
existingPreferences.BlurUnreadSummaries = preferencesDto.BlurUnreadSummaries;
existingPreferences.LayoutMode = preferencesDto.LayoutMode;
existingPreferences.PromptForDownloadSize = preferencesDto.PromptForDownloadSize;
existingPreferences.NoTransitions = preferencesDto.NoTransitions;
existingPreferences.SwipeToPaginate = preferencesDto.SwipeToPaginate;
existingPreferences.AllowAutomaticWebtoonReaderDetection = preferencesDto.AllowAutomaticWebtoonReaderDetection;
existingPreferences.CollapseSeriesRelationships = preferencesDto.CollapseSeriesRelationships;
existingPreferences.ShareReviews = preferencesDto.ShareReviews;
existingPreferences.PdfTheme = preferencesDto.PdfTheme;
existingPreferences.PdfScrollMode = preferencesDto.PdfScrollMode;
existingPreferences.PdfSpreadMode = preferencesDto.PdfSpreadMode;
if (await _licenseService.HasActiveLicense())
{
existingPreferences.AniListScrobblingEnabled = preferencesDto.AniListScrobblingEnabled;

View file

@ -9,61 +9,6 @@ namespace API.DTOs;
public sealed record UserPreferencesDto
{
/// <inheritdoc cref="API.Entities.AppUserPreferences.ReadingDirection"/>
[Required]
public ReadingDirection ReadingDirection { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.ScalingOption"/>
[Required]
public ScalingOption ScalingOption { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.PageSplitOption"/>
[Required]
public PageSplitOption PageSplitOption { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.ReaderMode"/>
[Required]
public ReaderMode ReaderMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.LayoutMode"/>
[Required]
public LayoutMode LayoutMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.EmulateBook"/>
[Required]
public bool EmulateBook { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BackgroundColor"/>
[Required]
public string BackgroundColor { get; set; } = "#000000";
/// <inheritdoc cref="API.Entities.AppUserPreferences.SwipeToPaginate"/>
[Required]
public bool SwipeToPaginate { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.AutoCloseMenu"/>
[Required]
public bool AutoCloseMenu { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.ShowScreenHints"/>
[Required]
public bool ShowScreenHints { get; set; } = true;
/// <inheritdoc cref="API.Entities.AppUserPreferences.AllowAutomaticWebtoonReaderDetection"/>
[Required]
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderMargin"/>
[Required]
public int BookReaderMargin { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderLineSpacing"/>
[Required]
public int BookReaderLineSpacing { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderFontSize"/>
[Required]
public int BookReaderFontSize { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderFontFamily"/>
[Required]
public string BookReaderFontFamily { get; set; } = null!;
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderTapToPaginate"/>
[Required]
public bool BookReaderTapToPaginate { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderReadingDirection"/>
[Required]
public ReadingDirection BookReaderReadingDirection { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderWritingStyle"/>
[Required]
public WritingStyle BookReaderWritingStyle { get; set; }
/// <summary>
/// UI Site Global Setting: The UI theme the user should use.
@ -72,15 +17,6 @@ public sealed record UserPreferencesDto
[Required]
public SiteThemeDto? Theme { get; set; }
[Required] public string BookReaderThemeName { get; set; } = null!;
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderLayoutMode"/>
[Required]
public BookPageLayoutMode BookReaderLayoutMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.BookReaderImmersiveMode"/>
[Required]
public bool BookReaderImmersiveMode { get; set; } = false;
/// <inheritdoc cref="API.Entities.AppUserPreferences.GlobalPageLayoutMode"/>
[Required]
public PageLayoutMode GlobalPageLayoutMode { get; set; } = PageLayoutMode.Cards;
/// <inheritdoc cref="API.Entities.AppUserPreferences.BlurUnreadSummaries"/>
[Required]
@ -101,16 +37,6 @@ public sealed record UserPreferencesDto
[Required]
public string Locale { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfTheme"/>
[Required]
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfScrollMode"/>
[Required]
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
/// <inheritdoc cref="API.Entities.AppUserPreferences.PdfSpreadMode"/>
[Required]
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
/// <inheritdoc cref="API.Entities.AppUserPreferences.AniListScrobblingEnabled"/>
public bool AniListScrobblingEnabled { get; set; }
/// <inheritdoc cref="API.Entities.AppUserPreferences.WantToReadSync"/>

View file

@ -0,0 +1,129 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using API.Entities;
using API.Entities.Enums;
using API.Entities.Enums.UserPreferences;
namespace API.DTOs;
public sealed record UserReadingProfileDto
{
public int Id { get; set; }
public int UserId { get; init; }
public string Name { get; init; }
public ReadingProfileKind Kind { get; init; }
#region MangaReader
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ReadingDirection"/>
[Required]
public ReadingDirection ReadingDirection { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ScalingOption"/>
[Required]
public ScalingOption ScalingOption { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PageSplitOption"/>
[Required]
public PageSplitOption PageSplitOption { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ReaderMode"/>
[Required]
public ReaderMode ReaderMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.AutoCloseMenu"/>
[Required]
public bool AutoCloseMenu { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.ShowScreenHints"/>
[Required]
public bool ShowScreenHints { get; set; } = true;
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.EmulateBook"/>
[Required]
public bool EmulateBook { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.LayoutMode"/>
[Required]
public LayoutMode LayoutMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BackgroundColor"/>
[Required]
public string BackgroundColor { get; set; } = "#000000";
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.SwipeToPaginate"/>
[Required]
public bool SwipeToPaginate { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.AllowAutomaticWebtoonReaderDetection"/>
[Required]
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
/// <inheritdoc cref="AppUserReadingProfile.WidthOverride"/>
public int? WidthOverride { get; set; }
#endregion
#region EpubReader
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderMargin"/>
[Required]
public int BookReaderMargin { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderLineSpacing"/>
[Required]
public int BookReaderLineSpacing { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderFontSize"/>
[Required]
public int BookReaderFontSize { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderFontFamily"/>
[Required]
public string BookReaderFontFamily { get; set; } = null!;
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderTapToPaginate"/>
[Required]
public bool BookReaderTapToPaginate { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderReadingDirection"/>
[Required]
public ReadingDirection BookReaderReadingDirection { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderWritingStyle"/>
[Required]
public WritingStyle BookReaderWritingStyle { get; set; }
/// <inheritdoc cref="AppUserReadingProfile.BookThemeName"/>
[Required]
public string BookReaderThemeName { get; set; } = null!;
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderLayoutMode"/>
[Required]
public BookPageLayoutMode BookReaderLayoutMode { get; set; }
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.BookReaderImmersiveMode"/>
[Required]
public bool BookReaderImmersiveMode { get; set; } = false;
#endregion
#region PdfReader
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfTheme"/>
[Required]
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfScrollMode"/>
[Required]
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
/// <inheritdoc cref="API.Entities.AppUserReadingProfile.PdfSpreadMode"/>
[Required]
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
#endregion
}

View file

@ -81,6 +81,7 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
public DbSet<MetadataSettings> MetadataSettings { get; set; } = null!;
public DbSet<MetadataFieldMapping> MetadataFieldMapping { get; set; } = null!;
public DbSet<AppUserChapterRating> AppUserChapterRating { get; set; } = null!;
public DbSet<AppUserReadingProfile> AppUserReadingProfiles { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder builder)
{
@ -256,6 +257,32 @@ public sealed class DataContext : IdentityDbContext<AppUser, AppRole, int,
builder.Entity<MetadataSettings>()
.Property(b => b.EnableCoverImage)
.HasDefaultValue(true);
builder.Entity<AppUserReadingProfile>()
.Property(b => b.BookThemeName)
.HasDefaultValue("Dark");
builder.Entity<AppUserReadingProfile>()
.Property(b => b.BackgroundColor)
.HasDefaultValue("#000000");
builder.Entity<AppUserReadingProfile>()
.Property(b => b.BookReaderWritingStyle)
.HasDefaultValue(WritingStyle.Horizontal);
builder.Entity<AppUserReadingProfile>()
.Property(b => b.AllowAutomaticWebtoonReaderDetection)
.HasDefaultValue(true);
builder.Entity<AppUserReadingProfile>()
.Property(rp => rp.LibraryIds)
.HasConversion(
v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default),
v => JsonSerializer.Deserialize<List<int>>(v, JsonSerializerOptions.Default) ?? new List<int>())
.HasColumnType("TEXT");
builder.Entity<AppUserReadingProfile>()
.Property(rp => rp.SeriesIds)
.HasConversion(
v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default),
v => JsonSerializer.Deserialize<List<int>>(v, JsonSerializerOptions.Default) ?? new List<int>())
.HasColumnType("TEXT");
}
#nullable enable

View file

@ -0,0 +1,84 @@
using System;
using System.Threading.Tasks;
using API.Entities;
using API.Entities.Enums;
using API.Entities.History;
using API.Extensions;
using API.Helpers.Builders;
using Kavita.Common.EnvironmentInfo;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace API.Data.ManualMigrations;
public static class ManualMigrateReadingProfiles
{
public static async Task Migrate(DataContext context, ILogger<Program> logger)
{
if (await context.ManualMigrationHistory.AnyAsync(m => m.Name == "ManualMigrateReadingProfiles"))
{
return;
}
logger.LogCritical("Running ManualMigrateReadingProfiles migration - Please be patient, this may take some time. This is not an error");
var users = await context.AppUser
.Include(u => u.UserPreferences)
.Include(u => u.ReadingProfiles)
.ToListAsync();
foreach (var user in users)
{
var readingProfile = new AppUserReadingProfile
{
Name = "Default",
NormalizedName = "Default".ToNormalized(),
Kind = ReadingProfileKind.Default,
LibraryIds = [],
SeriesIds = [],
BackgroundColor = user.UserPreferences.BackgroundColor,
EmulateBook = user.UserPreferences.EmulateBook,
AppUser = user,
PdfTheme = user.UserPreferences.PdfTheme,
ReaderMode = user.UserPreferences.ReaderMode,
ReadingDirection = user.UserPreferences.ReadingDirection,
ScalingOption = user.UserPreferences.ScalingOption,
LayoutMode = user.UserPreferences.LayoutMode,
WidthOverride = null,
AppUserId = user.Id,
AutoCloseMenu = user.UserPreferences.AutoCloseMenu,
BookReaderMargin = user.UserPreferences.BookReaderMargin,
PageSplitOption = user.UserPreferences.PageSplitOption,
BookThemeName = user.UserPreferences.BookThemeName,
PdfSpreadMode = user.UserPreferences.PdfSpreadMode,
PdfScrollMode = user.UserPreferences.PdfScrollMode,
SwipeToPaginate = user.UserPreferences.SwipeToPaginate,
BookReaderFontFamily = user.UserPreferences.BookReaderFontFamily,
BookReaderFontSize = user.UserPreferences.BookReaderFontSize,
BookReaderImmersiveMode = user.UserPreferences.BookReaderImmersiveMode,
BookReaderLayoutMode = user.UserPreferences.BookReaderLayoutMode,
BookReaderLineSpacing = user.UserPreferences.BookReaderLineSpacing,
BookReaderReadingDirection = user.UserPreferences.BookReaderReadingDirection,
BookReaderWritingStyle = user.UserPreferences.BookReaderWritingStyle,
AllowAutomaticWebtoonReaderDetection = user.UserPreferences.AllowAutomaticWebtoonReaderDetection,
BookReaderTapToPaginate = user.UserPreferences.BookReaderTapToPaginate,
ShowScreenHints = user.UserPreferences.ShowScreenHints,
};
user.ReadingProfiles.Add(readingProfile);
}
await context.SaveChangesAsync();
context.ManualMigrationHistory.Add(new ManualMigrationHistory
{
Name = "ManualMigrateReadingProfiles",
ProductVersion = BuildInfo.Version.ToString(),
RanAt = DateTime.UtcNow,
});
await context.SaveChangesAsync();
logger.LogCritical("Running ManualMigrateReadingProfiles migration - Completed. This is not an error");
}
}

File diff suppressed because it is too large Load diff

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

@ -609,6 +609,120 @@ namespace API.Data.Migrations
b.ToTable("AppUserRating");
});
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("AllowAutomaticWebtoonReaderDetection")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(true);
b.Property<int>("AppUserId")
.HasColumnType("INTEGER");
b.Property<bool>("AutoCloseMenu")
.HasColumnType("INTEGER");
b.Property<string>("BackgroundColor")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasDefaultValue("#000000");
b.Property<string>("BookReaderFontFamily")
.HasColumnType("TEXT");
b.Property<int>("BookReaderFontSize")
.HasColumnType("INTEGER");
b.Property<bool>("BookReaderImmersiveMode")
.HasColumnType("INTEGER");
b.Property<int>("BookReaderLayoutMode")
.HasColumnType("INTEGER");
b.Property<int>("BookReaderLineSpacing")
.HasColumnType("INTEGER");
b.Property<int>("BookReaderMargin")
.HasColumnType("INTEGER");
b.Property<int>("BookReaderReadingDirection")
.HasColumnType("INTEGER");
b.Property<bool>("BookReaderTapToPaginate")
.HasColumnType("INTEGER");
b.Property<int>("BookReaderWritingStyle")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER")
.HasDefaultValue(0);
b.Property<string>("BookThemeName")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT")
.HasDefaultValue("Dark");
b.Property<bool>("EmulateBook")
.HasColumnType("INTEGER");
b.Property<int>("Kind")
.HasColumnType("INTEGER");
b.Property<int>("LayoutMode")
.HasColumnType("INTEGER");
b.Property<string>("LibraryIds")
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT");
b.Property<string>("NormalizedName")
.HasColumnType("TEXT");
b.Property<int>("PageSplitOption")
.HasColumnType("INTEGER");
b.Property<int>("PdfScrollMode")
.HasColumnType("INTEGER");
b.Property<int>("PdfSpreadMode")
.HasColumnType("INTEGER");
b.Property<int>("PdfTheme")
.HasColumnType("INTEGER");
b.Property<int>("ReaderMode")
.HasColumnType("INTEGER");
b.Property<int>("ReadingDirection")
.HasColumnType("INTEGER");
b.Property<int>("ScalingOption")
.HasColumnType("INTEGER");
b.PrimitiveCollection<string>("SeriesIds")
.HasColumnType("TEXT");
b.Property<bool>("ShowScreenHints")
.HasColumnType("INTEGER");
b.Property<bool>("SwipeToPaginate")
.HasColumnType("INTEGER");
b.Property<int?>("WidthOverride")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("AppUserId");
b.ToTable("AppUserReadingProfiles");
});
modelBuilder.Entity("API.Entities.AppUserRole", b =>
{
b.Property<int>("UserId")
@ -2838,6 +2952,17 @@ namespace API.Data.Migrations
b.Navigation("Series");
});
modelBuilder.Entity("API.Entities.AppUserReadingProfile", b =>
{
b.HasOne("API.Entities.AppUser", "AppUser")
.WithMany("ReadingProfiles")
.HasForeignKey("AppUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AppUser");
});
modelBuilder.Entity("API.Entities.AppUserRole", b =>
{
b.HasOne("API.Entities.AppRole", "Role")
@ -3476,6 +3601,8 @@ namespace API.Data.Migrations
b.Navigation("ReadingLists");
b.Navigation("ReadingProfiles");
b.Navigation("ScrobbleHolds");
b.Navigation("SideNavStreams");

View file

@ -0,0 +1,112 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.DTOs;
using API.Entities;
using API.Entities.Enums;
using API.Extensions;
using API.Extensions.QueryExtensions;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
namespace API.Data.Repositories;
public interface IAppUserReadingProfileRepository
{
/// <summary>
/// Return the given profile if it belongs the user
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
Task<AppUserReadingProfile?> GetUserProfile(int userId, int profileId);
/// <summary>
/// Returns all reading profiles for the user
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool skipImplicit = false);
/// <summary>
/// Returns all reading profiles for the user
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool skipImplicit = false);
/// <summary>
/// Is there a user reading profile with this name (normalized)
/// </summary>
/// <param name="userId"></param>
/// <param name="name"></param>
/// <returns></returns>
Task<bool> IsProfileNameInUse(int userId, string name);
void Add(AppUserReadingProfile readingProfile);
void Update(AppUserReadingProfile readingProfile);
void Remove(AppUserReadingProfile readingProfile);
void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles);
}
public class AppUserReadingProfileRepository(DataContext context, IMapper mapper): IAppUserReadingProfileRepository
{
public async Task<AppUserReadingProfile?> GetUserProfile(int userId, int profileId)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId && rp.Id == profileId)
.FirstOrDefaultAsync();
}
public async Task<IList<AppUserReadingProfile>> GetProfilesForUser(int userId, bool skipImplicit = false)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId)
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
.ToListAsync();
}
/// <summary>
/// Returns all Reading Profiles for the User
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public async Task<IList<UserReadingProfileDto>> GetProfilesDtoForUser(int userId, bool skipImplicit = false)
{
return await context.AppUserReadingProfiles
.Where(rp => rp.AppUserId == userId)
.WhereIf(skipImplicit, rp => rp.Kind != ReadingProfileKind.Implicit)
.ProjectTo<UserReadingProfileDto>(mapper.ConfigurationProvider)
.ToListAsync();
}
public async Task<bool> IsProfileNameInUse(int userId, string name)
{
var normalizedName = name.ToNormalized();
return await context.AppUserReadingProfiles
.Where(rp => rp.NormalizedName == normalizedName && rp.AppUserId == userId)
.AnyAsync();
}
public void Add(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Add(readingProfile);
}
public void Update(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Update(readingProfile).State = EntityState.Modified;
}
public void Remove(AppUserReadingProfile readingProfile)
{
context.AppUserReadingProfiles.Remove(readingProfile);
}
public void RemoveRange(IEnumerable<AppUserReadingProfile> readingProfiles)
{
context.AppUserReadingProfiles.RemoveRange(readingProfiles);
}
}

View file

@ -111,7 +111,7 @@ public class GenreRepository : IGenreRepository
/// <summary>
/// Returns a set of Genre tags for a set of library Ids.
/// UserId will restrict returned Genres based on user's age restriction and library access.
/// AppUserId will restrict returned Genres based on user's age restriction and library access.
/// </summary>
/// <param name="userId"></param>
/// <param name="libraryIds"></param>

View file

@ -757,7 +757,7 @@ public class UserRepository : IUserRepository
/// <summary>
/// Fetches the UserId by API Key. This does not include any extra information
/// Fetches the AppUserId by API Key. This does not include any extra information
/// </summary>
/// <param name="apiKey"></param>
/// <returns></returns>

View file

@ -33,6 +33,7 @@ public interface IUnitOfWork
IAppUserExternalSourceRepository AppUserExternalSourceRepository { get; }
IExternalSeriesMetadataRepository ExternalSeriesMetadataRepository { get; }
IEmailHistoryRepository EmailHistoryRepository { get; }
IAppUserReadingProfileRepository AppUserReadingProfileRepository { get; }
bool Commit();
Task<bool> CommitAsync();
bool HasChanges();
@ -74,6 +75,7 @@ public class UnitOfWork : IUnitOfWork
AppUserExternalSourceRepository = new AppUserExternalSourceRepository(_context, _mapper);
ExternalSeriesMetadataRepository = new ExternalSeriesMetadataRepository(_context, _mapper);
EmailHistoryRepository = new EmailHistoryRepository(_context, _mapper);
AppUserReadingProfileRepository = new AppUserReadingProfileRepository(_context, _mapper);
}
/// <summary>
@ -103,6 +105,7 @@ public class UnitOfWork : IUnitOfWork
public IAppUserExternalSourceRepository AppUserExternalSourceRepository { get; }
public IExternalSeriesMetadataRepository ExternalSeriesMetadataRepository { get; }
public IEmailHistoryRepository EmailHistoryRepository { get; }
public IAppUserReadingProfileRepository AppUserReadingProfileRepository { get; }
/// <summary>
/// Commits changes to the DB. Completes the open transaction.

View file

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

View file

@ -1,4 +1,5 @@
using API.Data;
using System.Collections.Generic;
using API.Data;
using API.Entities.Enums;
using API.Entities.Enums.UserPreferences;

View file

@ -0,0 +1,143 @@
using System.Collections.Generic;
using API.Entities.Enums;
using API.Entities.Enums.UserPreferences;
namespace API.Entities;
public class AppUserReadingProfile
{
public int Id { get; set; }
public string Name { get; set; }
public string NormalizedName { get; set; }
public int AppUserId { get; set; }
public AppUser AppUser { get; set; }
public ReadingProfileKind Kind { get; set; }
public List<int> LibraryIds { get; set; }
public List<int> SeriesIds { get; set; }
#region MangaReader
/// <summary>
/// Manga Reader Option: What direction should the next/prev page buttons go
/// </summary>
public ReadingDirection ReadingDirection { get; set; } = ReadingDirection.LeftToRight;
/// <summary>
/// Manga Reader Option: How should the image be scaled to screen
/// </summary>
public ScalingOption ScalingOption { get; set; } = ScalingOption.Automatic;
/// <summary>
/// Manga Reader Option: Which side of a split image should we show first
/// </summary>
public PageSplitOption PageSplitOption { get; set; } = PageSplitOption.FitSplit;
/// <summary>
/// Manga Reader Option: How the manga reader should perform paging or reading of the file
/// <example>
/// Webtoon uses scrolling to page, MANGA_LR uses paging by clicking left/right side of reader, MANGA_UD uses paging
/// by clicking top/bottom sides of reader.
/// </example>
/// </summary>
public ReaderMode ReaderMode { get; set; }
/// <summary>
/// Manga Reader Option: Allow the menu to close after 6 seconds without interaction
/// </summary>
public bool AutoCloseMenu { get; set; } = true;
/// <summary>
/// Manga Reader Option: Show screen hints to the user on some actions, ie) pagination direction change
/// </summary>
public bool ShowScreenHints { get; set; } = true;
/// <summary>
/// Manga Reader Option: Emulate a book by applying a shadow effect on the pages
/// </summary>
public bool EmulateBook { get; set; } = false;
/// <summary>
/// Manga Reader Option: How many pages to display in the reader at once
/// </summary>
public LayoutMode LayoutMode { get; set; } = LayoutMode.Single;
/// <summary>
/// Manga Reader Option: Background color of the reader
/// </summary>
public string BackgroundColor { get; set; } = "#000000";
/// <summary>
/// Manga Reader Option: Should swiping trigger pagination
/// </summary>
public bool SwipeToPaginate { get; set; }
/// <summary>
/// Manga Reader Option: Allow Automatic Webtoon detection
/// </summary>
public bool AllowAutomaticWebtoonReaderDetection { get; set; }
/// <summary>
/// Manga Reader Option: Optional fixed width override
/// </summary>
public int? WidthOverride { get; set; } = null;
#endregion
#region EpubReader
/// <summary>
/// Book Reader Option: Override extra Margin
/// </summary>
public int BookReaderMargin { get; set; } = 15;
/// <summary>
/// Book Reader Option: Override line-height
/// </summary>
public int BookReaderLineSpacing { get; set; } = 100;
/// <summary>
/// Book Reader Option: Override font size
/// </summary>
public int BookReaderFontSize { get; set; } = 100;
/// <summary>
/// Book Reader Option: Maps to the default Kavita font-family (inherit) or an override
/// </summary>
public string BookReaderFontFamily { get; set; } = "default";
/// <summary>
/// Book Reader Option: Allows tapping on side of screens to paginate
/// </summary>
public bool BookReaderTapToPaginate { get; set; } = false;
/// <summary>
/// Book Reader Option: What direction should the next/prev page buttons go
/// </summary>
public ReadingDirection BookReaderReadingDirection { get; set; } = ReadingDirection.LeftToRight;
/// <summary>
/// Book Reader Option: Defines the writing styles vertical/horizontal
/// </summary>
public WritingStyle BookReaderWritingStyle { get; set; } = WritingStyle.Horizontal;
/// <summary>
/// Book Reader Option: The color theme to decorate the book contents
/// </summary>
/// <remarks>Should default to Dark</remarks>
public string BookThemeName { get; set; } = "Dark";
/// <summary>
/// Book Reader Option: The way a page from a book is rendered. Default is as book dictates, 1 column is fit to height,
/// 2 column is fit to height, 2 columns
/// </summary>
/// <remarks>Defaults to Default</remarks>
public BookPageLayoutMode BookReaderLayoutMode { get; set; } = BookPageLayoutMode.Default;
/// <summary>
/// Book Reader Option: A flag that hides the menu-ing system behind a click on the screen. This should be used with tap to paginate, but the app doesn't enforce this.
/// </summary>
/// <remarks>Defaults to false</remarks>
public bool BookReaderImmersiveMode { get; set; } = false;
#endregion
#region PdfReader
/// <summary>
/// PDF Reader: Theme of the Reader
/// </summary>
public PdfTheme PdfTheme { get; set; } = PdfTheme.Dark;
/// <summary>
/// PDF Reader: Scroll mode of the reader
/// </summary>
public PdfScrollMode PdfScrollMode { get; set; } = PdfScrollMode.Vertical;
/// <summary>
/// PDF Reader: Spread Mode of the reader
/// </summary>
public PdfSpreadMode PdfSpreadMode { get; set; } = PdfSpreadMode.None;
#endregion
}

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 track changes made in the readers. Can be converted to a User Reading Profile.
/// </summary>
Implicit
}

View file

@ -54,6 +54,7 @@ public static class ApplicationServiceExtensions
services.AddScoped<IStreamService, StreamService>();
services.AddScoped<IRatingService, RatingService>();
services.AddScoped<IPersonService, PersonService>();
services.AddScoped<IReadingProfileService, ReadingProfileService>();
services.AddScoped<IScannerService, ScannerService>();
services.AddScoped<IProcessSeries, ProcessSeries>();

View file

@ -275,13 +275,12 @@ public class AutoMapperProfiles : Profile
CreateMap<AppUserPreferences, UserPreferencesDto>()
.ForMember(dest => dest.Theme,
opt =>
opt.MapFrom(src => src.Theme))
opt.MapFrom(src => src.Theme));
CreateMap<AppUserReadingProfile, UserReadingProfileDto>()
.ForMember(dest => dest.BookReaderThemeName,
opt =>
opt.MapFrom(src => src.BookThemeName))
.ForMember(dest => dest.BookReaderLayoutMode,
opt =>
opt.MapFrom(src => src.BookReaderLayoutMode));
opt.MapFrom(src => src.BookThemeName));
CreateMap<AppUserBookmark, BookmarkDto>();

View file

@ -21,7 +21,7 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
ApiKey = HashUtil.ApiKey(),
UserPreferences = new AppUserPreferences
{
Theme = theme ?? Seed.DefaultThemes.First()
Theme = theme ?? Seed.DefaultThemes.First(),
},
ReadingLists = new List<ReadingList>(),
Bookmarks = new List<AppUserBookmark>(),
@ -31,7 +31,8 @@ public class AppUserBuilder : IEntityBuilder<AppUser>
Devices = new List<Device>(),
Id = 0,
DashboardStreams = new List<AppUserDashboardStream>(),
SideNavStreams = new List<AppUserSideNavStream>()
SideNavStreams = new List<AppUserSideNavStream>(),
ReadingProfiles = [],
};
}

View file

@ -0,0 +1,54 @@
using API.Entities;
using API.Entities.Enums;
using API.Extensions;
namespace API.Helpers.Builders;
public class AppUserReadingProfileBuilder
{
private readonly AppUserReadingProfile _profile;
public AppUserReadingProfile Build() => _profile;
/// <summary>
/// The profile's kind will be <see cref="ReadingProfileKind.User"/> unless overwritten with <see cref="WithKind"/>
/// </summary>
/// <param name="userId"></param>
public AppUserReadingProfileBuilder(int userId)
{
_profile = new AppUserReadingProfile
{
AppUserId = userId,
Kind = ReadingProfileKind.User,
SeriesIds = [],
LibraryIds = []
};
}
public AppUserReadingProfileBuilder WithSeries(Series series)
{
_profile.SeriesIds.Add(series.Id);
return this;
}
public AppUserReadingProfileBuilder WithLibrary(Library library)
{
_profile.LibraryIds.Add(library.Id);
return this;
}
public AppUserReadingProfileBuilder WithKind(ReadingProfileKind kind)
{
_profile.Kind = kind;
return this;
}
public AppUserReadingProfileBuilder WithName(string name)
{
_profile.Name = name;
_profile.NormalizedName = name.ToNormalized();
return this;
}
}

View file

@ -230,6 +230,8 @@
"scan-libraries": "Scan Libraries",
"kavita+-data-refresh": "Kavita+ Data Refresh",
"backup": "Backup",
"update-yearly-stats": "Update Yearly Stats"
"update-yearly-stats": "Update Yearly Stats",
"generated-reading-profile-name": "Generated from {0}"
}

View file

@ -261,7 +261,7 @@ public class ScrobblingService : IScrobblingService
var series = await _unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId, SeriesIncludes.Metadata | SeriesIncludes.Library);
if (series == null) throw new KavitaException(await _localizationService.Translate(userId, "series-doesnt-exist"));
_logger.LogInformation("Processing Scrobbling review event for {UserId} on {SeriesName}", userId, series.Name);
_logger.LogInformation("Processing Scrobbling review event for {AppUserId} on {SeriesName}", userId, series.Name);
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
if (IsAniListReviewValid(reviewTitle, reviewBody))
@ -297,7 +297,7 @@ public class ScrobblingService : IScrobblingService
};
_unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync();
_logger.LogDebug("Added Scrobbling Review update on {SeriesName} with Userid {UserId} ", series.Name, userId);
_logger.LogDebug("Added Scrobbling Review update on {SeriesName} with Userid {AppUserId} ", series.Name, userId);
}
private static bool IsAniListReviewValid(string reviewTitle, string reviewBody)
@ -317,7 +317,7 @@ public class ScrobblingService : IScrobblingService
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
_logger.LogInformation("Processing Scrobbling rating event for {UserId} on {SeriesName}", userId, series.Name);
_logger.LogInformation("Processing Scrobbling rating event for {AppUserId} on {SeriesName}", userId, series.Name);
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
@ -346,7 +346,7 @@ public class ScrobblingService : IScrobblingService
};
_unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync();
_logger.LogDebug("Added Scrobbling Rating update on {SeriesName} with Userid {UserId}", series.Name, userId);
_logger.LogDebug("Added Scrobbling Rating update on {SeriesName} with Userid {AppUserId}", series.Name, userId);
}
public static long? GetMalId(Series series)
@ -371,7 +371,7 @@ public class ScrobblingService : IScrobblingService
var user = await _unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
_logger.LogInformation("Processing Scrobbling reading event for {UserId} on {SeriesName}", userId, series.Name);
_logger.LogInformation("Processing Scrobbling reading event for {AppUserId} on {SeriesName}", userId, series.Name);
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
var existingEvt = await _unitOfWork.ScrobbleRepository.GetEvent(userId, series.Id,
@ -418,7 +418,7 @@ public class ScrobblingService : IScrobblingService
_unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync();
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} - Volume: {VolumeNumber} Chapter: {ChapterNumber} for User: {UserId}", series.Name, evt.VolumeNumber, evt.ChapterNumber, userId);
_logger.LogDebug("Added Scrobbling Read update on {SeriesName} - Volume: {VolumeNumber} Chapter: {ChapterNumber} for User: {AppUserId}", series.Name, evt.VolumeNumber, evt.ChapterNumber, userId);
}
catch (Exception ex)
{
@ -437,7 +437,7 @@ public class ScrobblingService : IScrobblingService
if (user == null || !user.UserPreferences.AniListScrobblingEnabled) return;
if (await CheckIfCannotScrobble(userId, seriesId, series)) return;
_logger.LogInformation("Processing Scrobbling want-to-read event for {UserId} on {SeriesName}", userId, series.Name);
_logger.LogInformation("Processing Scrobbling want-to-read event for {AppUserId} on {SeriesName}", userId, series.Name);
// Get existing events for this series/user
var existingEvents = (await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId))
@ -463,7 +463,7 @@ public class ScrobblingService : IScrobblingService
_unitOfWork.ScrobbleRepository.Attach(evt);
await _unitOfWork.CommitAsync();
_logger.LogDebug("Added Scrobbling WantToRead update on {SeriesName} with Userid {UserId} ", series.Name, userId);
_logger.LogDebug("Added Scrobbling WantToRead update on {SeriesName} with Userid {AppUserId} ", series.Name, userId);
}
private async Task<bool> CheckIfCannotScrobble(int userId, int seriesId, Series series)
@ -471,7 +471,7 @@ public class ScrobblingService : IScrobblingService
if (series.DontMatch) return true;
if (await _unitOfWork.UserRepository.HasHoldOnSeries(userId, seriesId))
{
_logger.LogInformation("Series {SeriesName} is on UserId {UserId}'s hold list. Not scrobbling", series.Name,
_logger.LogInformation("Series {SeriesName} is on AppUserId {AppUserId}'s hold list. Not scrobbling", series.Name,
userId);
return true;
}
@ -750,7 +750,7 @@ public class ScrobblingService : IScrobblingService
/// <param name="seriesId"></param>
public async Task ClearEventsForSeries(int userId, int seriesId)
{
_logger.LogInformation("Clearing Pre-existing Scrobble events for Series {SeriesId} by User {UserId} as Series is now on hold list", seriesId, userId);
_logger.LogInformation("Clearing Pre-existing Scrobble events for Series {SeriesId} by User {AppUserId} as Series is now on hold list", seriesId, userId);
var events = await _unitOfWork.ScrobbleRepository.GetUserEventsForSeries(userId, seriesId);
foreach (var scrobble in events)
{
@ -1109,7 +1109,7 @@ public class ScrobblingService : IScrobblingService
{
if (ex.Message.Contains("Access token is invalid"))
{
_logger.LogCritical(ex, "Access Token for UserId: {UserId} needs to be regenerated/renewed to continue scrobbling", evt.AppUser.Id);
_logger.LogCritical(ex, "Access Token for AppUserId: {AppUserId} needs to be regenerated/renewed to continue scrobbling", evt.AppUser.Id);
evt.IsErrored = true;
evt.ErrorDetails = AccessTokenErrorMessage;
_unitOfWork.ScrobbleRepository.Update(evt);

View file

@ -0,0 +1,453 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Data.Repositories;
using API.DTOs;
using API.Entities;
using API.Entities.Enums;
using API.Extensions;
using API.Helpers.Builders;
using AutoMapper;
using Kavita.Common;
namespace API.Services;
#nullable enable
public interface IReadingProfileService
{
/// <summary>
/// Returns the ReadingProfile that should be applied to the given series, walks up the tree.
/// Series (Implicit) -> Series (User) -> Library (User) -> Default
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <param name="skipImplicit"></param>
/// <returns></returns>
Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId, bool skipImplicit = false);
/// <summary>
/// Creates a new reading profile for a user. Name must be unique per user
/// </summary>
/// <param name="userId"></param>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserReadingProfileDto> CreateReadingProfile(int userId, UserReadingProfileDto dto);
Task<UserReadingProfileDto> PromoteImplicitProfile(int userId, int profileId);
/// <summary>
/// Updates the implicit reading profile for a series, creates one if none exists
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserReadingProfileDto> UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto);
/// <summary>
/// Updates the non-implicit reading profile for the given series, and removes implicit profiles
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserReadingProfileDto> UpdateParent(int userId, int seriesId, UserReadingProfileDto dto);
/// <summary>
/// Updates a given reading profile for a user
/// </summary>
/// <param name="userId"></param>
/// <param name="dto"></param>
/// <returns></returns>
/// <remarks>Does not update connected series and libraries</remarks>
Task<UserReadingProfileDto> UpdateReadingProfile(int userId, UserReadingProfileDto dto);
/// <summary>
/// Deletes a given profile for a user
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
/// <exception cref="UnauthorizedAccessException"></exception>
/// <exception cref="KavitaException">The default profile for the user cannot be deleted</exception>
Task DeleteReadingProfile(int userId, int profileId);
/// <summary>
/// Binds the reading profile to the series, and remove the implicit RP from the series if it exists
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <param name="seriesId"></param>
/// <returns></returns>
Task AddProfileToSeries(int userId, int profileId, int seriesId);
/// <summary>
/// Binds the reading profile to many series, and remove the implicit RP from the series if it exists
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <param name="seriesIds"></param>
/// <returns></returns>
Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds);
/// <summary>
/// Remove all reading profiles bound to the series
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <returns></returns>
Task ClearSeriesProfile(int userId, int seriesId);
/// <summary>
/// Bind the reading profile to the library
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <param name="libraryId"></param>
/// <returns></returns>
Task AddProfileToLibrary(int userId, int profileId, int libraryId);
/// <summary>
/// Remove the reading profile bound to the library, if it exists
/// </summary>
/// <param name="userId"></param>
/// <param name="libraryId"></param>
/// <returns></returns>
Task ClearLibraryProfile(int userId, int libraryId);
/// <summary>
/// Returns the bound Reading Profile to a Library
/// </summary>
/// <param name="userId"></param>
/// <param name="libraryId"></param>
/// <returns></returns>
Task<UserReadingProfileDto?> GetReadingProfileDtoForLibrary(int userId, int libraryId);
}
public class ReadingProfileService(IUnitOfWork unitOfWork, ILocalizationService localizationService, IMapper mapper): IReadingProfileService
{
/// <summary>
/// Tries to resolve the Reading Profile for a given Series. Will first check (optionally) Implicit profiles, then check for a bound Series profile, then a bound
/// Library profile, then default to the default profile.
/// </summary>
/// <param name="userId"></param>
/// <param name="seriesId"></param>
/// <param name="skipImplicit"></param>
/// <returns></returns>
/// <exception cref="KavitaException"></exception>
public async Task<AppUserReadingProfile> GetReadingProfileForSeries(int userId, int seriesId, bool skipImplicit = false)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, skipImplicit);
// If there is an implicit, send back
var implicitProfile =
profiles.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind == ReadingProfileKind.Implicit);
if (implicitProfile != null) return implicitProfile;
// Next check for a bound Series profile
var seriesProfile = profiles
.FirstOrDefault(p => p.SeriesIds.Contains(seriesId) && p.Kind != ReadingProfileKind.Implicit);
if (seriesProfile != null) return seriesProfile;
// Check for a library bound profile
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
if (series == null) throw new KavitaException(await localizationService.Translate(userId, "series-doesnt-exist"));
var libraryProfile = profiles
.FirstOrDefault(p => p.LibraryIds.Contains(series.LibraryId) && p.Kind != ReadingProfileKind.Implicit);
if (libraryProfile != null) return libraryProfile;
// Fallback to the default profile
return profiles.First(p => p.Kind == ReadingProfileKind.Default);
}
public async Task<UserReadingProfileDto> GetReadingProfileDtoForSeries(int userId, int seriesId, bool skipImplicit = false)
{
return mapper.Map<UserReadingProfileDto>(await GetReadingProfileForSeries(userId, seriesId, skipImplicit));
}
public async Task<UserReadingProfileDto> UpdateParent(int userId, int seriesId, UserReadingProfileDto dto)
{
var parentProfile = await GetReadingProfileForSeries(userId, seriesId, true);
UpdateReaderProfileFields(parentProfile, dto, false);
unitOfWork.AppUserReadingProfileRepository.Update(parentProfile);
// Remove the implicit profile when we UpdateParent (from reader) as it is implied that we are already bound with a non-implicit profile
await DeleteImplicateReadingProfilesForSeries(userId, [seriesId]);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(parentProfile);
}
public async Task<UserReadingProfileDto> UpdateReadingProfile(int userId, UserReadingProfileDto dto)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, dto.Id);
if (profile == null) throw new KavitaException("profile-does-not-exist");
UpdateReaderProfileFields(profile, dto);
unitOfWork.AppUserReadingProfileRepository.Update(profile);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(profile);
}
public async Task<UserReadingProfileDto> CreateReadingProfile(int userId, UserReadingProfileDto dto)
{
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null) throw new UnauthorizedAccessException();
if (await unitOfWork.AppUserReadingProfileRepository.IsProfileNameInUse(userId, dto.Name)) throw new KavitaException("name-already-in-use");
var newProfile = new AppUserReadingProfileBuilder(user.Id).Build();
UpdateReaderProfileFields(newProfile, dto);
unitOfWork.AppUserReadingProfileRepository.Add(newProfile);
user.ReadingProfiles.Add(newProfile);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(newProfile);
}
/// <summary>
/// Promotes the implicit profile to a user profile. Removes the series from other profiles.
/// </summary>
/// <param name="userId"></param>
/// <param name="profileId"></param>
/// <returns></returns>
public async Task<UserReadingProfileDto> PromoteImplicitProfile(int userId, int profileId)
{
// Get all the user's profiles including the implicit
var allUserProfiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, false);
var profileToPromote = allUserProfiles.First(r => r.Id == profileId);
var seriesId = profileToPromote.SeriesIds[0]; // An Implicit series can only be bound to 1 Series
// Check if there are any reading profiles (Series) already bound to the series
var existingSeriesProfile = allUserProfiles.FirstOrDefault(r => r.SeriesIds.Contains(seriesId) && r.Kind == ReadingProfileKind.User);
if (existingSeriesProfile != null)
{
existingSeriesProfile.SeriesIds.Remove(seriesId);
unitOfWork.AppUserReadingProfileRepository.Update(existingSeriesProfile);
}
// Convert the implicit profile into a proper Series
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId);
if (series == null) throw new KavitaException("series-doesnt-exist"); // Shouldn't happen
profileToPromote.Kind = ReadingProfileKind.User;
profileToPromote.Name = await localizationService.Translate(userId, "generated-reading-profile-name", series.Name);
profileToPromote.Name = EnsureUniqueProfileName(allUserProfiles, profileToPromote.Name);
profileToPromote.NormalizedName = profileToPromote.Name.ToNormalized();
unitOfWork.AppUserReadingProfileRepository.Update(profileToPromote);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(profileToPromote);
}
private static string EnsureUniqueProfileName(IList<AppUserReadingProfile> allUserProfiles, string name)
{
var counter = 1;
var newName = name;
while (allUserProfiles.Any(p => p.Name == newName))
{
newName = $"{name} ({counter})";
counter++;
}
return newName;
}
public async Task<UserReadingProfileDto> UpdateImplicitReadingProfile(int userId, int seriesId, UserReadingProfileDto dto)
{
var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId, AppUserIncludes.UserPreferences);
if (user == null) throw new UnauthorizedAccessException();
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var existingProfile = profiles.FirstOrDefault(rp => rp.Kind == ReadingProfileKind.Implicit && rp.SeriesIds.Contains(seriesId));
// Series already had an implicit profile, update it
if (existingProfile is {Kind: ReadingProfileKind.Implicit})
{
UpdateReaderProfileFields(existingProfile, dto, false);
unitOfWork.AppUserReadingProfileRepository.Update(existingProfile);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(existingProfile);
}
var series = await unitOfWork.SeriesRepository.GetSeriesByIdAsync(seriesId) ?? throw new KeyNotFoundException();
var newProfile = new AppUserReadingProfileBuilder(userId)
.WithSeries(series)
.WithKind(ReadingProfileKind.Implicit)
.Build();
// Set name to something fitting for debugging if needed
UpdateReaderProfileFields(newProfile, dto, false);
newProfile.Name = $"Implicit Profile for {seriesId}";
newProfile.NormalizedName = newProfile.Name.ToNormalized();
user.ReadingProfiles.Add(newProfile);
await unitOfWork.CommitAsync();
return mapper.Map<UserReadingProfileDto>(newProfile);
}
public async Task DeleteReadingProfile(int userId, int profileId)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-doesnt-exist");
if (profile.Kind == ReadingProfileKind.Default) throw new KavitaException("cant-delete-default-profile");
unitOfWork.AppUserReadingProfileRepository.Remove(profile);
await unitOfWork.CommitAsync();
}
public async Task AddProfileToSeries(int userId, int profileId, int seriesId)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-doesnt-exist");
await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
profile.SeriesIds.Add(seriesId);
unitOfWork.AppUserReadingProfileRepository.Update(profile);
await unitOfWork.CommitAsync();
}
public async Task BulkAddProfileToSeries(int userId, int profileId, IList<int> seriesIds)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-doesnt-exist");
await DeleteImplicitAndRemoveFromUserProfiles(userId, seriesIds, []);
profile.SeriesIds.AddRange(seriesIds.Except(profile.SeriesIds));
unitOfWork.AppUserReadingProfileRepository.Update(profile);
await unitOfWork.CommitAsync();
}
public async Task ClearSeriesProfile(int userId, int seriesId)
{
await DeleteImplicitAndRemoveFromUserProfiles(userId, [seriesId], []);
await unitOfWork.CommitAsync();
}
public async Task AddProfileToLibrary(int userId, int profileId, int libraryId)
{
var profile = await unitOfWork.AppUserReadingProfileRepository.GetUserProfile(userId, profileId);
if (profile == null) throw new KavitaException("profile-doesnt-exist");
await DeleteImplicitAndRemoveFromUserProfiles(userId, [], [libraryId]);
profile.LibraryIds.Add(libraryId);
unitOfWork.AppUserReadingProfileRepository.Update(profile);
await unitOfWork.CommitAsync();
}
public async Task ClearLibraryProfile(int userId, int libraryId)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var libraryProfile = profiles.FirstOrDefault(p => p.LibraryIds.Contains(libraryId));
if (libraryProfile != null)
{
libraryProfile.LibraryIds.Remove(libraryId);
unitOfWork.AppUserReadingProfileRepository.Update(libraryProfile);
}
if (unitOfWork.HasChanges())
{
await unitOfWork.CommitAsync();
}
}
public async Task<UserReadingProfileDto?> GetReadingProfileDtoForLibrary(int userId, int libraryId)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId, true);
return mapper.Map<UserReadingProfileDto>(profiles.FirstOrDefault(p => p.LibraryIds.Contains(libraryId)));
}
private async Task DeleteImplicitAndRemoveFromUserProfiles(int userId, IList<int> seriesIds, IList<int> libraryIds)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var implicitProfiles = profiles
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
.Where(rp => rp.Kind == ReadingProfileKind.Implicit)
.ToList();
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
var nonImplicitProfiles = profiles
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any() || rp.LibraryIds.Intersect(libraryIds).Any())
.Where(rp => rp.Kind != ReadingProfileKind.Implicit);
foreach (var profile in nonImplicitProfiles)
{
profile.SeriesIds.RemoveAll(seriesIds.Contains);
profile.LibraryIds.RemoveAll(libraryIds.Contains);
unitOfWork.AppUserReadingProfileRepository.Update(profile);
}
}
private async Task DeleteImplicateReadingProfilesForSeries(int userId, IList<int> seriesIds)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var implicitProfiles = profiles
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
.Where(rp => rp.Kind == ReadingProfileKind.Implicit)
.ToList();
unitOfWork.AppUserReadingProfileRepository.RemoveRange(implicitProfiles);
}
private async Task RemoveSeriesFromUserProfiles(int userId, IList<int> seriesIds)
{
var profiles = await unitOfWork.AppUserReadingProfileRepository.GetProfilesForUser(userId);
var userProfiles = profiles
.Where(rp => rp.SeriesIds.Intersect(seriesIds).Any())
.Where(rp => rp.Kind == ReadingProfileKind.User)
.ToList();
unitOfWork.AppUserReadingProfileRepository.RemoveRange(userProfiles);
}
public static void UpdateReaderProfileFields(AppUserReadingProfile existingProfile, UserReadingProfileDto dto, bool updateName = true)
{
if (updateName && !string.IsNullOrEmpty(dto.Name) && existingProfile.NormalizedName != dto.Name.ToNormalized())
{
existingProfile.Name = dto.Name;
existingProfile.NormalizedName = dto.Name.ToNormalized();
}
// Manga Reader
existingProfile.ReadingDirection = dto.ReadingDirection;
existingProfile.ScalingOption = dto.ScalingOption;
existingProfile.PageSplitOption = dto.PageSplitOption;
existingProfile.ReaderMode = dto.ReaderMode;
existingProfile.AutoCloseMenu = dto.AutoCloseMenu;
existingProfile.ShowScreenHints = dto.ShowScreenHints;
existingProfile.EmulateBook = dto.EmulateBook;
existingProfile.LayoutMode = dto.LayoutMode;
existingProfile.BackgroundColor = string.IsNullOrEmpty(dto.BackgroundColor) ? "#000000" : dto.BackgroundColor;
existingProfile.SwipeToPaginate = dto.SwipeToPaginate;
existingProfile.AllowAutomaticWebtoonReaderDetection = dto.AllowAutomaticWebtoonReaderDetection;
existingProfile.WidthOverride = dto.WidthOverride;
// Book Reader
existingProfile.BookReaderMargin = dto.BookReaderMargin;
existingProfile.BookReaderLineSpacing = dto.BookReaderLineSpacing;
existingProfile.BookReaderFontSize = dto.BookReaderFontSize;
existingProfile.BookReaderFontFamily = dto.BookReaderFontFamily;
existingProfile.BookReaderTapToPaginate = dto.BookReaderTapToPaginate;
existingProfile.BookReaderReadingDirection = dto.BookReaderReadingDirection;
existingProfile.BookReaderWritingStyle = dto.BookReaderWritingStyle;
existingProfile.BookThemeName = dto.BookReaderThemeName;
existingProfile.BookReaderLayoutMode = dto.BookReaderLayoutMode;
existingProfile.BookReaderImmersiveMode = dto.BookReaderImmersiveMode;
// PDF Reading
existingProfile.PdfTheme = dto.PdfTheme;
existingProfile.PdfScrollMode = dto.PdfScrollMode;
existingProfile.PdfSpreadMode = dto.PdfSpreadMode;
}
}

View file

@ -293,6 +293,9 @@ public class Startup
await ManualMigrateScrobbleSpecials.Migrate(dataContext, logger);
await ManualMigrateScrobbleEventGen.Migrate(dataContext, logger);
// v0.8.7
await ManualMigrateReadingProfiles.Migrate(dataContext, logger);
#endregion
// Update the version in the DB after all migrations are run