From 902f5f5d6734bf106c4d21f4fec8650a602eb316 Mon Sep 17 00:00:00 2001 From: brios <127139797+balazs-szucs@users.noreply.github.com> Date: Wed, 15 Apr 2026 21:53:49 +0200 Subject: [PATCH] fix(user-settings): fix settings loading errors (#527) * refactor(user): optimize detail fetching with custom repository implementation * refactor(fonts): fix font loading and improve custom font handling * refactor(user-data): update userSettings to use input() for better reactivity * refactor(fonts): improve font loading logic and improve readi ness state management again * refactor(user-data): simplify user fetching logic and improve batch loading * refactor(custom-fonts): improve font loading logic with run ID for better state management --- .../booklore/repository/UserRepository.java | 53 +------ .../repository/UserRepositoryCustom.java | 19 +++ .../repository/UserRepositoryImpl.java | 85 +++++++++++ .../custom-fonts/custom-fonts.component.ts | 15 +- .../epub-reader-preferences-component.html | 4 +- .../epub-reader-preferences-component.ts | 132 +++++++----------- .../app/shared/service/custom-font.service.ts | 30 +++- 7 files changed, 192 insertions(+), 146 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/repository/UserRepositoryCustom.java create mode 100644 booklore-api/src/main/java/org/booklore/repository/UserRepositoryImpl.java diff --git a/booklore-api/src/main/java/org/booklore/repository/UserRepository.java b/booklore-api/src/main/java/org/booklore/repository/UserRepository.java index e15226fe2..e5c9b9481 100644 --- a/booklore-api/src/main/java/org/booklore/repository/UserRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/UserRepository.java @@ -2,69 +2,18 @@ package org.booklore.repository; import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.enums.ProvisioningMethod; -import org.jspecify.annotations.NonNull; -import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; -import java.util.List; import java.util.Optional; @Repository -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository, UserRepositoryCustom { Optional findByUsername(String username); Optional findByEmail(String email); - Optional findById(@NonNull Long id); - - /** - * Fetch a user with all eagerly-needed associations (settings, libraries, permissions) - * in a single query to prevent N+1 problems after OSIV is disabled. - */ - @EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"}) - @Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id") - Optional findByIdWithDetails(@Param("id") Long id); - - /** - * Fetch a user with settings and permissions (without libraries) for settings-related operations. - */ - @EntityGraph(attributePaths = {"settings", "permissions"}) - @Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id") - Optional findByIdWithSettings(@Param("id") Long id); - - /** - * Fetch a user with libraries and permissions for authorization/library-access operations. - */ - @EntityGraph(attributePaths = {"libraries", "libraries.libraryPaths", "permissions"}) - @Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id") - Optional findByIdWithLibraries(@Param("id") Long id); - - /** - * Fetch a user with just permissions for security checks or simple profile updates. - */ - @EntityGraph(attributePaths = {"permissions"}) - @Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id") - Optional findByIdWithPermissions(@Param("id") Long id); - - /** - * Fetch all users with their settings, libraries, and permissions in a single query. - * Prevents N+1 when listing all users (admin panel). - */ - @EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"}) - @Query("SELECT DISTINCT u FROM BookLoreUserEntity u") - List findAllWithDetails(); - - /** - * Fetch a user by username with all associations needed for authentication/DTO mapping. - */ - @EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"}) - @Query("SELECT u FROM BookLoreUserEntity u WHERE u.username = :username") - Optional findByUsernameWithDetails(@Param("username") String username); - long countByProvisioningMethod(ProvisioningMethod provisioningMethod); Optional findByOidcIssuerAndOidcSubject(String oidcIssuer, String oidcSubject); diff --git a/booklore-api/src/main/java/org/booklore/repository/UserRepositoryCustom.java b/booklore-api/src/main/java/org/booklore/repository/UserRepositoryCustom.java new file mode 100644 index 000000000..16e94aaa7 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/repository/UserRepositoryCustom.java @@ -0,0 +1,19 @@ +package org.booklore.repository; + +import org.booklore.model.entity.BookLoreUserEntity; + +import java.util.List; +import java.util.Optional; + +public interface UserRepositoryCustom { + + Optional findByIdWithDetails(Long id); + + List findAllWithDetails(); + + Optional findByIdWithSettings(Long id); + + Optional findByIdWithLibraries(Long id); + + Optional findByIdWithPermissions(Long id); +} diff --git a/booklore-api/src/main/java/org/booklore/repository/UserRepositoryImpl.java b/booklore-api/src/main/java/org/booklore/repository/UserRepositoryImpl.java new file mode 100644 index 000000000..9226ce4bf --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/repository/UserRepositoryImpl.java @@ -0,0 +1,85 @@ +package org.booklore.repository; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import org.booklore.model.entity.BookLoreUserEntity; +import org.hibernate.Hibernate; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; + +public class UserRepositoryImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager em; + + @Override + @Transactional(readOnly = true) + public Optional findByIdWithDetails(Long id) { + List users = em.createQuery( + "SELECT DISTINCT u FROM BookLoreUserEntity u " + + "LEFT JOIN FETCH u.settings " + + "LEFT JOIN FETCH u.permissions " + + "WHERE u.id = :id", + BookLoreUserEntity.class) + .setParameter("id", id) + .getResultList(); + if (users.isEmpty()) return Optional.empty(); + + BookLoreUserEntity user = users.getFirst(); + Hibernate.initialize(user.getLibraries()); + user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths())); + + return Optional.of(user); + } + + @Override + @Transactional(readOnly = true) + public List findAllWithDetails() { + List users = em.createQuery( + "SELECT DISTINCT u FROM BookLoreUserEntity u " + + "LEFT JOIN FETCH u.settings " + + "LEFT JOIN FETCH u.permissions", + BookLoreUserEntity.class) + .getResultList(); + if (users.isEmpty()) return users; + + users.forEach(user -> { + Hibernate.initialize(user.getLibraries()); + user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths())); + }); + + return users; + } + + @Override + @Transactional(readOnly = true) + public Optional findByIdWithSettings(Long id) { + BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id); + if (user == null) return Optional.empty(); + Hibernate.initialize(user.getSettings()); + Hibernate.initialize(user.getPermissions()); + return Optional.of(user); + } + + @Override + @Transactional(readOnly = true) + public Optional findByIdWithLibraries(Long id) { + BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id); + if (user == null) return Optional.empty(); + Hibernate.initialize(user.getLibraries()); + user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths())); + Hibernate.initialize(user.getPermissions()); + return Optional.of(user); + } + + @Override + @Transactional(readOnly = true) + public Optional findByIdWithPermissions(Long id) { + BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id); + if (user == null) return Optional.empty(); + Hibernate.initialize(user.getPermissions()); + return Optional.of(user); + } +} diff --git a/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.ts b/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.ts index 7ffc8c3dd..0722f414e 100644 --- a/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.ts +++ b/frontend/src/app/features/settings/custom-fonts/custom-fonts.component.ts @@ -24,8 +24,6 @@ import {DatePipe} from '@angular/common'; providers: [ConfirmationService, DialogService] }) export class CustomFontsComponent implements OnInit { - customFonts: CustomFont[] = []; - isLoading = true; fontsLoadedInBrowser = false; uploadDialogRef: DynamicDialogRef | null = null; @@ -38,6 +36,9 @@ export class CustomFontsComponent implements OnInit { private t = inject(TranslocoService); private destroyRef = inject(DestroyRef); + get customFonts(): CustomFont[] { return this.customFontService.fonts(); } + get isLoading(): boolean { return this.customFontService.isFontsLoading(); } + ngOnInit(): void { this.loadFonts(); } @@ -48,9 +49,6 @@ export class CustomFontsComponent implements OnInit { try { const fonts = await this.customFontService.ensureFonts(); - this.customFonts = fonts; - this.isLoading = false; - await this.customFontService.loadAllFonts(fonts); this.fontsLoadedInBrowser = true; @@ -61,7 +59,6 @@ export class CustomFontsComponent implements OnInit { summary: this.t.translate('common.error'), detail: this.t.translate('settingsReader.fonts.loadError') }); - this.isLoading = false; this.fontsLoadedInBrowser = true; } } @@ -87,10 +84,7 @@ export class CustomFontsComponent implements OnInit { if (this.uploadDialogRef) { this.uploadDialogRef.onClose.pipe( takeUntilDestroyed(this.destroyRef) - ).subscribe((font: CustomFont | null) => { - if (font) { - this.customFonts.push(font); - } + ).subscribe(() => { this.uploadDialogRef = null; }); } @@ -106,7 +100,6 @@ export class CustomFontsComponent implements OnInit { takeUntilDestroyed(this.destroyRef) ).subscribe({ next: () => { - this.customFonts = this.customFonts.filter(f => f.id !== font.id); this.messageService.add({ severity: 'success', summary: this.t.translate('common.success'), diff --git a/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html index b9600ee16..fe83554cb 100644 --- a/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html +++ b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html @@ -72,7 +72,7 @@
{{ t('fontFamily') }}
- @for (font of fonts; track font) { + @for (font of fonts(); track font.key) {
diff --git a/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index f1130d63c..ae54998a0 100644 --- a/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/frontend/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -1,5 +1,5 @@ import {DecimalPipe} from '@angular/common'; -import {Component, effect, inject, Input} from '@angular/core'; +import {Component, computed, effect, untracked, inject, input} from '@angular/core'; import {Button} from 'primeng/button'; import {FormsModule} from '@angular/forms'; import {TranslocoDirective} from '@jsverse/transloco'; @@ -7,8 +7,7 @@ import {ReaderPreferencesService} from '../reader-preferences.service'; import {UserSettings} from '../../user-management/user.service'; import {Tooltip} from 'primeng/tooltip'; import {CustomFontService} from '../../../../shared/service/custom-font.service'; -import {CustomFont} from '../../../../shared/model/custom-font.model'; -import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util'; +import {addCustomFontsToDropdown, FontPreferenceItem} from '../../../../shared/util/custom-font.util'; import {Skeleton} from 'primeng/skeleton'; import {themes} from '../../../readers/ebook-reader/state/themes.constant'; @@ -27,14 +26,12 @@ import {themes} from '../../../readers/ebook-reader/state/themes.constant'; }) export class EpubReaderPreferencesComponent { - @Input() userSettings!: UserSettings; + userSettings = input.required(); private readonly readerPreferencesService = inject(ReaderPreferencesService); private readonly customFontService = inject(CustomFontService); - customFonts: CustomFont[] = []; - - fonts = [ + private static readonly baseFonts: FontPreferenceItem[] = [ {name: 'Book Default', displayName: 'Default', key: null}, {name: 'Serif', displayName: 'Serif', key: 'serif'}, {name: 'Sans Serif', displayName: 'Sans Serif', key: 'sans-serif'}, @@ -45,58 +42,35 @@ export class EpubReaderPreferencesComponent { readonly themes = themes; - customFontsReady = false; - - private readonly syncFontsEffect = effect(() => { - const fonts = this.customFontService.fonts(); - if (fonts.length > 0 || !this.customFontService.isFontsLoading()) { - this.customFontsReady = true; - } - if (this.hasCustomFontsChanged(fonts)) { - this.onFontsChanged(fonts); - } + readonly customFontsReady = computed(() => { + return this.customFontService.isFontsReady() || !this.customFontService.isFontsLoading(); }); - private async onFontsChanged(fonts: CustomFont[]): Promise { - try { - const selectedFontDeleted = this.isCurrentlySelectedFontDeleted(fonts); + readonly fonts = computed(() => { + const base: FontPreferenceItem[] = [...EpubReaderPreferencesComponent.baseFonts]; + addCustomFontsToDropdown(this.customFontService.fonts(), base, 'preference'); + return base; + }); - this.customFonts = fonts; - await this.customFontService.loadAllFonts(fonts); - this.updateFontsDropdown(fonts); + private readonly loadFontsEffect = effect(() => { + const fonts = this.customFontService.fonts(); + if (fonts.length === 0 && this.customFontService.isFontsLoading()) return; - if (selectedFontDeleted) { - this.resetToDefaultFont(); + untracked(() => { + this.customFontService.loadAllFonts(fonts).catch(err => { + console.error('Failed to load custom fonts:', err); + }); + }); + + const fontFamily = this.userSettings()?.ebookReaderSetting?.fontFamily; + if (fontFamily && fontFamily.startsWith('custom:')) { + const fontId = parseInt(fontFamily.split(':')[1], 10); + const fontStillExists = fonts.some(font => font.id === fontId); + if (!fontStillExists) { + queueMicrotask(() => this.resetToDefaultFont()); } - } catch (err) { - console.error('Failed to process custom fonts:', err); } - } - - private hasCustomFontsChanged(newFonts: CustomFont[]): boolean { - if (newFonts.length !== this.customFonts.length) { - return true; - } - const newIds = new Set(newFonts.map(f => f.id)); - const currentIds = new Set(this.customFonts.map(f => f.id)); - return newFonts.some(f => !currentIds.has(f.id)) || this.customFonts.some(f => !newIds.has(f.id)); - } - - private updateFontsDropdown(fonts: CustomFont[]): void { - this.fonts = this.fonts.filter(font => !font.key || !font.key.startsWith('custom:')); - addCustomFontsToDropdown(fonts, this.fonts, 'preference'); - } - - private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean { - const fontFamily = this.userSettings.ebookReaderSetting.fontFamily; - if (!fontFamily || !fontFamily.startsWith('custom:')) { - return false; - } - - const fontId = fontFamily.split(':')[1]; - const fontStillExists = newFonts.some(font => font.id === parseInt(fontId, 10)); - return !fontStillExists; - } + }); private resetToDefaultFont(): void { console.log('Selected custom font was deleted, resetting to default font'); @@ -104,116 +78,116 @@ export class EpubReaderPreferencesComponent { } get selectedTheme(): string | null { - return this.userSettings.ebookReaderSetting.theme; + return this.userSettings().ebookReaderSetting.theme; } set selectedTheme(value: string | null) { if (typeof value === "string") { - this.userSettings.ebookReaderSetting.theme = value; + this.userSettings().ebookReaderSetting.theme = value; } this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'theme'], value); } get selectedFont(): string | null { - return this.userSettings.ebookReaderSetting.fontFamily || null; + return this.userSettings().ebookReaderSetting.fontFamily || null; } set selectedFont(value: string | null) { if (typeof value === "string") { - this.userSettings.ebookReaderSetting.fontFamily = value; + this.userSettings().ebookReaderSetting.fontFamily = value; } else { - this.userSettings.ebookReaderSetting.fontFamily = ''; + this.userSettings().ebookReaderSetting.fontFamily = ''; } this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontFamily'], value); } get fontSize(): number { - return this.userSettings.ebookReaderSetting.fontSize; + return this.userSettings().ebookReaderSetting.fontSize; } set fontSize(value: number) { - this.userSettings.ebookReaderSetting.fontSize = value; + this.userSettings().ebookReaderSetting.fontSize = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontSize'], value); } get lineHeight(): number { - return this.userSettings.ebookReaderSetting.lineHeight; + return this.userSettings().ebookReaderSetting.lineHeight; } set lineHeight(value: number) { - this.userSettings.ebookReaderSetting.lineHeight = value; + this.userSettings().ebookReaderSetting.lineHeight = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'lineHeight'], value); } get justify(): boolean { - return this.userSettings.ebookReaderSetting.justify; + return this.userSettings().ebookReaderSetting.justify; } set justify(value: boolean) { - this.userSettings.ebookReaderSetting.justify = value; + this.userSettings().ebookReaderSetting.justify = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'justify'], value); } get hyphenate(): boolean { - return this.userSettings.ebookReaderSetting.hyphenate; + return this.userSettings().ebookReaderSetting.hyphenate; } set hyphenate(value: boolean) { - this.userSettings.ebookReaderSetting.hyphenate = value; + this.userSettings().ebookReaderSetting.hyphenate = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'hyphenate'], value); } get maxColumnCount(): number { - return this.userSettings.ebookReaderSetting.maxColumnCount; + return this.userSettings().ebookReaderSetting.maxColumnCount; } set maxColumnCount(value: number) { - this.userSettings.ebookReaderSetting.maxColumnCount = value; + this.userSettings().ebookReaderSetting.maxColumnCount = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxColumnCount'], value); } get gap(): number { - return this.userSettings.ebookReaderSetting.gap; + return this.userSettings().ebookReaderSetting.gap; } set gap(value: number) { - this.userSettings.ebookReaderSetting.gap = value; + this.userSettings().ebookReaderSetting.gap = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'gap'], value); } get maxInlineSize(): number { - return this.userSettings.ebookReaderSetting.maxInlineSize; + return this.userSettings().ebookReaderSetting.maxInlineSize; } set maxInlineSize(value: number) { - this.userSettings.ebookReaderSetting.maxInlineSize = value; + this.userSettings().ebookReaderSetting.maxInlineSize = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxInlineSize'], value); } get maxBlockSize(): number { - return this.userSettings.ebookReaderSetting.maxBlockSize; + return this.userSettings().ebookReaderSetting.maxBlockSize; } set maxBlockSize(value: number) { - this.userSettings.ebookReaderSetting.maxBlockSize = value; + this.userSettings().ebookReaderSetting.maxBlockSize = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxBlockSize'], value); } get isDark(): boolean { - return this.userSettings.ebookReaderSetting.isDark; + return this.userSettings().ebookReaderSetting.isDark; } set isDark(value: boolean) { - this.userSettings.ebookReaderSetting.isDark = value; + this.userSettings().ebookReaderSetting.isDark = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'isDark'], value); } get flow(): 'paginated' | 'scrolled' { - return this.userSettings.ebookReaderSetting.flow; + return this.userSettings().ebookReaderSetting.flow; } set flow(value: 'paginated' | 'scrolled') { - this.userSettings.ebookReaderSetting.flow = value; + this.userSettings().ebookReaderSetting.flow = value; this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'flow'], value); } @@ -283,7 +257,7 @@ export class EpubReaderPreferencesComponent { return null; } const fontId = parseInt(fontKey.split(':')[1]); - const customFont = this.customFonts.find(f => f.id === fontId); + const customFont = this.customFontService.fonts().find(f => f.id === fontId); return customFont ? customFont.fontName : null; } } diff --git a/frontend/src/app/shared/service/custom-font.service.ts b/frontend/src/app/shared/service/custom-font.service.ts index c19d5980c..1f6cd3209 100644 --- a/frontend/src/app/shared/service/custom-font.service.ts +++ b/frontend/src/app/shared/service/custom-font.service.ts @@ -1,4 +1,4 @@ -import {computed, effect, inject, Injectable} from '@angular/core'; +import {computed, signal, effect, inject, Injectable} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {lastValueFrom, Observable, tap} from 'rxjs'; import {CustomFont} from '../model/custom-font.model'; @@ -13,6 +13,7 @@ const CUSTOM_FONTS_QUERY_KEY = ['customFonts'] as const; }) export class CustomFontService { private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`; + private loadAllFontsRunId = 0; private loadedFonts = new Set(); private http = inject(HttpClient); private authService = inject(AuthService); @@ -27,11 +28,15 @@ export class CustomFontService { fonts = computed(() => this.fontsQuery.data() ?? []); isFontsLoading = computed(() => !!this.token() && this.fontsQuery.isPending()); + private readonly isFontsReadyInternal = signal(false); + isFontsReady = this.isFontsReadyInternal.asReadonly(); + constructor() { effect(() => { const token = this.token(); if (token === null) { this.queryClient.removeQueries({queryKey: CUSTOM_FONTS_QUERY_KEY}); + this.isFontsReadyInternal.set(false); } }); } @@ -125,8 +130,29 @@ export class CustomFontService { } async loadAllFonts(fonts: CustomFont[]): Promise { + const runId = ++this.loadAllFontsRunId; + this.isFontsReadyInternal.set(false); + + if (fonts.length === 0) { + if (runId === this.loadAllFontsRunId) { + this.isFontsReadyInternal.set(true); + } + return; + } + const loadPromises = fonts.map(font => this.loadFontFace(font)); - await Promise.allSettled(loadPromises); + const results = await Promise.allSettled(loadPromises); + + if (runId !== this.loadAllFontsRunId) { + return; + } + + const hasFailures = results.some(r => r.status === 'rejected'); + if (hasFailures) { + const failures = results.filter(r => r.status === 'rejected'); + console.error(`Failed to load ${failures.length} fonts out of ${fonts.length}`); + } + this.isFontsReadyInternal.set(true); } isFontLoaded(fontName: string): boolean {