feat: Add custom font support for EPUB reader (#2120)

* feat: Add custom font support for EPUB reader

This commit introduces the ability to manage and use custom fonts in the EPUB reader. Key changes include:

**Backend:**
- Added `CustomFontService` for handling custom font operations.
- Introduced `CustomFontController` for API endpoints.
- Created `CustomFontEntity` and `CustomFontRepository` for database interactions.
- Added `CustomFontMapper` and `CustomFontDto` for data transformation.
- Updated `SecurityConfig` to include JWT filter for custom fonts.
- Enhanced `GlobalExceptionHandler` to handle custom font-related exceptions.
- Added database migrations:
  - `V83__Create_Custom_Font_Table.sql` for creating the custom font table.
  - `V84__Add_Custom_Font_To_Epub_Preferences.sql` for integrating custom fonts with EPUB preferences.

**Frontend:**
- Added `CustomFontsComponent` and `FontUploadDialogComponent` for managing custom fonts in the settings UI.
- Updated `EpubReaderPreferencesComponent` to include custom font options.
- Introduced `CustomFontService` and `CustomFontModel` for frontend logic and data handling.
- Enhanced `SettingsComponent` to integrate custom font management.

**Other Changes:**
- Updated `EpubViewerPreferences` and `EpubViewerPreferencesEntity` to support custom fonts.
- Modified existing components and services to accommodate the new feature.

This feature enhances the user experience by allowing personalized font choices for EPUB reading.

* fix: custom font does not apply after page layout changed

* fix: duplicate API call when change EPUB global settings

* fix: some code review items, extract shared filter logic and improve UX

- Extract AbstractQueryParameterJwtFilter base class to reduce code duplication
  between CoverJwtFilter and CustomFontJwtFilter
- Remove cssIdentifier and fontUrl fields from CustomFont model (no longer needed)
- Add font name sanitization to prevent XSS and ensure data integrity
- Improve error handling in CustomFontService with proper APIException usage
- Replace RuntimeException handler with specific IllegalStateException and
  UnsupportedOperationException handlers in GlobalExceptionHandler
- Add skeleton loading states for font previews and font dropdowns
- Improve font loading state management in epub-reader component
- Create shared custom-font.util.ts for dropdown population logic
- Use reactive font$ subscription for real-time font updates in preferences
- Make DB migrations idempotent with IF NOT EXISTS clauses
- Optimize font file validation to read only header bytes instead of entire file

* chore: re-version migration scripts

* Fix: Kobo sync missing book covers (v1.16.4) (#2147)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Fix: correctly update book cover hash on metadata refresh (#2149)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Introduce Vitest as the frontend Angular testing framework for Booklore (#2150)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Add Vitest frontend tests to CI with JUnit reporting and coverage (#2151)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Update PR template to capture frontend test details

* Add instructions for running Angular frontend tests

---------

Co-authored-by: ACX <8075870+acx10@users.noreply.github.com>
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
Darkraise
2026-01-05 14:45:29 -07:00
committed by GitHub
co-authored by acx10 ACX
parent 9861e23333
commit 926b87872e
35 changed files with 3192 additions and 94 deletions
@@ -0,0 +1,23 @@
export interface CustomFont {
id: number;
fontName: string;
originalFileName: string;
format: FontFormat;
fileSize: number;
uploadedAt: string;
}
export enum FontFormat {
TTF = 'TTF',
OTF = 'OTF',
WOFF = 'WOFF',
WOFF2 = 'WOFF2'
}
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
@@ -0,0 +1,122 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs';
import {CustomFont} from '../model/custom-font.model';
import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class CustomFontService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`;
private fontsSubject = new BehaviorSubject<CustomFont[]>([]);
public fonts$ = this.fontsSubject.asObservable();
private loadedFonts = new Set<string>();
private authService = inject(AuthService);
constructor(private http: HttpClient) {}
uploadFont(file: File, fontName?: string): Observable<CustomFont> {
const formData = new FormData();
formData.append('file', file);
if (fontName) {
formData.append('fontName', fontName);
}
return this.http.post<CustomFont>(`${this.apiUrl}/upload`, formData).pipe(
tap(font => {
// Add to cache
const currentFonts = this.fontsSubject.value;
this.fontsSubject.next([...currentFonts, font]);
// Load the font immediately
this.loadFontFace(font).catch(err => {
console.error('Failed to load font after upload:', err);
});
})
);
}
getUserFonts(): Observable<CustomFont[]> {
return this.http.get<CustomFont[]>(this.apiUrl).pipe(
tap(fonts => {
this.fontsSubject.next(fonts);
})
);
}
deleteFont(fontId: number): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${fontId}`).pipe(
tap(() => {
// Remove from cache
const currentFonts = this.fontsSubject.value;
const updatedFonts = currentFonts.filter(f => f.id !== fontId);
this.fontsSubject.next(updatedFonts);
// Remove from loaded fonts set and document.fonts
const deletedFont = currentFonts.find(f => f.id === fontId);
if (deletedFont) {
this.removeFontFace(deletedFont.fontName);
this.loadedFonts.delete(deletedFont.fontName);
}
})
);
}
getFontUrl(fontId: number): string {
return `${this.apiUrl}/${fontId}/file`;
}
private getToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
public appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
async loadFontFace(font: CustomFont): Promise<void> {
if (this.loadedFonts.has(font.fontName)) {
return;
}
try {
const absoluteFontUrl = this.getFontUrl(font.id);
const fontUrlWithToken = this.appendToken(absoluteFontUrl);
const fontFace = new FontFace(
font.fontName,
`url(${fontUrlWithToken})`,
{
weight: 'normal',
style: 'normal'
}
);
await fontFace.load();
document.fonts.add(fontFace);
this.loadedFonts.add(font.fontName);
} catch (error) {
console.error(`Failed to load font ${font.fontName}:`, error);
throw error;
}
}
async loadAllFonts(fonts: CustomFont[]): Promise<void> {
const loadPromises = fonts.map(font => this.loadFontFace(font));
await Promise.allSettled(loadPromises);
}
isFontLoaded(fontName: string): boolean {
return this.loadedFonts.has(fontName);
}
private removeFontFace(fontName: string): void {
for (const font of document.fonts) {
if (font.family === fontName) {
document.fonts.delete(font);
}
}
}
}
@@ -0,0 +1,74 @@
import { CustomFont } from '../model/custom-font.model';
/**
* Font dropdown item for epub-reader component (PrimeNG Select format)
*/
export interface FontDropdownItem {
label: string;
value: string | null;
disabled?: boolean;
}
/**
* Font dropdown item for epub-reader-preferences component
*/
export interface FontPreferenceItem {
name: string;
displayName: string;
key: string | null;
}
const MAX_FONT_DISPLAY_LENGTH = 12;
/**
* Adds custom fonts to a dropdown array with a separator.
* Removes any existing separator before adding to prevent duplicates.
*/
export function addCustomFontsToDropdown<T extends FontDropdownItem | FontPreferenceItem>(
fonts: CustomFont[],
targetArray: T[],
format: 'select' | 'preference'
): void {
if (fonts.length === 0) {
return;
}
if (format === 'select') {
const separatorIndex = (targetArray as FontDropdownItem[]).findIndex(item => item.value === 'separator');
if (separatorIndex !== -1) {
targetArray.splice(separatorIndex, 1);
}
(targetArray as FontDropdownItem[]).push({
label: '--- Custom Fonts ---',
value: 'separator',
disabled: true
});
fonts.forEach(font => {
(targetArray as FontDropdownItem[]).push({
label: font.fontName,
value: `custom:${font.id}`
});
});
} else {
const separatorIndex = (targetArray as FontPreferenceItem[]).findIndex(item => item.key === 'separator');
if (separatorIndex !== -1) {
targetArray.splice(separatorIndex, 1);
}
(targetArray as FontPreferenceItem[]).push({
name: '--- Custom Fonts ---',
displayName: '---',
key: 'separator'
});
fonts.forEach(font => {
(targetArray as FontPreferenceItem[]).push({
name: font.fontName,
displayName: font.fontName.substring(0, MAX_FONT_DISPLAY_LENGTH),
key: `custom:${font.id}`
});
});
}
}