refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components (#2050)

* refactor(types): replace most usages of 'any' with 'unknown' and improve type safety across services and components

- Update method signatures, variables, and interfaces to use 'unknown' instead of 'any'
- Refine event and observable typings for better type inference
- Add or adjust explicit types for function parameters and return values
- Update Chart.js tooltip and context typings for chart services
- Improve type safety in Book, BookState, and related models
- Adjust template bindings and method calls to match stricter typings
- Add SecureSrcDirective for secure image loading with fallback and error handling

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* chore(angular): remove proxy configuration from development build settings

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(book-browser): streamline entity and book state management with reactive streams

- Refactor entity type and entity fetching logic to use observables and combine route params
- Simplify book state handling by consolidating filtering and fetching into a single reactive pipeline
- Remove redundant applySortOption logic and related subscriptions
- Fix book card index binding in template for improved rendering performance
- Ensure proper cleanup of epub rendition in epub-reader component

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(book-browser, book-uploader): improve permission checks and enhance file upload handling

- Use optional chaining for user permission checks in book-browser.component.html to prevent runtime errors when user data is undefined
- Refactor book-uploader.component.ts to pass destination and IDs explicitly to uploadBatch, reconstruct files for strict type handling, and ensure proper upload flow and UI feedback

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(charts, services): improve type safety for book state validation and update form field checks

- Refactor isValidBookState methods across chart components and services to use type predicates and stricter type checks for BookState
- Update metadata-picker.component to simplify array field checks for authors, categories, moods, and tags
- Adjust magic-shelf-utils to remove unnecessary fallback in object spread
- Update notification-event.service to use correct timeout type for highlightTimeout

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* fix(theme): ensure safe merging of theme properties and improve type definition for themesMap

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

* refactor(epub-reader): streamline book and rendition initialization logic

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
Balázs Szücs
2026-01-02 18:22:54 -07:00
committed by GitHub
parent 998b07d243
commit ab96eee5bc
86 changed files with 853 additions and 638 deletions
@@ -144,13 +144,20 @@ export class BookUploaderComponent implements OnInit {
if (filesToUpload.length === 0) return;
this.isUploading = true;
this.uploadBatch(filesToUpload, 0, 5);
const destination = this.value;
const libraryId = this.selectedLibrary?.id?.toString();
const pathId = this.selectedPath?.id?.toString();
this.uploadBatch(filesToUpload, 0, 1, destination, libraryId, pathId);
}
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number): void {
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number, destination: string, libraryId?: string, pathId?: string): void {
const batch = files.slice(startIndex, startIndex + batchSize);
if (batch.length === 0) {
this.isUploading = false;
if (destination === 'bookdrop') {
this.ref.close('uploaded_to_bookdrop');
}
return;
}
@@ -160,14 +167,16 @@ export class BookUploaderComponent implements OnInit {
uploadFile.status = 'Uploading';
const formData = new FormData();
formData.append('file', uploadFile.file);
// Reconstruct the file to ensure strict type and name handling
const cleanFile = new File([uploadFile.file], uploadFile.file.name, {type: uploadFile.file.type});
formData.append('file', cleanFile, uploadFile.file.name);
let uploadUrl: string;
if (this.value === 'library') {
const libraryId = this.selectedLibrary!.id!.toString();
const pathId = this.selectedPath!.id!.toString();
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
if (destination === 'library') {
if (libraryId && pathId) {
formData.append('libraryId', libraryId);
formData.append('pathId', pathId);
}
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
} else {
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload/bookdrop`;
@@ -177,7 +186,9 @@ export class BookUploaderComponent implements OnInit {
next: () => {
uploadFile.status = 'Uploaded';
if (--pending === 0) {
this.uploadBatch(files, startIndex + batchSize, batchSize);
setTimeout(() => {
this.uploadBatch(files, startIndex + batchSize, batchSize, destination, libraryId, pathId);
}, 1000);
}
},
error: (err) => {
@@ -185,7 +196,9 @@ export class BookUploaderComponent implements OnInit {
uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.';
console.error('Upload failed for', uploadFile.file.name, err);
if (--pending === 0) {
this.uploadBatch(files, startIndex + batchSize, batchSize);
setTimeout(() => {
this.uploadBatch(files, startIndex + batchSize, batchSize, destination, libraryId, pathId);
}, 1000);
}
}
});
@@ -32,7 +32,7 @@ import {Tooltip} from 'primeng/tooltip';
styleUrls: ['./directory-picker.component.scss']
})
export class DirectoryPickerComponent implements OnInit {
value: any;
value: unknown;
paths: string[] = [];
filteredPaths: string[] = [];
selectedProductName: string = '';
@@ -103,7 +103,7 @@ export class FileMoverComponent implements OnDestroy {
const libraryId =
book.libraryId ??
book.libraryPath?.id ??
(book as any).library?.id ??
(book as { library?: { id: number } }).library?.id ??
null;
if (!booksByLibrary.has(libraryId)) {
booksByLibrary.set(libraryId, []);
@@ -157,7 +157,7 @@ export class FileMoverComponent implements OnDestroy {
const relativeOriginalPath = `${fileSubPath}${fileName}`;
const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as any).library?.id ?? null;
const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as { library?: { id: number } }).library?.id ?? null;
const currentLibraryName = this.getLibraryNameById(currentLibraryId);
const currentLibraryPath = this.getLibraryPathById(currentLibraryId);
@@ -33,7 +33,7 @@ export class MetadataProgressWidgetComponent implements OnInit, OnDestroy {
private messageService = inject(MessageService);
private lastUpdateMap = new Map<string, number>();
private timeoutHandles = new Map<string, any>();
private timeoutHandles = new Map<string, number>();
private readonly TASK_STALL_TIMEOUT_MS = 60 * 1000; // 1 minute
ngOnInit(): void {
@@ -67,7 +67,7 @@ export class MetadataProgressWidgetComponent implements OnInit, OnDestroy {
taskId,
setTimeout(() => {
this.markTaskStalled(taskId);
}, this.TASK_STALL_TIMEOUT_MS)
}, this.TASK_STALL_TIMEOUT_MS) as any
);
}
}
@@ -20,7 +20,7 @@ export class SetupGuard implements CanActivate {
private router = inject(Router);
canActivate(): Observable<boolean | UrlTree> {
return this.http.get<any>(`${this.url}/status`).pipe(
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(response => {
if (response?.data === true) {
return this.router.createUrlTree(['/login']);
@@ -22,9 +22,9 @@ export class AppLayoutComponent implements OnDestroy {
overlayMenuOpenSubscription: Subscription;
menuOutsideClickListener: any;
menuOutsideClickListener: (() => void) | null = null;
profileMenuOutsideClickListener: any;
profileMenuOutsideClickListener: (() => void) | null = null;
@ViewChild(AppSidebarComponent) appSidebar!: AppSidebarComponent;
@@ -44,7 +44,7 @@ export class LayoutService {
};
private configUpdate = new Subject<AppConfig>();
private overlayOpen = new Subject<any>();
private overlayOpen = new Subject<unknown>();
overlayOpen$ = this.overlayOpen.asObservable();
constructor() {
@@ -12,6 +12,7 @@ import {AppVersion, VersionService} from '../../../service/version.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {MagicShelfService, MagicShelfState} from '../../../../features/magic-shelf/service/magic-shelf.service';
import {MenuItem} from 'primeng/api';
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
@Component({
@@ -21,10 +22,10 @@ import {DialogLauncherService} from '../../../services/dialog-launcher.service';
templateUrl: './app.menu.component.html',
})
export class AppMenuComponent implements OnInit {
libraryMenu$: Observable<any> | undefined;
shelfMenu$: Observable<any> | undefined;
homeMenu$: Observable<any> | undefined;
magicShelfMenu$: Observable<any> | undefined;
libraryMenu$: Observable<MenuItem[]> | undefined;
shelfMenu$: Observable<MenuItem[]> | undefined;
homeMenu$: Observable<MenuItem[]> | undefined;
magicShelfMenu$: Observable<MenuItem[]> | undefined;
versionInfo: AppVersion | null = null;
dynamicDialogRef: DynamicDialogRef | undefined | null;
@@ -216,8 +217,8 @@ export class AppMenuComponent implements OnInit {
private sortArray<T>(array: T[], field: 'name' | 'id', order: 'asc' | 'desc'): T[] {
return [...array].sort((a, b) => {
const aVal = (a as any)[field] ?? '';
const bVal = (b as any)[field] ?? '';
const aVal = (a as Record<string, unknown>)[field] ?? '';
const bVal = (b as Record<string, unknown>)[field] ?? '';
let comparison = 0;
if (typeof aVal === 'string' && typeof bVal === 'string') {
@@ -12,6 +12,7 @@ import {UserService} from '../../../../features/settings/user-management/user.se
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {BookDialogHelperService} from '../../../../features/book/components/book-browser/BookDialogHelperService';
import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component';
import {MenuItem} from 'primeng/api';
import {IconSelection} from '../../../service/icon-picker.service';
@Component({
@@ -68,7 +68,7 @@ export class AppTopBarComponent implements OnDestroy {
hasAnyTasks = false;
hasPendingBookdropFiles = false;
private eventTimer: any;
private eventTimer: number | undefined;
private destroy$ = new Subject<void>();
private latestTasks: { [taskId: string]: MetadataBatchProgressNotification } = {};
@@ -197,7 +197,7 @@ export class AppTopBarComponent implements OnDestroy {
clearTimeout(this.eventTimer);
this.eventTimer = setTimeout(() => {
this.showPulse = false;
}, 4000);
}, 4000) as unknown as number;
}
private updateCompletedTaskCount() {
@@ -347,7 +347,7 @@ export class AppConfigService {
}
this.saveAppState(state);
this.onPresetChange();
}, {allowSignalWrites: true});
});
}
private loadAppState(): AppState {
@@ -92,7 +92,7 @@ export class AppSettingsService {
}
}
saveSettings(settings: { key: string; newValue: any }[]): Observable<void> {
saveSettings(settings: { key: string; newValue: unknown }[]): Observable<void> {
const payload = settings.map(setting => ({
name: setting.key,
value: setting.newValue
@@ -25,7 +25,7 @@ export class DownloadProgressService {
private lastUpdateTime = 0;
private updateThrottleMs = 100;
private pendingUpdate: DownloadProgress | null = null;
private throttleTimer: any = null;
private throttleTimer: ReturnType<typeof setTimeout> | null = null;
downloadProgress$ = this.downloadProgressSubject.asObservable();
@@ -99,8 +99,8 @@ export class FileDownloadService {
}, 100);
}
private handleDownloadError(error: any): void {
if (error?.name !== 'AbortError') {
private handleDownloadError(error: unknown): void {
if ((error as { name?: string })?.name !== 'AbortError') {
this.messageService.add({
severity: 'error',
summary: 'Download Failed',
@@ -66,7 +66,7 @@ export class MetadataProgressService implements OnDestroy {
return result;
}
private hasMetadataPermissions(user: any): boolean {
private hasMetadataPermissions(user: { permissions: { admin: boolean; canEditMetadata: boolean } } | null): boolean {
return !!(user?.permissions?.admin || user?.permissions?.canEditMetadata);
}
@@ -270,7 +270,7 @@ export class ReadingSessionService {
return this.currentSession !== null;
}
private log(message: string, data?: any): void {
private log(message: string, data?: unknown): void {
if (data) {
console.log(`[ReadingSession] ${message}`, data);
} else {
@@ -278,7 +278,7 @@ export class ReadingSessionService {
}
}
private logError(message: string, error?: any): void {
private logError(message: string, error?: unknown): void {
if (error) {
console.error(`[ReadingSession] ${message}`, error);
} else {
@@ -1,4 +1,4 @@
import {inject, Injectable} from '@angular/core';
import {inject, Injectable, Type} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {GithubSupportDialog} from '../components/github-support-dialog/github-support-dialog';
import {LibraryCreatorComponent} from '../../features/library-creator/library-creator.component';
@@ -37,8 +37,8 @@ export class DialogLauncherService {
maximizable: false,
}
openDialog(component: any, options: {}): DynamicDialogRef | null {
return this.dialogService.open(component, {
openDialog(component: unknown, options: {}): DynamicDialogRef | null {
return this.dialogService.open(component as Type<any>, {
...this.defaultDialogOptions,
...options,
@@ -105,7 +105,7 @@ export class IconService {
});
}
deleteSvgIcon(svgName: string): Observable<any> {
deleteSvgIcon(svgName: string): Observable<unknown> {
return this.http.delete(`${this.baseUrl}/${encodeURIComponent(svgName)}`).pipe(
tap(() => {
this.iconCache.removeIcon(svgName);
@@ -16,7 +16,7 @@ export class NotificationEventService {
private notificationHighlightSubject = new BehaviorSubject<boolean>(false);
notificationHighlight$ = this.notificationHighlightSubject.asObservable();
private highlightTimeout: any;
private highlightTimeout: ReturnType<typeof setTimeout> | undefined;
handleNewNotification(notification: LogNotification): void {
this.latestNotificationSubject.next(notification);