Improve Angular project structure and code organization (#1328)

This commit is contained in:
Aditya Chandel
2025-10-12 02:01:59 -06:00
committed by GitHub
parent 54a8bacccd
commit 7c9bd56f63
405 changed files with 463 additions and 727 deletions
+84
View File
@@ -0,0 +1,84 @@
import {Routes} from '@angular/router';
import {BookBrowserComponent} from '../features/book/components/book-browser/book-browser.component';
import {AppLayoutComponent} from '../shared/layout/component/layout-main/app.layout.component';
import {LoginComponent} from '../shared/components/login/login.component';
import {AuthGuard} from './auth.guard';
import {SettingsComponent} from '../features/settings/settings.component';
import {ChangePasswordComponent} from '../shared/components/change-password/change-password.component';
import {BookMetadataCenterComponent} from '../features/metadata/component/book-metadata-center-component/book-metadata-center.component';
import {SetupComponent} from '../shared/components/setup/setup.component';
import {SetupGuard} from '../shared/components/setup/setup.guard';
import {SetupRedirectGuard} from '../shared/components/setup/setup-redirect.guard';
import {EmptyComponent} from '../shared/components/empty/empty.component';
import {LoginGuard} from '../shared/components/setup/ login.guard';
import {OidcCallbackComponent} from './security/oidc-callback/oidc-callback.component';
import {CbxReaderComponent} from '../features/readers/cbx-reader/cbx-reader.component';
import {MainDashboardComponent} from '../features/dashboard/components/main-dashboard/main-dashboard.component';
import {SeriesPageComponent} from '../features/book/components/series-page/series-page.component';
import {MetadataManagerComponent} from '../features/metadata-manager/metadata-manager.component';
import {StatsComponent} from '../features/stats/component/stats-component';
import {EpubReaderComponent} from '../features/readers/epub-reader/component/epub-reader.component';
import {PdfReaderComponent} from '../features/readers/pdf-reader/pdf-reader.component';
import {BookdropFileReviewComponent} from '../features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component';
export const routes: Routes = [
{
path: '',
canActivate: [SetupRedirectGuard],
pathMatch: 'full',
component: EmptyComponent
},
{
path: 'setup',
component: SetupComponent,
canActivate: [SetupGuard]
},
{path: 'oauth2-callback', component: OidcCallbackComponent},
{
path: '',
component: AppLayoutComponent,
children: [
{path: 'dashboard', component: MainDashboardComponent, canActivate: [AuthGuard]},
{path: 'all-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'settings', component: SettingsComponent, canActivate: [AuthGuard]},
{path: 'library/:libraryId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'shelf/:shelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'unshelved-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'series/:seriesName', component: SeriesPageComponent, canActivate: [AuthGuard]},
{path: 'magic-shelf/:magicShelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'book/:bookId', component: BookMetadataCenterComponent, canActivate: [AuthGuard]},
{path: 'bookdrop', component: BookdropFileReviewComponent, canActivate: [AuthGuard]},
{path: 'metadata-manager', component: MetadataManagerComponent, canActivate: [AuthGuard]},
{path: 'stats', component: StatsComponent, canActivate: [AuthGuard]},
]
},
{
path: 'pdf-reader/book/:bookId',
component: PdfReaderComponent,
canActivate: [AuthGuard]
},
{
path: 'epub-reader/book/:bookId',
component: EpubReaderComponent,
canActivate: [AuthGuard]
},
{
path: 'cbx-reader/book/:bookId',
component: CbxReaderComponent,
canActivate: [AuthGuard]
},
{
path: 'login',
component: LoginComponent,
canActivate: [LoginGuard]
},
{
path: 'change-password',
component: ChangePasswordComponent
},
{
path: '**',
redirectTo: 'login',
pathMatch: 'full'
}
];
@@ -0,0 +1,126 @@
import {inject} from '@angular/core';
import {OAuthService} from 'angular-oauth2-oidc';
import {AuthService, websocketInitializer} from '../shared/service/auth.service';
import {AppSettingsService} from '../shared/service/app-settings.service';
import {AuthInitializationService} from './service/auth-initialization-service';
const OIDC_BYPASS_KEY = 'booklore-oidc-bypass';
const OIDC_ERROR_COUNT_KEY = 'booklore-oidc-error-count';
const MAX_OIDC_RETRIES = 3;
const OIDC_TIMEOUT_MS = 5000;
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return Promise.race([
promise,
new Promise<T>((_, reject) =>
setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)
)
]);
}
export function initializeAuthFactory() {
return () => {
const oauthService = inject(OAuthService);
const appSettingsService = inject(AppSettingsService);
const authService = inject(AuthService);
const authInitService = inject(AuthInitializationService);
return new Promise<void>((resolve) => {
const sub = appSettingsService.publicAppSettings$.subscribe(publicSettings => {
if (publicSettings) {
const forceLocalOnly = new URLSearchParams(window.location.search).get('localOnly') === 'true';
const oidcBypassed = localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
const errorCount = parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
if (!forceLocalOnly &&
publicSettings.oidcEnabled &&
publicSettings.oidcProviderDetails &&
!oidcBypassed &&
errorCount < MAX_OIDC_RETRIES) {
const details = publicSettings.oidcProviderDetails;
oauthService.configure({
issuer: details.issuerUri,
clientId: details.clientId,
scope: 'openid profile email offline_access',
redirectUri: window.location.origin + '/oauth2-callback',
responseType: 'code',
showDebugInformation: false,
requireHttps: false,
strictDiscoveryDocumentValidation: false,
});
console.log(`[OIDC] Attempting discovery and login (attempt ${errorCount + 1}/${MAX_OIDC_RETRIES})`);
withTimeout(oauthService.loadDiscoveryDocumentAndTryLogin(), OIDC_TIMEOUT_MS)
.then(() => {
console.log('[OIDC] Discovery document loaded and login attempted');
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
if (oauthService.hasValidAccessToken()) {
authService.tokenSubject.next(oauthService.getAccessToken());
console.log('[OIDC] Valid access token found after tryLogin');
oauthService.setupAutomaticSilentRefresh();
websocketInitializer(authService)();
authInitService.markAsInitialized();
resolve();
} else {
console.log('[OIDC] No valid access token found, attempting silent login with prompt=none');
oauthService.initImplicitFlow();
resolve();
}
})
.catch(err => {
const newErrorCount = errorCount + 1;
localStorage.setItem(OIDC_ERROR_COUNT_KEY, newErrorCount.toString());
authInitService.markAsInitialized();
const isTimeout = err.message.includes('timed out');
const errorType = isTimeout ? 'timeout' : 'network/configuration';
console.error(
`OIDC initialization failed (${errorType}, attempt ${newErrorCount}/${MAX_OIDC_RETRIES}): ` +
'Unable to complete OpenID Connect discovery or login. ' +
`${isTimeout ? 'The request timed out after ' + OIDC_TIMEOUT_MS + 'ms. ' : ''}` +
'This may be due to an incorrect issuer URL, client ID, network issue, or slow server response. ' +
'Falling back to local login. Details:', err
);
if (newErrorCount >= MAX_OIDC_RETRIES) {
console.warn(`[OIDC] Maximum retry attempts (${MAX_OIDC_RETRIES}) exceeded. OIDC will be automatically bypassed until manually re-enabled.`);
localStorage.setItem(OIDC_BYPASS_KEY, 'true');
}
resolve();
});
} else {
if (forceLocalOnly) {
console.warn('[OIDC] Forced local-only login via ?localOnly=true');
} else if (oidcBypassed) {
console.log('[OIDC] OIDC is manually bypassed, using local authentication only');
} else if (errorCount >= MAX_OIDC_RETRIES) {
console.log(`[OIDC] OIDC automatically bypassed due to ${errorCount} consecutive errors`);
}
authInitService.markAsInitialized();
resolve();
}
sub.unsubscribe();
}
});
});
};
}
export function resetOidcBypass(): void {
localStorage.removeItem(OIDC_BYPASS_KEY);
localStorage.removeItem(OIDC_ERROR_COUNT_KEY);
}
export function isOidcBypassed(): boolean {
return localStorage.getItem(OIDC_BYPASS_KEY) === 'true';
}
export function getOidcErrorCount(): number {
return parseInt(localStorage.getItem(OIDC_ERROR_COUNT_KEY) || '0', 10);
}
+35
View File
@@ -0,0 +1,35 @@
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Router } from '@angular/router';
import {AuthService} from '../shared/service/auth.service';
import {OAuthService} from 'angular-oauth2-oidc';
export const AuthGuard: CanActivateFn = (route, state) => {
const router = inject(Router);
const authService = inject(AuthService);
const oauthService = inject(OAuthService);
const internalAccessToken = authService.getInternalAccessToken();
if (internalAccessToken) {
try {
const payload = JSON.parse(atob(internalAccessToken.split('.')[1]));
if (payload.isDefaultPassword) {
router.navigate(['/change-password']);
return false;
}
return true;
} catch (e) {
localStorage.removeItem('accessToken_Internal');
router.navigate(['/login']);
return false;
}
}
if (oauthService.hasValidAccessToken()) {
return true;
}
router.navigate(['/login']);
return false;
};
@@ -1,37 +0,0 @@
<div class="change-password-container">
<div class="change-password-wrapper">
<p-card class="change-password-card p-fluid">
<ng-template pTemplate="content">
<form #changePasswordForm="ngForm" (ngSubmit)="changePassword()">
<div class="p-field">
<label for="currentPassword">Current Password</label>
<p-password id="currentPassword" [(ngModel)]="currentPassword" name="currentPassword" [feedback]="false" required fluid></p-password>
</div>
<div class="p-field">
<label for="newPassword">New Password</label>
<p-password id="newPassword" [(ngModel)]="newPassword" name="newPassword" [feedback]="false" required fluid></p-password>
</div>
<div class="p-field">
<label for="confirmNewPassword">Confirm New Password</label>
<p-password id="confirmNewPassword" [(ngModel)]="confirmNewPassword" name="confirmNewPassword" [feedback]="false" required fluid></p-password>
@if (!passwordsMatch && confirmNewPassword) {
<p-message severity="error" text="New passwords do not match."></p-message>
}
</div>
<p-button type="submit" label="Change Password" icon="pi pi-key" class="p-fluid"></p-button>
@if (errorMessage) {
<p-message severity="error" text="{{ errorMessage }}"></p-message>
}
@if (successMessage) {
<p-message severity="success" text="{{ successMessage }}"></p-message>
}
</form>
</ng-template>
</p-card>
</div>
</div>
@@ -1,28 +0,0 @@
.change-password-container {
@apply flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-900 via-cyan-600 to-blue-400 relative;
}
.change-password-wrapper {
@apply flex flex-col items-center gap-6 absolute top-1/4 transform -translate-y-1/4;
}
.app-title {
@apply text-5xl font-extrabold text-white drop-shadow-lg;
text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
}
.change-password-card {
@apply w-96 shadow-lg rounded-xl bg-opacity-90 backdrop-blur-lg;
}
form {
@apply flex flex-col gap-4;
}
.p-field {
@apply flex flex-col gap-2;
}
p-button {
@apply mt-4;
}
@@ -1,81 +0,0 @@
import {Component, inject} from '@angular/core';
import {Button} from 'primeng/button';
import {Card} from 'primeng/card';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Message} from 'primeng/message';
import {Password} from 'primeng/password';
import {MessageService, PrimeTemplate} from 'primeng/api';
import {UserService} from '../../../settings/user-management/user.service';
import {AuthService} from '../../service/auth.service';
@Component({
selector: 'app-change-password',
standalone: true,
imports: [
Button,
Card,
FormsModule,
Message,
Password,
PrimeTemplate,
ReactiveFormsModule
],
templateUrl: './change-password.component.html',
styleUrl: './change-password.component.scss'
})
export class ChangePasswordComponent {
currentPassword: string = '';
newPassword: string = '';
confirmNewPassword: string = '';
errorMessage: string | null = null;
successMessage: string | null = null;
protected userService = inject(UserService);
protected authService = inject(AuthService);
protected messageService = inject(MessageService);
get passwordsMatch(): boolean {
return this.newPassword === this.confirmNewPassword;
}
changePassword() {
this.errorMessage = null;
this.successMessage = null;
if (!this.currentPassword || !this.newPassword || !this.confirmNewPassword) {
this.errorMessage = 'All fields are required.';
return;
}
if (!this.passwordsMatch) {
this.errorMessage = 'New passwords do not match.';
return;
}
if (this.currentPassword === this.newPassword) {
this.errorMessage = 'New password cannot be the same as the current password.';
return;
}
this.userService.changePassword(this.currentPassword, this.newPassword).subscribe({
next: () => {
this.successMessage = 'Password changed successfully!';
this.logout();
},
error: (err) => {
this.errorMessage = err.message;
this.messageService.add({
severity: 'error',
summary: 'Password Change Failed',
detail: this.errorMessage ?? 'An unknown error occurred.'
});
}
});
}
logout() {
this.authService.logout();
window.location.href = '/login';
}
}
@@ -1,84 +0,0 @@
<div class="dialog-container">
<div class="info-message">
<i class="pi pi-exclamation-triangle"></i>
<p>{{ totalRecords }} duplicate file groups have been detected in your library. To maintain data integrity and ensure optimal performance, please review and remove these duplicate entries from your file system.</p>
</div>
<div class="table-container">
<p-table
#dataTable
[value]="(duplicateFiles$ | async) || []"
[scrollable]="true"
scrollHeight="100%"
[paginator]="false"
[rows]="15"
[rowHover]="true">
<ng-template pTemplate="body" let-group>
<tr>
<td>
<div class="hash-group">
<div class="hash-header">
<i class="pi pi-copy"></i>
<span class="hash-label">Hash:</span>
<span class="hash-value">{{ group.hash }}</span>
<span class="file-count">({{ group.files.length }} files)</span>
</div>
<div class="files-list">
@for (file of (group.files || []); track file.fullPath) {
<div class="file-item-compact">
<div class="file-icon">
<i class="pi pi-file"></i>
</div>
<div class="file-details">
<div class="filename">{{ file.fileName }}</div>
<div class="file-path" [title]="file.fullPath">{{ file.fullPath }}</div>
<div class="library-info">
<i class="pi pi-database"></i>
<span>{{ file.libraryName }}</span>
<span class="timestamp">{{ file.timestamp | date:'short' }}</span>
</div>
</div>
</div>
}
</div>
</div>
</td>
</tr>
</ng-template>
<ng-template pTemplate="emptymessage">
<tr>
<td class="empty-message">
<div class="empty-content">
<i class="pi pi-info-circle"></i>
<span>No duplicate files detected</span>
</div>
</td>
</tr>
</ng-template>
</p-table>
</div>
<div class="bottom-fixed-area">
<div class="paginator-container">
<p-paginator
[first]="first"
[rows]="rows"
[totalRecords]="totalRecords"
[showCurrentPageReport]="true"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords} duplicate file groups"
(onPageChange)="onPageChange($event)">
</p-paginator>
</div>
<div class="dialog-actions">
<p-button
label="Acknowledge"
icon="pi pi-check"
(click)="acknowledgeAndClose()">
</p-button>
</div>
</div>
</div>
@@ -1,235 +0,0 @@
.dialog-container {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.table-container {
flex: 1;
overflow: hidden;
margin-bottom: 100px;
::ng-deep .p-datatable {
height: 100%;
.p-datatable-wrapper {
height: 100%;
}
.p-datatable-tbody > tr > td {
border: none !important;
padding: 0.5rem 0.5rem;
}
.p-datatable-tbody > tr {
border: none !important;
}
}
}
.bottom-fixed-area {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: var(--surface-ground);
z-index: 1000;
display: flex;
flex-direction: column;
}
.paginator-container {
::ng-deep .p-paginator {
border: none;
border-bottom: 1px solid var(--border-color);
}
}
.dialog-actions {
display: flex;
justify-content: flex-end;
padding: 1rem;
}
.duplicate-files-content {
overflow: hidden;
}
.hash-group {
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 1rem;
margin: 0.5rem 0;
}
.hash-header {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.75rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
i {
color: var(--primary-color);
font-size: 0.9rem;
}
.hash-label {
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
font-size: 0.9rem;
}
.hash-value {
font-family: 'Courier New', monospace;
color: rgba(255, 255, 255, 0.7);
font-size: 1rem;
font-weight: 900;
background: rgba(255, 255, 255, 0.05);
padding: 0.25rem 0.5rem;
border-radius: 4px;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-count {
background: var(--primary-color);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 12px;
font-size: 0.8rem;
font-weight: 500;
}
}
.files-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.file-item-compact {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.75rem;
border-radius: 6px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.2s ease;
margin-left: 1rem;
}
.file-icon {
background: var(--primary-color);
color: white;
width: 32px;
height: 32px;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
i {
font-size: 0.9rem;
}
}
.file-details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.filename {
font-family: 'Courier New', monospace;
font-weight: 600;
font-size: 0.95rem;
color: rgba(255, 255, 255, 0.9);
word-break: break-word;
line-height: 1.2;
}
.file-path {
font-size: 0.95rem;
color: rgba(255, 255, 255, 0.7);
font-family: 'Courier New', monospace;
word-break: break-all;
line-height: 1.2;
max-height: 2.4em;
overflow: hidden;
}
.library-info {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.8);
margin-top: 0.1rem;
i {
color: var(--primary-color);
font-size: 0.85rem;
}
.timestamp {
margin-left: auto;
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.6);
}
}
.empty-message {
text-align: center !important;
padding: 3rem 1rem !important;
.empty-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
opacity: 0.6;
i {
font-size: 1.5rem;
}
span {
font-size: 0.875rem;
}
}
}
.info-message {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 1rem;
margin-bottom: 1rem;
background: rgba(234, 88, 12, 0.1);
border: 1px solid rgba(234, 88, 12, 0.3);
border-radius: 0.375rem;
color: #fbbf24;
i {
color: #f59e0b;
font-size: 1.125rem;
margin-top: 0.125rem;
flex-shrink: 0;
}
p {
margin: 0;
line-height: 1.5;
font-size: 1rem;
}
}
@@ -1,86 +0,0 @@
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
import { TableModule } from 'primeng/table';
import { ButtonModule } from 'primeng/button';
import { TooltipModule } from 'primeng/tooltip';
import { PaginatorModule } from 'primeng/paginator';
import { Observable, map } from 'rxjs';
import {DuplicateFileNotification} from '../../../shared/websocket/model/duplicate-file-notification.model';
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
@Component({
selector: 'app-duplicate-files-dialog',
standalone: true,
imports: [CommonModule, TableModule, ButtonModule, TooltipModule, PaginatorModule],
templateUrl: './duplicate-files-dialog.component.html',
styleUrls: ['./duplicate-files-dialog.component.scss']
})
export class DuplicateFilesDialogComponent implements OnInit {
duplicateFiles$: Observable<{ hash: string; files: DuplicateFileNotification[] }[]>;
totalRecords = 0;
first = 0;
rows = 15;
constructor(
public ref: DynamicDialogRef,
public config: DynamicDialogConfig,
private duplicateFileService: DuplicateFileService
) {
this.duplicateFiles$ = this.config.data.duplicateFiles$.pipe(
map((files: DuplicateFileNotification[] | null) => {
if (!files) return [];
// Group files by hash
const groupedFiles = files.reduce((acc, file) => {
if (!acc[file.hash]) {
acc[file.hash] = [];
}
acc[file.hash].push(file);
return acc;
}, {} as { [hash: string]: DuplicateFileNotification[] });
const groups = Object.entries(groupedFiles).map(([hash, files]) => ({
hash,
files: files.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
}));
this.totalRecords = groups.length;
return groups.slice(this.first, this.first + this.rows);
})
);
}
ngOnInit() {}
onPageChange(event: any) {
this.first = event.first;
this.rows = event.rows;
this.duplicateFiles$ = this.config.data.duplicateFiles$.pipe(
map((files: DuplicateFileNotification[] | null) => {
if (!files) return [];
const groupedFiles = files.reduce((acc, file) => {
if (!acc[file.hash]) {
acc[file.hash] = [];
}
acc[file.hash].push(file);
return acc;
}, {} as { [hash: string]: DuplicateFileNotification[] });
const groups = Object.entries(groupedFiles).map(([hash, files]) => ({
hash,
files: files.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
}));
this.totalRecords = groups.length;
return groups.slice(this.first, this.first + this.rows);
})
);
}
acknowledgeAndClose() {
this.duplicateFileService.clearDuplicateFiles();
this.ref.close();
}
}
@@ -1,22 +0,0 @@
@if (duplicateFilesCount$ | async; as count) {
@if (count > 0) {
<div class="flex flex-col p-4 space-y-2 live-border">
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<i class="pi pi-exclamation-triangle text-yellow-500"></i>
<span class="font-normal text-zinc-200">{{ count }} duplicate files detected</span>
</div>
<p-tag [value]="count.toString()" severity="warn" [rounded]="true"></p-tag>
</div>
<p-button
label="View Details"
icon="pi pi-list"
outlined
size="small"
severity="info"
fluid
(click)="openDialog()">
</p-button>
</div>
}
}
@@ -1,10 +0,0 @@
.duplicate-files-content {
max-height: 500px;
overflow: hidden;
}
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
@@ -1,80 +0,0 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {CommonModule} from '@angular/common';
import {DialogModule} from 'primeng/dialog';
import {ButtonModule} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {TagModule} from 'primeng/tag';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
import {DuplicateFileNotification} from '../../../shared/websocket/model/duplicate-file-notification.model';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DuplicateFilesDialogComponent} from './duplicate-files-dialog.component';
@Component({
selector: 'app-duplicate-files-notification',
standalone: true,
imports: [CommonModule, DialogModule, ButtonModule, TableModule, TagModule],
templateUrl: './duplicate-files-notification.component.html',
styleUrls: ['./duplicate-files-notification.component.scss'],
providers: [DialogService]
})
export class DuplicateFilesNotificationComponent implements OnDestroy {
displayDialog = false;
private duplicateFileService = inject(DuplicateFileService);
private ref: DynamicDialogRef | undefined;
duplicateFiles$ = this.duplicateFileService.duplicateFiles$;
duplicateFilesCount$: Observable<number> = this.duplicateFiles$.pipe(
map(files => files?.length || 0)
);
constructor(
private dialogService: DialogService
) {
}
openDialog() {
this.ref = this.dialogService.open(DuplicateFilesDialogComponent, {
header: 'Duplicate Files Detected',
width: '80dvw',
height: '75dvh',
contentStyle: {overflow: 'hidden'},
maximizable: true,
modal: true,
data: {
duplicateFiles$: this.duplicateFiles$
}
});
this.ref.onClose.subscribe((result: any) => {
if (result) {
// Handle any result from dialog if needed
}
});
}
closeDialog() {
this.displayDialog = false;
}
clearAllDuplicates() {
this.duplicateFileService.clearDuplicateFiles();
this.closeDialog();
}
removeDuplicate(file: DuplicateFileNotification) {
this.duplicateFileService.removeDuplicateFile(file.fullPath, file.libraryId);
}
formatTimestamp(timestamp: string): string {
return new Date(timestamp).toLocaleString();
}
ngOnDestroy() {
if (this.ref) {
this.ref.close();
}
}
}
@@ -1,4 +0,0 @@
<div class="flex flex-col p-4 space-y-2 live-border">
<p class="text-xs text-zinc-400">{{ latestNotification.timestamp }}</p>
<p class="font-normal text-zinc-200">{{ latestNotification.message }}</p>
</div>
@@ -1,5 +0,0 @@
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
@@ -1,24 +0,0 @@
import {Component, inject} from '@angular/core';
import {NotificationEventService} from '../../../shared/websocket/notification-event.service';
import {LogNotification} from '../../../shared/websocket/model/log-notification.model';
@Component({
selector: 'app-live-notification-box',
standalone: true,
templateUrl: './live-notification-box.component.html',
styleUrls: ['./live-notification-box.component.scss'],
host: {
class: 'config-panel'
},
})
export class LiveNotificationBoxComponent {
latestNotification: LogNotification = {message: 'No recent notifications...'};
private notificationService = inject(NotificationEventService);
constructor() {
this.notificationService.latestNotification$.subscribe(notification => {
this.latestNotification = notification;
});
}
}
@@ -1,133 +0,0 @@
<div class="flex items-center justify-center min-h-screen min-w-[100vw] overflow-hidden"
style="background: linear-gradient(60deg, var(--primary-color) 0%, #1e3a8a 100%);">
<div class="flex flex-col items-center justify-center -mt-48 w-[90%] sm:w-auto sm:min-w-[400px] md:min-w-[500px]">
<div class="w-full" style="border-radius: 56px; padding: 0.3rem; background: linear-gradient(180deg, var(--primary-color) 10%, rgba(33, 150, 243, 0) 30%)">
<div class="w-full bg-surface-900 pt-8 pb-14 px-8 sm:px-12" style="border-radius: 53px">
<div class="text-center mb-8">
<svg class="mb-8 w-14 h-14 mx-auto" viewBox="0 0 126 126" fill="var(--primary-color)" xmlns="http://www.w3.org/2000/svg">
<path
d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z"/>
<path
d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z"
fill="white"/>
</svg>
<div class="text-3xl font-medium mb-4">Welcome to Booklore</div>
<span class="font-medium">Sign in to continue</span>
</div>
@if (showOidcBypassInfo) {
<div class="mb-4 p-3 rounded-md bg-yellow-900/30 border border-yellow-600/50 w-full">
<div class="flex flex-col items-center">
<div class="flex items-center gap-2 text-yellow-200 text-sm mb-2">
<i class="pi pi-exclamation-triangle"></i>
<span class="font-medium">OIDC Authentication Issues Detected</span>
</div>
<p class="text-xs text-yellow-300 mb-3 text-center">
{{ oidcBypassMessage }}
</p>
<div class="flex gap-4">
<p-button
size="small"
severity="warn"
label="Retry OIDC"
icon="pi pi-refresh"
(click)="retryOidc()"
/>
<p-button
size="small"
severity="success"
label="Use Local Login"
icon="pi pi-times"
(click)="dismissOidcWarning()"
/>
</div>
</div>
</div>
}
<form class="flex flex-col gap-4 w-full" #loginForm="ngForm" (ngSubmit)="login()">
<div class="flex flex-col gap-2">
<label for="username" class="text-lg font-medium">Username</label>
<input
fluid
pInputText
id="username"
name="username"
required
[(ngModel)]="username"
placeholder="Enter your username"
class="w-full"
autocomplete="username"
/>
</div>
<div class="flex flex-col gap-2">
<label for="password" class="text-lg font-medium">Password</label>
<p-password
id="password"
name="password"
required
[(ngModel)]="password"
[feedback]="false"
placeholder="Enter your password"
[toggleMask]="true"
class="mb-4"
[fluid]="true"
autocomplete="current-password"
></p-password>
</div>
<p-button
fluid
type="submit"
label="Login"
icon="pi pi-sign-in"
[disabled]="!loginForm.valid || !username || !password"
class="w-full">
</p-button>
@if (errorMessage) {
<p-message severity="error">{{ errorMessage }}</p-message>
}
@if (oidcEnabled && !isOidcBypassed) {
<div class="flex items-center gap-2 my-2">
<hr class="flex-grow" style="border: none; border-top: 1px solid var(--border-color);"/>
<span class="text-gray-300">or</span>
<hr class="flex-grow" style="border: none; border-top: 1px solid var(--border-color);"/>
</div>
<p-button
fluid
severity="info"
[label]="isOidcLoginInProgress ? 'Redirecting to ' + oidcName + '...' : 'Login with ' + oidcName"
[icon]="isOidcLoginInProgress ? 'pi pi-spin pi-spinner' : 'pi pi-id-card'"
[disabled]="isOidcLoginInProgress"
(click)="loginWithOidc()"
class="w-full bg-gray-800 text-white hover:bg-gray-700"/>
<div class="text-center">
<button
type="button"
class="text-xs text-gray-400 hover:text-gray-300 underline"
(click)="bypassOidc()">
Having trouble with {{ oidcName }}? Use local login only
</button>
</div>
}
@if (oidcEnabled && isOidcBypassed) {
<div class="text-center mt-4">
<button
type="button"
class="text-xs text-blue-400 hover:text-blue-300 underline"
(click)="enableOidc()">
Re-enable {{ oidcName }} login
</button>
</div>
}
</form>
</div>
</div>
</div>
</div>
@@ -1,146 +0,0 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {AuthService} from '../../service/auth.service';
import {Router} from '@angular/router';
import {FormsModule} from '@angular/forms';
import {Password} from 'primeng/password';
import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
import {InputText} from 'primeng/inputtext';
import {OAuthService} from 'angular-oauth2-oidc';
import {Observable, Subject} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {getOidcErrorCount, isOidcBypassed, resetOidcBypass} from '../../../auth-initializer';
import {AppSettingsService, PublicAppSettings} from '../../service/app-settings.service';
@Component({
selector: 'app-login',
imports: [
FormsModule,
Password,
Button,
Message,
InputText
],
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit, OnDestroy {
username = '';
password = '';
errorMessage = '';
oidcEnabled = false;
oidcName = 'OIDC';
isOidcBypassed = false;
showOidcBypassInfo = false;
oidcBypassMessage = '';
isOidcLoginInProgress = false;
private authService = inject(AuthService);
private oAuthService = inject(OAuthService);
private appSettingsService = inject(AppSettingsService);
private router = inject(Router);
publicAppSettings$: Observable<PublicAppSettings | null> = this.appSettingsService.publicAppSettings$;
private destroy$ = new Subject<void>();
ngOnInit(): void {
this.publicAppSettings$
.pipe(
filter(settings => settings != null),
take(1)
)
.subscribe(publicSettings => {
this.oidcEnabled = publicSettings!.oidcEnabled;
this.oidcName = publicSettings!.oidcProviderDetails?.providerName || 'OIDC';
this.checkOidcBypassStatus();
});
}
private checkOidcBypassStatus(): void {
this.isOidcBypassed = isOidcBypassed();
const errorCount = getOidcErrorCount();
if (this.oidcEnabled && (this.isOidcBypassed || errorCount > 0)) {
this.showOidcBypassInfo = true;
if (this.isOidcBypassed && errorCount >= 3) {
this.oidcBypassMessage = `${this.oidcName} authentication has been automatically disabled after ${errorCount} consecutive failures (including timeouts). You can retry or continue with local login.`;
} else if (this.isOidcBypassed) {
this.oidcBypassMessage = `${this.oidcName} authentication has been manually disabled. You can re-enable it or continue with local login.`;
} else if (errorCount > 0) {
this.oidcBypassMessage = `${this.oidcName} authentication encountered ${errorCount} error(s), possibly due to timeouts or server issues.`;
}
}
}
login(): void {
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
next: (response) => {
if (response.isDefaultPassword === 'true') {
this.router.navigate(['/change-password']);
} else {
this.router.navigate(['/dashboard']);
}
},
error: (error) => {
if (error.status === 0) {
this.errorMessage = 'Cannot connect to the server. Please check your connection and try again.';
} else {
this.errorMessage = error?.error?.message || 'An unexpected error occurred. Please try again.';
}
}
});
}
loginWithOidc(): void {
if (this.isOidcLoginInProgress) {
return;
}
this.isOidcLoginInProgress = true;
this.errorMessage = '';
try {
setTimeout(() => {
this.isOidcLoginInProgress = false;
}, 5000);
this.oAuthService.initCodeFlow();
} catch (error) {
console.error('OIDC login initiation failed:', error);
this.errorMessage = 'Failed to initiate OIDC login. Please try again or use local login.';
this.isOidcLoginInProgress = false;
}
}
bypassOidc(): void {
localStorage.setItem('booklore-oidc-bypass', 'true');
this.isOidcBypassed = true;
this.showOidcBypassInfo = false;
}
enableOidc(): void {
resetOidcBypass();
this.isOidcBypassed = false;
this.showOidcBypassInfo = false;
this.isOidcLoginInProgress = false;
window.location.reload();
}
retryOidc(): void {
resetOidcBypass();
this.isOidcBypassed = false;
this.showOidcBypassInfo = false;
this.isOidcLoginInProgress = false;
window.location.reload();
}
dismissOidcWarning(): void {
this.showOidcBypassInfo = false;
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -1,93 +0,0 @@
<div class="task-border mt-4">
@if (Object.keys(activeTasks).length > 0) {
@for (task of activeTasks | keyvalue; track task; let idx = $index) {
<div class="task-card p-4">
<div class="flex items-center justify-between mb-2">
<div class="flex items-center gap-2">
<p class="text-sm font-semibold text-[var(--primary-color)]">Metadata Fetch Task</p>
</div>
<div class="flex items-center gap-1">
@if (task.value.review) {
<p-tag
value="Review"
severity="warn"
class="text-xs">
</p-tag>
} @else {
<p-tag
value="Auto"
severity="success"
class="text-xs">
</p-tag>
}
<p-tag
[value]="getStatusLabel(task.value.status)"
[severity]="getTagSeverity(task.value.status)"
class="text-xs"
></p-tag>
</div>
</div>
<div class="task-message text-gray-200">
{{ task.value.message }}
</div>
<div class="task-progress-info text-sm text-gray-300">
Book <strong>{{ task.value.status === 'COMPLETED' || task.value.completed >= task.value.total ? task.value.total : task.value.completed + 1 }}</strong>
of {{ task.value.total }}
</div>
<p-progressBar
[style]="{ height: '15px' }"
[value]="getProgressPercent(task.value)"
[showValue]="true">
</p-progressBar>
@if (task.value.status === 'COMPLETED' || task.value.status === 'ERROR') {
<div class="action-buttons mt-4 flex justify-end gap-2">
@if (task.value.review) {
<p-button
label="Review"
severity="info"
icon="pi pi-search"
size="small"
outlined
(click)="reviewTask(task.key)">
</p-button>
}
<p-button
[label]="task.value.review ? 'Discard' : 'Dismiss'"
icon="pi pi-times"
[severity]="task.value.review ? 'danger' : 'secondary'"
size="small"
[pTooltip]="task.value.review ? 'Preserve current metadata, discard new fetched metadata' : ''"
[tooltipPosition]="task.value.review ? 'top' : undefined"
outlined
(click)="clearTask(task.key)">
</p-button>
</div>
} @else if (task.value.status === 'IN_PROGRESS') {
<div class="action-buttons mt-4 flex justify-end gap-2">
<p-button
label="Cancel"
icon="pi pi-stop"
severity="danger"
size="small"
pTooltip="Cancel this task"
tooltipPosition="top"
outlined
(click)="cancelTask(task.key)">
</p-button>
</div>
}
</div>
@if (idx < Object.keys(activeTasks).length - 1) {
<p-divider></p-divider>
}
}
}
</div>
@@ -1,34 +0,0 @@
.task-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
.task-header {
display: flex;
justify-content: flex-end;
margin-bottom: 0.5rem;
}
.task-message {
font-size: 1rem;
color: var(--text-color);
margin-bottom: 0.5rem;
}
.task-progress-info {
font-size: 0.875rem;
color: var(--text-secondary-color);
margin-bottom: 0.5rem;
}
.review-button {
text-align: right;
margin-top: 0.75rem;
}
.review-indicator {
display: flex;
align-items: center;
gap: 0.5rem;
}
@@ -1,172 +0,0 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {KeyValuePipe} from '@angular/common';
import {ProgressBarModule} from 'primeng/progressbar';
import {ButtonModule} from 'primeng/button';
import {Divider} from 'primeng/divider';
import {Tooltip} from 'primeng/tooltip';
import {DialogService} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {MetadataBatchProgressNotification, MetadataBatchStatus, MetadataBatchStatusLabels} from '../../model/metadata-batch-progress.model';
import {MetadataProgressService} from '../../service/metadata-progress-service';
import {MetadataReviewDialogComponent} from '../../../metadata/metadata-review-dialog-component/metadata-review-dialog-component';
import {MetadataTaskService} from '../../../book/service/metadata-task';
import {TaskService} from '../../../shared/services/task.service';
import {Tag} from 'primeng/tag';
@Component({
selector: 'app-metadata-progress-widget',
templateUrl: './metadata-progress-widget-component.html',
styleUrls: ['./metadata-progress-widget-component.scss'],
standalone: true,
imports: [KeyValuePipe, ProgressBarModule, ButtonModule, Divider, Tooltip, Tag]
})
export class MetadataProgressWidgetComponent implements OnInit, OnDestroy {
activeTasks: { [taskId: string]: MetadataBatchProgressNotification } = {};
private destroy$ = new Subject<void>();
private dialogService = inject(DialogService);
private metadataProgressService = inject(MetadataProgressService);
private metadataTaskService = inject(MetadataTaskService);
private taskService = inject(TaskService);
private messageService = inject(MessageService);
private lastUpdateMap = new Map<string, number>();
private timeoutHandles = new Map<string, any>();
private readonly TASK_STALL_TIMEOUT_MS = 60 * 1000; // 1 minute
ngOnInit(): void {
this.metadataProgressService.activeTasks$
.pipe(takeUntil(this.destroy$))
.subscribe(tasks => {
this.activeTasks = tasks;
this.checkForStalledTasks(tasks);
});
}
private checkForStalledTasks(tasks: { [taskId: string]: MetadataBatchProgressNotification }): void {
const now = Date.now();
for (const taskId of this.timeoutHandles.keys()) {
if (!tasks[taskId]) {
clearTimeout(this.timeoutHandles.get(taskId));
this.timeoutHandles.delete(taskId);
this.lastUpdateMap.delete(taskId);
}
}
for (const [taskId, task] of Object.entries(tasks)) {
this.lastUpdateMap.set(taskId, now);
if (this.timeoutHandles.has(taskId)) {
clearTimeout(this.timeoutHandles.get(taskId));
}
this.timeoutHandles.set(
taskId,
setTimeout(() => {
this.markTaskStalled(taskId);
}, this.TASK_STALL_TIMEOUT_MS)
);
}
}
private markTaskStalled(taskId: string): void {
const task = this.activeTasks[taskId];
if (!task) return;
if (task.status !== MetadataBatchStatus.COMPLETED && task.status !== 'ERROR') {
this.activeTasks[taskId] = {
...task,
status: MetadataBatchStatus.ERROR,
message: 'Task stalled or backend unavailable'
};
this.activeTasks = {...this.activeTasks};
}
}
getProgressPercent(task: MetadataBatchProgressNotification): number {
if (task.total <= 0) return 0;
if (task.status === 'COMPLETED') return 100;
return Math.round((task.completed / task.total) * 100);
}
clearTask(taskId: string): void {
this.metadataTaskService.deleteTask(taskId).subscribe(() => {
this.metadataProgressService.clearTask(taskId);
clearTimeout(this.timeoutHandles.get(taskId));
this.timeoutHandles.delete(taskId);
this.lastUpdateMap.delete(taskId);
});
}
reviewTask(taskId: string): void {
this.dialogService.open(MetadataReviewDialogComponent, {
showHeader: false,
width: '90vw',
height: '90vh',
data: {taskId},
closable: false,
modal: true
});
}
cancelTask(taskId: string): void {
this.taskService.cancelTask(taskId).subscribe({
next: () => {
const task = this.activeTasks[taskId];
if (task) {
this.activeTasks[taskId] = {
...task,
status: MetadataBatchStatus.ERROR,
message: 'Task cancelled by user'
};
this.activeTasks = {...this.activeTasks};
}
this.messageService.add({
severity: 'success',
summary: 'Cancellation Scheduled',
detail: 'Task cancellation has been successfully scheduled'
});
},
error: (error) => {
console.error('Failed to cancel task:', error);
this.messageService.add({
severity: 'error',
summary: 'Cancel Failed',
detail: 'Failed to cancel the task. Please try again.'
});
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
for (const timeout of this.timeoutHandles.values()) {
clearTimeout(timeout);
}
this.timeoutHandles.clear();
this.lastUpdateMap.clear();
}
getTagSeverity(status: 'IN_PROGRESS' | 'COMPLETED' | 'ERROR'): 'info' | 'success' | 'danger' {
switch (status) {
case 'COMPLETED':
return 'success';
case 'ERROR':
return 'danger';
case 'IN_PROGRESS':
default:
return 'info';
}
}
getStatusLabel(status: MetadataBatchStatus): string {
return MetadataBatchStatusLabels[status] ?? status;
}
protected readonly Object = Object;
}
@@ -1,12 +0,0 @@
<div class="metadata-progress-box flex gap-4 flex-col w-[25rem] max-h-[60vh] overflow-y-auto">
<app-live-notification-box/>
@if (hasDuplicateFiles$ | async) {
<app-duplicate-files-notification/>
}
@if (hasMetadataTasks$ | async) {
<app-metadata-progress-widget/>
}
@if (hasPendingBookdropFiles$ | async) {
<app-bookdrop-files-widget-component/>
}
</div>
@@ -1,9 +0,0 @@
.metadata-progress-box {
overflow-y: auto;
border-radius: 0.5rem;
}
::ng-deep .p-divider-horizontal {
margin: 0 !important;
padding: 0 !important;
}
@@ -1,39 +0,0 @@
import {Component, inject} from '@angular/core';
import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component';
import {MetadataProgressWidgetComponent} from '../metadata-progress-widget-component/metadata-progress-widget-component';
import {MetadataProgressService} from '../../service/metadata-progress-service';
import {map} from 'rxjs/operators';
import {AsyncPipe} from '@angular/common';
import {BookdropFilesWidgetComponent} from '../../../bookdrop/bookdrop-files-widget-component/bookdrop-files-widget.component';
import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
import {DuplicateFilesNotificationComponent} from '../duplicate-files-notification/duplicate-files-notification.component';
import {DuplicateFileService} from '../../../shared/websocket/duplicate-file.service';
@Component({
selector: 'app-unified-notification-popover-component',
imports: [
LiveNotificationBoxComponent,
MetadataProgressWidgetComponent,
AsyncPipe,
BookdropFilesWidgetComponent,
DuplicateFilesNotificationComponent
],
templateUrl: './unified-notification-popover-component.html',
standalone: true,
styleUrl: './unified-notification-popover-component.scss'
})
export class UnifiedNotificationBoxComponent {
metadataProgressService = inject(MetadataProgressService);
bookdropFileService = inject(BookdropFileService);
duplicateFileService = inject(DuplicateFileService);
hasMetadataTasks$ = this.metadataProgressService.activeTasks$.pipe(
map(tasks => Object.keys(tasks).length > 0)
);
hasPendingBookdropFiles$ = this.bookdropFileService.hasPendingFiles$;
hasDuplicateFiles$ = this.duplicateFileService.duplicateFiles$.pipe(
map(files => files && files.length > 0)
);
}
@@ -0,0 +1,3 @@
import {environment} from '../../../environments/environment';
export const API_CONFIG = environment.API_CONFIG;
@@ -0,0 +1,39 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class CustomReuseStrategy implements RouteReuseStrategy {
private storedRoutes = new Map<string, DetachedRouteHandle>();
// Only detach the route if it's for the book details page
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.routeConfig?.path === 'book/:id'; // Match the path of the route you want to reuse
}
// Store the route component instance when detaching
store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
if (handle) {
// Save the handle if we are detaching this route
this.storedRoutes.set(route.routeConfig?.path || '', handle);
}
}
// Check if we should attach the route (reuse it) when navigating back to it
shouldAttach(route: ActivatedRouteSnapshot): boolean {
// Attach the route only if there's a stored instance for this route
return !!this.storedRoutes.get(route.routeConfig?.path || '');
}
// Retrieve the stored route component instance
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
return this.storedRoutes.get(route.routeConfig?.path || '') || null;
}
// Determine if the route should be reused based on its configuration
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
// Reuse the route if the path and parameters match
return future.routeConfig === curr.routeConfig && future.params['id'] === curr.params['id'];
}
}
@@ -1 +0,0 @@
<p>empty works!</p>
@@ -1,11 +0,0 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-empty',
imports: [],
templateUrl: './empty.component.html',
styleUrl: './empty.component.scss'
})
export class EmptyComponent {
}
@@ -1,145 +0,0 @@
import {MetadataRefreshOptions} from '../../metadata/model/request/metadata-refresh-options.model';
export interface MetadataMatchWeights {
title: number;
subtitle: number;
description: number;
authors: number;
publisher: number;
publishedDate: number;
seriesName: number;
seriesNumber: number;
seriesTotal: number;
isbn13: number;
isbn10: number;
language: number;
pageCount: number;
categories: number;
amazonRating: number;
amazonReviewCount: number;
goodreadsRating: number;
goodreadsReviewCount: number;
hardcoverRating: number;
hardcoverReviewCount: number;
doubanRating: number;
doubanReviewCount: number;
coverImage: number;
}
export interface OidcProviderDetails {
providerName: string;
clientId: string;
issuerUri: string;
claimMapping: {
username: string;
email: string;
name: string;
};
}
export interface OidcAutoProvisionDetails {
enableAutoProvisioning: boolean;
defaultPermissions: string[];
defaultLibraryIds: number[];
}
export interface MetadataProviderSettings {
amazon: Amazon;
google: Google;
goodReads: Goodreads;
hardcover: Hardcover;
comicvine: Comicvine;
douban: Douban;
}
export interface Amazon {
enabled: boolean;
cookie: string;
domain: string;
}
export interface Google {
enabled: boolean;
}
export interface Goodreads {
enabled: boolean;
}
export interface Hardcover {
enabled: boolean;
apiKey: string;
}
export interface Comicvine {
enabled: boolean;
apiKey: string;
}
export interface Douban {
enabled: boolean;
}
export interface MetadataPersistenceSettings {
moveFilesToLibraryPattern: boolean;
saveToOriginalFile: boolean;
convertCbrCb7ToCbz: boolean;
}
export interface ReviewProviderConfig {
provider: string;
enabled: boolean;
maxReviews: number;
}
export interface PublicReviewSettings {
downloadEnabled: boolean;
autoDownloadEnabled: boolean;
providers: ReviewProviderConfig[];
}
export interface KoboSettings {
convertToKepub: boolean;
conversionLimitInMb: number;
}
export interface AppSettings {
autoBookSearch: boolean;
similarBookRecommendation: boolean;
defaultMetadataRefreshOptions: MetadataRefreshOptions;
libraryMetadataRefreshOptions: MetadataRefreshOptions[];
uploadPattern: string;
opdsServerEnabled: boolean;
remoteAuthEnabled: boolean;
oidcEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
cbxCacheSizeInMb: number;
maxFileUploadSizeInMb: number;
metadataProviderSettings: MetadataProviderSettings;
metadataMatchWeights: MetadataMatchWeights;
metadataPersistenceSettings: MetadataPersistenceSettings;
metadataPublicReviewsSettings: PublicReviewSettings;
koboSettings: KoboSettings;
metadataDownloadOnBookdrop: boolean;
}
export enum AppSettingKey {
QUICK_BOOK_MATCH = 'QUICK_BOOK_MATCH',
AUTO_BOOK_SEARCH = 'AUTO_BOOK_SEARCH',
SIMILAR_BOOK_RECOMMENDATION = 'SIMILAR_BOOK_RECOMMENDATION',
LIBRARY_METADATA_REFRESH_OPTIONS = 'LIBRARY_METADATA_REFRESH_OPTIONS',
UPLOAD_FILE_PATTERN = 'UPLOAD_FILE_PATTERN',
OPDS_SERVER_ENABLED = 'OPDS_SERVER_ENABLED',
OIDC_ENABLED = 'OIDC_ENABLED',
OIDC_PROVIDER_DETAILS = 'OIDC_PROVIDER_DETAILS',
OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS',
CBX_CACHE_SIZE_IN_MB = 'CBX_CACHE_SIZE_IN_MB',
MAX_FILE_UPLOAD_SIZE_IN_MB = 'MAX_FILE_UPLOAD_SIZE_IN_MB',
METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS',
METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS',
METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS',
METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP',
METADATA_PUBLIC_REVIEWS_SETTINGS = 'METADATA_PUBLIC_REVIEWS_SETTINGS',
KOBO_SETTINGS = 'KOBO_SETTINGS'
}
@@ -1,5 +0,0 @@
export interface AppState {
preset?: string;
primary?: string;
surface?: string;
}
@@ -1,20 +0,0 @@
export enum MetadataBatchStatus {
IN_PROGRESS = 'IN_PROGRESS',
COMPLETED = 'COMPLETED',
ERROR = 'ERROR',
}
export const MetadataBatchStatusLabels: Record<MetadataBatchStatus, string> = {
[MetadataBatchStatus.IN_PROGRESS]: 'In Progress',
[MetadataBatchStatus.COMPLETED]: 'Completed',
[MetadataBatchStatus.ERROR]: 'Error',
};
export interface MetadataBatchProgressNotification {
taskId: string;
completed: number;
total: number;
message: string;
status: MetadataBatchStatus;
review: boolean;
}
+19
View File
@@ -0,0 +1,19 @@
import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({
name: 'secure',
pure: true
})
export class SecurePipe implements PipeTransform {
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}
transform(url: string): Observable<SafeUrl> {
return this.http.get(url, { responseType: 'blob' }).pipe(
map(blob => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob)))
);
}
}
@@ -6,13 +6,13 @@ import {Button} from 'primeng/button';
import {Checkbox} from 'primeng/checkbox';
import {ToggleSwitch} from 'primeng/toggleswitch';
import {MessageService} from 'primeng/api';
import {AppSettingsService} from '../../service/app-settings.service';
import {AppSettingsService} from '../../../shared/service/app-settings.service';
import {Observable} from 'rxjs';
import {AppSettingKey, AppSettings, OidcProviderDetails} from '../../model/app-settings.model';
import {AppSettingKey, AppSettings, OidcProviderDetails} from '../../../shared/model/app-settings.model';
import {filter, take} from 'rxjs/operators';
import {MultiSelect} from 'primeng/multiselect';
import {Library} from '../../../book/model/library.model';
import {LibraryService} from '../../../book/service/library.service';
import {Library} from '../../../features/book/model/library.model';
import {LibraryService} from '../../../features/book/service/library.service';
@Component({
selector: 'app-authentication-settings',
@@ -1,7 +1,7 @@
import {Component, inject, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {OAuthService} from 'angular-oauth2-oidc';
import {AuthService} from '../../service/auth.service';
import {AuthService} from '../../../shared/service/auth.service';
import {MessageService} from 'primeng/api';
@Component({
@@ -1,435 +0,0 @@
import {DOCUMENT, isPlatformBrowser} from '@angular/common';
import {effect, inject, Injectable, PLATFORM_ID, signal} from '@angular/core';
import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes';
import Aura from '@primeng/themes/aura';
import {AppState} from '../model/app-state.model';
type ColorPalette = Record<string, string>;
interface Palette {
name: string;
palette: ColorPalette;
}
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
private readonly STORAGE_KEY = 'appConfigState';
appState = signal<AppState>({});
document = inject(DOCUMENT);
platformId = inject(PLATFORM_ID);
private initialized = false;
readonly surfaces: Palette[] = [
{
name: 'slate',
palette: {
0: '#ffffff',
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
900: '#0f172a',
950: '#020617'
}
},
{
name: 'gray',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'neutral',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
950: '#0a0a0a'
}
},
{
name: 'zinc',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'stone',
palette: {
0: '#ffffff',
50: '#fafaf9',
100: '#f5f5f4',
200: '#e7e5e4',
300: '#d6d3d1',
400: '#a8a29e',
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#292524',
900: '#1c1917',
950: '#0c0a09'
}
},
{
name: 'iron',
palette: {
0: '#ffffff',
50: '#f1f3f4',
100: '#e3e5e6',
200: '#d2d4d6',
300: '#b8bbc0',
400: '#9ca0a6',
500: '#7d8288',
600: '#646a70',
700: '#4c5258',
800: '#353a40',
900: '#1a1d20',
950: '#0d0f11'
}
},
{
name: 'steel',
palette: {
0: '#ffffff',
50: '#f3f4f6',
100: '#e5e7eb',
200: '#d1d5db',
300: '#b0b7c3',
400: '#8b93a6',
500: '#6b7280',
600: '#545861',
700: '#3f4347',
800: '#2c2f33',
900: '#16181b',
950: '#0b0d0e'
}
},
{
name: 'carbon',
palette: {
0: '#ffffff',
50: '#eef0f2',
100: '#dde1e6',
200: '#c7cdd5',
300: '#a8b0bc',
400: '#8691a0',
500: '#697080',
600: '#545a66',
700: '#41464f',
800: '#303439',
900: '#181a1d',
950: '#0c0e10'
}
},
{
name: 'ash',
palette: {
0: '#ffffff',
50: '#f4f6f8',
100: '#e6e9ed',
200: '#d3d8de',
300: '#b4bcc7',
400: '#919ca9',
500: '#71808a',
600: '#5a666f',
700: '#464f56',
800: '#34393e',
900: '#1a1e21',
950: '#0d1012'
}
},
{
name: 'smoke',
palette: {
0: '#ffffff',
50: '#f6f6f7',
100: '#ebebed',
200: '#dadadd',
300: '#bbbcc1',
400: '#989aa1',
500: '#797c84',
600: '#63666d',
700: '#4f5257',
800: '#3a3d42',
900: '#1d2023',
950: '#0e1011'
}
},
{
name: 'midnight-blue',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f7f8fb',
200: '#f0f2f7',
300: '#e5e8f0',
400: '#d3d8e3',
500: '#5c6b7a',
600: '#4a5866',
700: '#3b4651',
800: '#2d353e',
900: '#1f252c',
950: '#121518'
}
},
{
name: 'charcoal',
palette: {
0: '#ffffff',
50: '#f0f0f0',
100: '#e5e5e5',
200: '#d1d1d1',
300: '#b8b8b8',
400: '#9a9a9a',
500: '#7d7d7d',
600: '#666666',
700: '#525252',
800: '#3d3d3d',
900: '#2a2a2a',
950: '#141414'
}
},
{
name: 'soho',
palette: {
0: '#ffffff',
50: '#ececec',
100: '#dedfdf',
200: '#c4c4c6',
300: '#adaeb0',
400: '#97979b',
500: '#7f8084',
600: '#6a6b70',
700: '#55565b',
800: '#3f4046',
900: '#2c2c34',
950: '#16161d'
}
},
{
name: 'viva',
palette: {
0: '#ffffff',
50: '#f3f3f3',
100: '#e7e7e8',
200: '#cfd0d0',
300: '#b7b8b9',
400: '#9fa1a1',
500: '#87898a',
600: '#6e7173',
700: '#565a5b',
800: '#3e4244',
900: '#262b2c',
950: '#0e1315'
}
},
{
name: 'ocean',
palette: {
0: '#ffffff',
50: '#fbfcfc',
100: '#F7F9F8',
200: '#EFF3F2',
300: '#DADEDD',
400: '#B1B7B6',
500: '#828787',
600: '#5F7274',
700: '#415B61',
800: '#29444E',
900: '#183240',
950: '#0c1920'
}
},
{
name: 'light-slate',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f8fafc',
200: '#f1f5f9',
300: '#e2e8f0',
400: '#cbd5e1',
500: '#94a3b8',
600: '#64748b',
700: '#475569',
800: '#334155',
900: '#1e293b',
950: '#0f172a'
}
},
{
name: 'olive',
palette: {
0: '#ffffff',
50: '#fcfcfb',
100: '#f8f9f6',
200: '#f1f4ed',
300: '#e6eadc',
400: '#d4dfc5',
500: '#6a755e',
600: '#555d4c',
700: '#434a3d',
800: '#333930',
900: '#232824',
950: '#131614'
}
},
{
name: 'crimson',
palette: {
0: '#ffffff',
50: '#fcfbfb',
100: '#f8f5f5',
200: '#f1ebeb',
300: '#e6d9d9',
400: '#d4c3c3',
500: '#755e5e',
600: '#5d4c4c',
700: '#4a3d3d',
800: '#382f2f',
900: '#242020',
950: '#141212'
}
}
];
constructor() {
const initialState = this.loadAppState();
this.appState.set({...initialState});
this.document.documentElement.classList.add('p-dark');
if (isPlatformBrowser(this.platformId)) {
this.onPresetChange();
}
effect(() => {
const state = this.appState();
if (!this.initialized || !state) {
this.initialized = true;
return;
}
this.saveAppState(state);
this.onPresetChange();
}, {allowSignalWrites: true});
}
private loadAppState(): AppState {
if (isPlatformBrowser(this.platformId)) {
const storedState = localStorage.getItem(this.STORAGE_KEY);
if (storedState) {
return JSON.parse(storedState);
}
}
return {
preset: 'Aura',
primary: 'green',
surface: 'neutral',
};
}
private saveAppState(state: AppState): void {
if (isPlatformBrowser(this.platformId)) {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state));
}
}
private getSurfacePalette(surface: string): ColorPalette {
return this.surfaces.find(s => s.name === surface)?.palette ?? {};
}
getPresetExt(): object {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const primaryName = this.appState().primary ?? 'green';
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const color = presetPalette[primaryName] ?? {};
if (primaryName === 'noir') {
return {
semantic: {
primary: {...surfacePalette},
colorScheme: {
dark: {
primary: {
color: '{primary.50}',
contrastColor: '{primary.950}',
hoverColor: '{primary.200}',
activeColor: '{primary.300}'
},
highlight: {
background: '{primary.50}',
focusBackground: '{primary.300}',
color: '{primary.950}',
focusColor: '{primary.950}'
}
}
}
}
};
}
return {
semantic: {
primary: color,
colorScheme: {
dark: {
primary: {
color: '{primary.400}',
contrastColor: '{surface.900}',
hoverColor: '{primary.300}',
activeColor: '{primary.200}'
},
highlight: {
background: 'color-mix(in srgb, {primary.400}, transparent 84%)',
focusBackground: 'color-mix(in srgb, {primary.400}, transparent 76%)',
color: 'rgba(255,255,255,.87)',
focusColor: 'rgba(255,255,255,.87)'
}
}
}
}
};
}
onPresetChange(): void {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const preset = this.getPresetExt();
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({useDefaultOptions: true});
}
}
@@ -1,143 +0,0 @@
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, finalize, shareReplay, tap} from 'rxjs/operators';
import {API_CONFIG} from '../../config/api-config';
import {AppSettings, OidcProviderDetails} from '../model/app-settings.model';
import {AuthService} from './auth.service';
export interface PublicAppSettings {
oidcEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
}
@Injectable({providedIn: 'root'})
export class AppSettingsService {
private http = inject(HttpClient);
private injector = inject(Injector);
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/settings`;
private readonly publicApiUrl = `${API_CONFIG.BASE_URL}/api/v1/public-settings`;
private loading$: Observable<AppSettings> | null = null;
private appSettingsSubject = new BehaviorSubject<AppSettings | null>(null);
appSettings$ = this.appSettingsSubject.asObservable().pipe(
tap(state => {
if (!state && !this.loading$) {
this.loading$ = this.fetchAppSettings().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private publicLoading$: Observable<PublicAppSettings> | null = null;
private publicAppSettingsSubject = new BehaviorSubject<PublicAppSettings | null>(null);
publicAppSettings$ = this.publicAppSettingsSubject.asObservable().pipe(
tap(state => {
if (!state && !this.publicLoading$) {
this.publicLoading$ = this.fetchPublicSettings().pipe(
shareReplay(1),
finalize(() => (this.publicLoading$ = null))
);
this.publicLoading$.subscribe();
}
})
);
private fetchAppSettings(): Observable<AppSettings> {
return this.http.get<AppSettings>(this.apiUrl).pipe(
tap(settings => {
this.appSettingsSubject.next(settings);
this.syncPublicSettings(settings);
}),
catchError(err => {
console.error('Error loading app settings:', err);
this.appSettingsSubject.next(null);
throw err;
})
);
}
private fetchPublicSettings(): Observable<PublicAppSettings> {
return this.http.get<PublicAppSettings>(this.publicApiUrl).pipe(
tap(settings => this.publicAppSettingsSubject.next(settings)),
catchError(err => {
console.error('Failed to fetch public settings', err);
throw err;
})
);
}
private syncPublicSettings(appSettings: AppSettings): void {
const updatedPublicSettings: PublicAppSettings = {
oidcEnabled: appSettings.oidcEnabled,
oidcProviderDetails: appSettings.oidcProviderDetails
};
const current = this.publicAppSettingsSubject.value;
if (
!current ||
current.oidcEnabled !== updatedPublicSettings.oidcEnabled ||
JSON.stringify(current.oidcProviderDetails) !== JSON.stringify(updatedPublicSettings.oidcProviderDetails)
) {
this.publicAppSettingsSubject.next(updatedPublicSettings);
}
}
saveSettings(settings: { key: string; newValue: any }[]): Observable<void> {
const payload = settings.map(setting => ({
name: setting.key,
value: setting.newValue
}));
return this.http.put<void>(this.apiUrl, payload).pipe(
tap(() => {
const current = this.appSettingsSubject.value;
if (current) {
settings.forEach(s => (current as any)[s.key] = s.newValue);
this.appSettingsSubject.next({...current});
this.syncPublicSettings(current);
} else {
this.loading$ = this.fetchAppSettings().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
}),
catchError(err => {
console.error('Error saving settings:', err);
return of();
})
);
}
toggleOidcEnabled(enabled: boolean): Observable<void> {
const payload = [{name: 'OIDC_ENABLED', value: enabled}];
return this.http.put<void>(this.apiUrl, payload).pipe(
tap(() => {
const current = this.appSettingsSubject.value;
if (current) {
current.oidcEnabled = enabled;
this.appSettingsSubject.next({...current});
this.syncPublicSettings(current);
}
if (!enabled) {
setTimeout(() => {
const authService = this.injector.get(AuthService);
authService.clearOIDCTokens();
});
}
}),
catchError(err => {
console.error('Error toggling OIDC:', err);
return of();
})
);
}
}
@@ -0,0 +1,12 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({providedIn: 'root'})
export class AuthInitializationService {
private initialized = new BehaviorSubject<boolean>(false);
initialized$ = this.initialized.asObservable();
markAsInitialized() {
this.initialized.next(true);
}
}
@@ -0,0 +1,79 @@
import {HttpErrorResponse, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
import {inject} from '@angular/core';
import {Router} from '@angular/router';
import {catchError, filter, switchMap, take} from 'rxjs/operators';
import {BehaviorSubject, Observable, throwError} from 'rxjs';
import {AuthService} from '../../shared/service/auth.service';
import {API_CONFIG} from '../config/api-config';
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
const authService = inject(AuthService);
const router = inject(Router);
const internalToken = authService.getInternalAccessToken();
const oidcToken = authService.getOidcAccessToken();
const token = internalToken || oidcToken;
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
return next(authReq).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
return handle401Error(authService, authReq, next, router, !!internalToken);
}
return throwError(() => error);
})
);
};
let isRefreshing = false;
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
function handle401Error(authService: AuthService, request: HttpRequest<any>, next: HttpHandlerFn, router: Router, isInternal: boolean): Observable<any> {
if (!isRefreshing && isInternal) {
isRefreshing = true;
refreshTokenSubject.next(null);
return authService.internalRefreshToken().pipe(
switchMap(response => {
isRefreshing = false;
const { accessToken, refreshToken } = response;
if (accessToken && refreshToken) {
authService.saveInternalTokens(accessToken, refreshToken);
refreshTokenSubject.next(accessToken);
}
return next(request.clone({
setHeaders: { Authorization: `Bearer ${accessToken}` }
}));
}),
catchError(err => {
isRefreshing = false;
forceLogout(authService, router);
return throwError(() => err);
})
);
}
if (isRefreshing && isInternal) {
return refreshTokenSubject.pipe(
filter(token => token !== null),
take(1),
switchMap(token =>
next(request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
}))
)
);
}
forceLogout(authService, router, isInternal ? 'Session expired, please log in again.' : 'OIDC token expired, please log in again.');
return throwError(() => new Error('Authentication failed, please log in.'));
}
function forceLogout(authService: AuthService, router: Router, message?: string): void {
authService.logout();
router.navigate(['/login']);
if (message) console.warn(message);
}
@@ -1,109 +0,0 @@
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs';
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {API_CONFIG} from '../../config/api-config';
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
private rxStompService?: RxStompService;
private http = inject(HttpClient);
private injector = inject(Injector);
private oAuthService = inject(OAuthService);
private oAuthStorage = inject(OAuthStorage);
private router = inject(Router);
public tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
public token$ = this.tokenSubject.asObservable();
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.initializeWebSocketConnection();
}
})
);
}
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
}
})
);
}
saveInternalTokens(accessToken: string, refreshToken: string): void {
localStorage.setItem('accessToken_Internal', accessToken);
localStorage.setItem('refreshToken_Internal', refreshToken);
this.tokenSubject.next(accessToken);
}
getInternalAccessToken(): string | null {
return localStorage.getItem('accessToken_Internal');
}
getOidcAccessToken(): string | null {
return this.oAuthService.getIdToken();
}
getInternalRefreshToken(): string | null {
return localStorage.getItem('refreshToken_Internal');
}
clearOIDCTokens(): void {
const hasInternalTokens = this.getInternalAccessToken() || this.getInternalRefreshToken();
if (!hasInternalTokens) {
this.oAuthStorage.removeItem("access_token");
this.oAuthStorage.removeItem("refresh_token");
this.oAuthStorage.removeItem("id_token");
this.router.navigate(['/login']);
}
}
logout(): void {
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal');
this.oAuthStorage.removeItem("access_token");
this.oAuthStorage.removeItem("refresh_token");
this.oAuthStorage.removeItem("id_token");
this.tokenSubject.next(null);
this.getRxStompService().deactivate();
this.router.navigate(['/login']);
}
getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
}
initializeWebSocketConnection(): void {
const token = this.getOidcAccessToken() || this.getInternalAccessToken();
if (!token) return;
const stompService = this.getRxStompService();
const config = createRxStompConfig(this);
stompService.updateConfig(config);
stompService.activate();
}
}
export function websocketInitializer(authService: AuthService): () => void {
return () => authService.initializeWebSocketConnection();
}
@@ -1,42 +0,0 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
export interface BookNote {
id: number;
userId: number;
bookId: number;
title: string;
content: string;
createdAt: string;
updatedAt: string;
}
export interface CreateBookNoteRequest {
id?: number;
bookId: number;
title: string;
content: string;
}
@Injectable({
providedIn: 'root'
})
export class BookNoteService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/book-notes`;
private readonly http = inject(HttpClient);
getNotesForBook(bookId: number): Observable<BookNote[]> {
return this.http.get<BookNote[]>(`${this.url}/book/${bookId}`);
}
createOrUpdateNote(request: CreateBookNoteRequest): Observable<BookNote> {
return this.http.post<BookNote>(this.url, request);
}
deleteNote(noteId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${noteId}`);
}
}
@@ -0,0 +1,80 @@
import {inject, Injectable} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {GithubSupportDialog} from '../../shared/components/github-support-dialog/github-support-dialog';
import {LibraryCreatorComponent} from '../../features/library-creator/library-creator.component';
import {BookUploaderComponent} from '../../shared/components/book-uploader/book-uploader.component';
import {UserProfileDialogComponent} from '../../features/settings/user-profile-dialog/user-profile-dialog.component';
import {MagicShelfComponent} from '../../features/magic-shelf/component/magic-shelf-component';
@Injectable({
providedIn: 'root',
})
export class DialogLauncherService {
dialogService = inject(DialogService);
open(options: { component: any; header: string; top?: string; width?: string }): DynamicDialogRef {
const isMobile = window.innerWidth <= 768;
const {component, header, top, width} = options;
return this.dialogService.open(component, {
header,
modal: true,
closable: true,
contentStyle: {
overflowY: 'hidden',
},
style: {
position: 'absolute',
...(top ? {top} : {}),
...(isMobile
? {
width: '90vw',
maxWidth: '90vw',
minWidth: '90vw',
}
: width
? {width}
: {}),
},
});
}
openGithubSupportDialog(): void {
this.open({
component: GithubSupportDialog,
header: 'Support Booklore',
top: '15%'
});
}
openLibraryCreatorDialog(): void {
this.open({
component: LibraryCreatorComponent,
header: 'Create New Library',
top: '15%'
});
}
openFileUploadDialog(): void {
this.open({
component: BookUploaderComponent,
header: 'Book Uploader',
top: '10%'
});
}
openUserProfileDialog(): void {
this.open({
component: UserProfileDialogComponent,
header: 'User Profile Information',
top: '10%'
});
}
openMagicShelfDialog(): void {
this.open({
component: MagicShelfComponent,
header: 'Magic Shelf Creator'
});
}
}
@@ -1,18 +0,0 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private loadingSubject = new BehaviorSubject<boolean>(false);
loading$ = this.loadingSubject.asObservable();
show(): void {
this.loadingSubject.next(true);
}
hide(): void {
this.loadingSubject.next(false);
}
}
@@ -1,25 +0,0 @@
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class LocalStorageService {
get<T>(key: string): T | null {
try {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) as T : null;
} catch {
return null;
}
}
set<T>(key: string, value: T): void {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
}
}
remove(key: string): void {
localStorage.removeItem(key);
}
}
@@ -1,87 +0,0 @@
import {inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subject, Subscription} from 'rxjs';
import {MetadataBatchProgressNotification} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../book/service/metadata-task';
import {UserService} from '../../settings/user-management/user.service';
import {filter, take} from 'rxjs/operators';
@Injectable({providedIn: 'root'})
export class MetadataProgressService implements OnDestroy {
private progressMap = new Map<string, BehaviorSubject<MetadataBatchProgressNotification>>();
private progressUpdatesSubject = new Subject<MetadataBatchProgressNotification>();
progressUpdates$ = this.progressUpdatesSubject.asObservable();
private activeTasksSubject = new BehaviorSubject<{ [taskId: string]: MetadataBatchProgressNotification }>({});
activeTasks$ = this.activeTasksSubject.asObservable();
private metadataTaskService = inject(MetadataTaskService);
private userService = inject(UserService);
private subscriptions = new Subscription();
constructor() {
const sub = this.userService.userState$
.pipe(
filter(userState => !!userState?.user),
take(1)
)
.subscribe(userState => {
if (!this.hasMetadataPermissions(userState.user)) {
return;
}
const activeTasksSub = this.metadataTaskService.getActiveTasks().subscribe({
next: (tasks) => this.initializeActiveTasks(tasks),
error: (err) => console.warn('Failed to fetch active metadata tasks:', err)
});
this.subscriptions.add(activeTasksSub);
});
this.subscriptions.add(sub);
}
handleIncomingProgress(progress: MetadataBatchProgressNotification): void {
const {taskId} = progress;
if (!this.progressMap.has(taskId)) {
this.progressMap.set(taskId, new BehaviorSubject(progress));
} else {
this.progressMap.get(taskId)!.next(progress);
}
this.progressUpdatesSubject.next(progress);
this.activeTasksSubject.next(this.getActiveTasks());
}
clearTask(taskId: string): void {
this.progressMap.delete(taskId);
this.activeTasksSubject.next(this.getActiveTasks());
}
getActiveTasks(): { [taskId: string]: MetadataBatchProgressNotification } {
const result: { [taskId: string]: MetadataBatchProgressNotification } = {};
this.progressMap.forEach((subject, taskId) => {
result[taskId] = subject.getValue();
});
return result;
}
private hasMetadataPermissions(user: any): boolean {
return !!(user?.permissions?.admin || user?.permissions?.canEditMetadata);
}
private initializeActiveTasks(tasks: MetadataBatchProgressNotification[]): void {
for (const task of tasks) {
this.progressMap.set(task.taskId, new BehaviorSubject(task));
this.progressUpdatesSubject.next(task);
}
this.activeTasksSubject.next(this.getActiveTasks());
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
this.progressMap.forEach(subject => subject.complete());
this.progressUpdatesSubject.complete();
this.activeTasksSubject.complete();
}
}
@@ -1,60 +0,0 @@
import {Injectable, inject} from '@angular/core';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SettingsHelperService {
private readonly appSettingsService = inject(AppSettingsService);
private readonly messageService = inject(MessageService);
saveSetting(key: string, value: unknown): Observable<void> {
const observable = this.appSettingsService.saveSettings([{key, newValue: value}]);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
console.error('Failed to save setting:', error);
this.showErrorMessage();
}
});
return observable;
}
saveMultipleSettings(settings: { key: string, newValue: unknown }[]): Observable<void> {
const observable = this.appSettingsService.saveSettings(settings);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
console.error('Failed to save settings:', error);
this.showErrorMessage();
}
});
return observable;
}
private showSuccessMessage(): void {
this.messageService.add({
severity: 'success',
summary: 'Settings Saved',
detail: 'The settings were successfully saved!'
});
}
private showErrorMessage(): void {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'There was an error saving the settings.'
});
}
showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
this.messageService.add({severity, summary, detail});
}
}
@@ -1,28 +0,0 @@
import {Injectable, inject} from '@angular/core';
import {AuthService} from './auth.service';
import {UserService} from '../../settings/user-management/user.service';
import {filter, catchError} from 'rxjs/operators';
import {of} from 'rxjs';
import {OAuthService} from 'angular-oauth2-oidc';
@Injectable({providedIn: 'root'})
export class StartupService {
private authService = inject(AuthService);
private userService = inject(UserService);
load(): Promise<void> {
this.authService.token$
.pipe(filter(t => !!t))
.subscribe(() => {
this.userService.getMyself()
.pipe(catchError(() => of(null)))
.subscribe(user => {
if (user) {
this.userService.setInitialUser(user);
}
});
});
return Promise.resolve();
}
}
@@ -1,26 +0,0 @@
import {inject, Injectable} from '@angular/core';
import {MessageService} from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class ToastService {
private messageService = inject(MessageService);
showSuccess(summary: string, detail: string) {
this.messageService.add({ severity: 'success', summary, detail });
}
showError(summary: string, detail: string) {
this.messageService.add({ severity: 'error', summary, detail });
}
showInfo(summary: string, detail: string) {
this.messageService.add({ severity: 'info', summary, detail });
}
showWarning(summary: string, detail: string) {
this.messageService.add({ severity: 'warn', summary, detail });
}
}
@@ -1,34 +0,0 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
export interface AppVersion {
current: string;
latest: string;
}
export interface ReleaseNote {
version: string;
name: string;
changelog: string;
url: string;
publishedAt: string;
}
@Injectable({
providedIn: 'root'
})
export class VersionService {
private versionUrl = `${API_CONFIG.BASE_URL}/api/v1/version`;
constructor(private http: HttpClient) {}
getVersion(): Observable<AppVersion> {
return this.http.get<AppVersion>(this.versionUrl);
}
getChangelog(): Observable<ReleaseNote[]> {
return this.http.get<ReleaseNote[]>(`${this.versionUrl}/changelog`);
}
}
@@ -1,30 +0,0 @@
import { inject, Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, map, catchError, of } from 'rxjs';
import { API_CONFIG } from '../../config/api-config';
@Injectable({
providedIn: 'root',
})
export class LoginGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean> {
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(res => {
if (!res.data) {
this.router.navigate(['/setup']);
return false;
}
return true;
}),
catchError(() => {
this.router.navigate(['/setup']);
return of(false);
})
);
}
}
@@ -1,28 +0,0 @@
import {inject, Injectable} from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { Observable, map } from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
@Injectable({
providedIn: 'root',
})
export class SetupRedirectGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean> {
return this.http.get<{ data: boolean }>(`${this.url}/status`).pipe(
map(res => {
if (!res.data) {
this.router.navigate(['/setup']);
} else {
this.router.navigate(['/dashboard']);
}
return false;
})
);
}
}
@@ -1,113 +0,0 @@
<div class="flex items-center justify-center min-h-screen min-w-[100vw] overflow-hidden"
style="background: linear-gradient(60deg, var(--primary-color) 0%, #1e3a8a 100%);">
<div class="flex flex-col items-center justify-center -mt-48">
<div style="border-radius: 56px; padding: 0.3rem; background: linear-gradient(180deg, var(--primary-color) 10%, rgba(33, 150, 243, 0) 30%)">
<div class="w-full bg-surface-900 py-16 px-8 sm:px-16" style="border-radius: 53px">
<div class="text-center mb-8">
<svg class="mb-8 w-16 h-16 mx-auto" viewBox="0 0 126 126" fill="var(--primary-color)" xmlns="http://www.w3.org/2000/svg">
<path
d="M59 4.79297C71.5051 11.5557 80 24.7854 80 40C80 40.5959 79.987 41.1888 79.9609 41.7783C79.8609 44.0406 81.7355 46 84 46C106.091 46 124 63.9086 124 86C124 108.091 106.091 126 84 126H10C4.47715 126 0 121.523 0 116V39.0068L0.0126953 38.9941C0.357624 25.0252 7.86506 12.8347 19 5.95215V63.832C19 64.8345 20.0676 65.4391 20.9121 64.9902L21.0771 64.8867L38.2227 52.3428C38.6819 52.0068 39.3064 52.0068 39.7656 52.3428L56.9229 64.8945L57.0879 64.998C57.9324 65.447 59 64.8423 59 63.8398V4.79297Z"/>
<path
d="M40 0C43.8745 0 47.6199 0.552381 51.1631 1.58008V50.9697L44.3926 46.0176L44.0879 45.8037C40.9061 43.6679 36.7098 43.7393 33.5957 46.0176L26.8369 50.9619V2.21875C30.9593 0.782634 35.3881 0 40 0Z"
fill="white"/>
</svg>
<div class="text-3xl font-medium mb-4">Welcome to Booklore</div>
<span class="text-xl">Setup Initial Admin Account</span>
</div>
<form class="flex flex-col gap-4" [formGroup]="setupForm" (ngSubmit)="onSubmit()">
<div class="flex flex-col gap-2">
<label for="username" class="text-lg font-medium">Username</label>
<input
pInputText
id="username"
name="username"
required
formControlName="username"
placeholder="Enter your username"
class="w-full md:w-[30rem]"
/>
@if (setupForm.get('username')?.invalid && setupForm.get('username')?.touched) {
<small class="text-red-500">
Username is required.
</small>
}
</div>
<div class="flex flex-col gap-2">
<label for="name" class="text-lg font-medium">Name</label>
<input
pInputText
id="name"
name="name"
required
formControlName="name"
placeholder="Enter your full name"
class="w-full md:w-[30rem]"
/>
@if (setupForm.get('name')?.invalid && setupForm.get('name')?.touched) {
<small class="text-red-500">
Name is required.
</small>
}
</div>
<div class="flex flex-col gap-2">
<label for="email" class="text-lg font-medium">Email</label>
<input
pInputText
id="email"
name="email"
required
formControlName="email"
placeholder="Enter your email"
class="w-full md:w-[30rem]"
/>
@if (setupForm.get('email')?.invalid && setupForm.get('email')?.touched) {
<small class="text-red-500">
Valid email is required.
</small>
}
</div>
<div class="flex flex-col gap-2">
<label for="password" class="text-lg font-medium">Password</label>
<input
pInputText
id="password"
name="password"
required
formControlName="password"
placeholder="Enter new password"
class="w-full md:w-[30rem]"
/>
@if (setupForm.get('password')?.invalid && setupForm.get('password')?.touched) {
<small class="text-red-500">
Minimum 6 characters required.
</small>
}
</div>
<div class="flex flex-col gap-3 mt-4">
<p-button
fluid
type="submit"
[label]="loading ? 'Creating…' : 'Create Admin Account'"
[disabled]="loading || setupForm.invalid"
icon="pi pi-user-plus"
>
</p-button>
@if (error) {
<p-message severity="error" text="{{ error }}"></p-message>
}
@if (success) {
<p-message severity="success" text="Admin account created! Redirecting…"></p-message>
}
</div>
</form>
</div>
</div>
</div>
</div>
@@ -1,58 +0,0 @@
import {Component} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {SetupService} from './setup.service';
import {InputText} from 'primeng/inputtext';
import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
@Component({
selector: 'app-setup',
templateUrl: './setup.component.html',
styleUrls: ['./setup.component.scss'],
standalone: true,
imports: [
ReactiveFormsModule,
InputText,
Button,
Message
]
})
export class SetupComponent {
setupForm: FormGroup;
loading = false;
error: string | null = null;
success = false;
constructor(
private fb: FormBuilder,
private setupService: SetupService,
private router: Router
) {
this.setupForm = this.fb.group({
name: ['', [Validators.required]],
username: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]],
});
}
onSubmit(): void {
if (this.setupForm.invalid) return;
this.loading = true;
this.error = null;
this.setupService.createAdmin(this.setupForm.value).subscribe({
next: () => {
this.success = true;
setTimeout(() => this.router.navigate(['/login']), 1500);
},
error: (err) => {
this.loading = false;
this.error =
err?.error?.message || 'Failed to create admin user. Try again.';
},
});
}
}
@@ -1,32 +0,0 @@
import {inject, Injectable} from '@angular/core';
import {
CanActivate,
Router,
UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
import {API_CONFIG} from '../../config/api-config';
@Injectable({
providedIn: 'root'
})
export class SetupGuard implements CanActivate {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
private router = inject(Router);
canActivate(): Observable<boolean | UrlTree> {
return this.http.get<any>(`${this.url}/status`).pipe(
map(response => {
if (response?.data === true) {
return this.router.createUrlTree(['/login']);
}
return true;
})
);
}
}
@@ -1,21 +0,0 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
export interface SetupPayload {
email: string;
password: string;
}
@Injectable({providedIn: 'root'})
export class SetupService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/setup`;
private http = inject(HttpClient);
createAdmin(payload: SetupPayload): Observable<void> {
return this.http.post<void>(this.url, payload);
}
}