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
@@ -0,0 +1,141 @@
@if ((libraryState$ | async)?.libraries; as libraries) {
<div
class="flex flex-col gap-8 p-4 items-center justify-center w-full max-w-[700px]">
<div class="flex flex-col items-center gap-2 w-full">
<label class="text-sm text-stone-400">Upload Destination</label>
<p-selectbutton
[options]="stateOptions"
[(ngModel)]="value"
[allowEmpty]="false"
optionLabel="label"
optionValue="value">
</p-selectbutton>
</div>
@if (value === 'library') {
<p-select
[options]="libraries"
optionLabel="name"
placeholder="Select Library"
[(ngModel)]="selectedLibrary"
class="w-full"></p-select>
<p-select
[options]="selectedLibrary?.paths"
optionLabel="path"
placeholder="Select Subpath"
[(ngModel)]="selectedPath"
[disabled]="!selectedLibrary"
class="w-full"></p-select>
}
<p-fileupload class="w-full" name="file"
[maxFileSize]="maxFileSizeBytes"
[customUpload]="true"
[multiple]="true" accept=".pdf,.epub,.cbz,.cbr,.cb7"
(onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)"
[disabled]="value === 'library' ? (!selectedLibrary || !selectedPath) : false">
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
<div class="flex flex-col items-center justify-center flex-1 gap-4">
<div class="flex gap-4">
<p-button
(onClick)="choose($event, chooseCallback)"
icon="pi pi-images"
[rounded]="true"
[outlined]="true"
[disabled]="isChooseDisabled()"
pTooltip="Choose files to upload"
tooltipPosition="top"/>
<p-button
(onClick)="uploadEvent(uploadCallback)"
icon="pi pi-cloud-upload"
[rounded]="true"
[outlined]="true"
severity="success"
[disabled]="isUploadDisabled()"
pTooltip="Start uploading selected files"
tooltipPosition="top"/>
<p-button
(onClick)="onClear(clearCallback)"
icon="pi pi-times"
[rounded]="true"
[outlined]="true"
severity="danger"
[disabled]="!filesPresent() || isUploading"
pTooltip="Clear selected files"
tooltipPosition="top"/>
</div>
<div>Click the upload icon to upload the files.</div>
</div>
</ng-template>
<ng-template #content let-files let-removeFileCallback="removeFileCallback">
<div class="flex flex-col gap-8 px-4">
@if (files?.length > 0) {
<div>
<div class="max-h-96 max-w-[22rem] md:max-w-none overflow-y-auto pr-2">
<div class="flex flex-wrap">
@for (uploadFile of this.files; track uploadFile; let i = $index) {
<div class="flex justify-between items-center w-full gap-4">
<div class="flex items-center gap-4 overflow-hidden flex-1">
<p-badge [value]="uploadFile.status === 'Pending' ? 'Ready to Upload' : uploadFile.status" [severity]="getBadgeSeverity(uploadFile.status)"
class="shrink-0"/>
<span class="font-semibold text-ellipsis whitespace-nowrap overflow-hidden flex-1">
{{ uploadFile.file.name }}
</span>
<div class="shrink-0">{{ formatSize(uploadFile.file.size) }}</div>
</div>
@switch (uploadFile.status) {
@case ('Pending') {
<p-button
icon="pi pi-times"
(click)="onRemoveTemplatingFile($event, uploadFile.file, removeFileCallback, i)"
severity="danger"
[text]="true"/>
}
@case ('Uploading') {
<i
class="pi pi-spin pi-spinner p-3"
style="color: slateblue"
pTooltip="Uploading"
tooltipPosition="top">
</i>
}
@case ('Uploaded') {
<i
class="pi pi-check p-3"
style="color: green"
pTooltip="Uploaded"
tooltipPosition="top">
</i>
}
@case ('Failed') {
<i
class="pi pi-exclamation-triangle p-3"
style="color: darkred"
pTooltip="{{ uploadFile.errorMessage || 'Upload failed' }}"
tooltipPosition="top">
</i>
}
}
</div>
}
</div>
</div>
</div>
}
</div>
</ng-template>
<ng-template #file></ng-template>
<ng-template #empty>
<div class="flex items-center justify-center flex-col text-center">
<i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl"></i>
<p class="mt-6 mb-2">Drag and drop files here to upload.</p>
<p class="mt-2 mb-2">
Only <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, and <strong>.cb7</strong> files are supported (max size: 100 MB per
file).
</p>
</div>
</ng-template>
</p-fileupload>
</div>
}
@@ -0,0 +1,3 @@
:host ::ng-deep .p-fileupload-content p-progressbar {
display: none !important;
}
@@ -0,0 +1,226 @@
import {Component, inject, OnInit} from '@angular/core';
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
import {Button} from 'primeng/button';
import {AsyncPipe} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {MessageService} from 'primeng/api';
import {Select} from 'primeng/select';
import {Badge} from 'primeng/badge';
import {LibraryService} from '../../../features/book/service/library.service';
import {Library, LibraryPath} from '../../../features/book/model/library.model';
import {LibraryState} from '../../../features/book/model/state/library-state.model';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../core/config/api-config';
import {Book} from '../../../features/book/model/book.model';
import {HttpClient} from '@angular/common/http';
import {Tooltip} from 'primeng/tooltip';
import {AppSettingsService} from '../../service/app-settings.service';
import {filter, take} from 'rxjs/operators';
import {AppSettings} from '../../model/app-settings.model';
import {SelectButton} from 'primeng/selectbutton';
interface UploadingFile {
file: File;
status: 'Pending' | 'Uploading' | 'Uploaded' | 'Failed';
errorMessage?: string;
}
@Component({
selector: 'app-book-uploader',
standalone: true,
imports: [
FileUpload,
Button,
AsyncPipe,
FormsModule,
Select,
Badge,
Tooltip,
SelectButton
],
templateUrl: './book-uploader.component.html',
styleUrl: './book-uploader.component.scss'
})
export class BookUploaderComponent implements OnInit {
files: UploadingFile[] = [];
isUploading: boolean = false;
_selectedLibrary: Library | null = null;
selectedPath: LibraryPath | null = null;
private readonly libraryService = inject(LibraryService);
private readonly messageService = inject(MessageService);
private readonly appSettingsService = inject(AppSettingsService);
private readonly http = inject(HttpClient);
readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
maxFileSizeBytes?: number;
stateOptions = [
{label: 'Library', value: 'library'},
{label: 'Bookdrop', value: 'bookdrop'}
];
value = 'library';
ngOnInit(): void {
this.appSettings$
.pipe(
filter(settings => settings != null),
take(1)
)
.subscribe(settings => {
this.maxFileSizeBytes = (settings?.maxFileUploadSizeInMb ?? 100) * 1024 * 1024;
});
this.libraryState$.subscribe(state => {
if (state?.libraries?.length !== 1 || this.selectedLibrary) {
return;
}
this.selectedLibrary = state.libraries[0];
});
}
get selectedLibrary(): Library | null {
return this._selectedLibrary;
}
set selectedLibrary(library: Library | null) {
this._selectedLibrary = library;
if(library?.paths?.length === 1) {
this.selectedPath = library.paths[0];
}
}
hasPendingFiles(): boolean {
return this.files.some(f => f.status === 'Pending');
}
filesPresent(): boolean {
return this.files.length > 0;
}
choose(_event: any, chooseCallback: () => void): void {
chooseCallback();
}
onClear(clearCallback: () => void): void {
clearCallback();
this.files = [];
}
onFilesSelect(event: FileSelectEvent): void {
const newFiles = event.currentFiles;
for (const file of newFiles) {
const exists = this.files.some(f => f.file.name === file.name && f.file.size === file.size);
if (!exists) {
this.files.unshift({file, status: 'Pending'});
}
}
}
onRemoveTemplatingFile(_event: any, _file: File, removeFileCallback: (event: any, index: number) => void, index: number): void {
removeFileCallback(_event, index);
}
uploadEvent(uploadCallback: () => void): void {
uploadCallback();
}
uploadFiles(event: FileUploadHandlerEvent): void {
if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
this.messageService.add({
severity: 'warn',
summary: 'Missing Data',
detail: 'Please select a library and path before uploading.',
life: 4000
});
return;
}
const filesToUpload = this.files.filter(f => f.status === 'Pending');
if (filesToUpload.length === 0) return;
this.isUploading = true;
this.uploadBatch(filesToUpload, 0, 5);
}
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number): void {
const batch = files.slice(startIndex, startIndex + batchSize);
if (batch.length === 0) {
this.isUploading = false;
return;
}
let pending = batch.length;
for (const uploadFile of batch) {
uploadFile.status = 'Uploading';
const formData = new FormData();
formData.append('file', uploadFile.file);
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);
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
} else {
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload/bookdrop`;
}
this.http.post<Book>(uploadUrl, formData).subscribe({
next: () => {
uploadFile.status = 'Uploaded';
if (--pending === 0) {
this.uploadBatch(files, startIndex + batchSize, batchSize);
}
},
error: (err) => {
uploadFile.status = 'Failed';
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);
}
}
});
}
}
isChooseDisabled(): boolean {
if (this.value === 'bookdrop') {
return this.isUploading;
}
return !this.selectedLibrary || !this.selectedPath || this.isUploading;
}
isUploadDisabled(): boolean {
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
}
formatSize(bytes: number): string {
const k = 1024;
const dm = 2;
if (bytes < k) return `${bytes} B`;
if (bytes < k * k) return `${(bytes / k).toFixed(dm)} KB`;
return `${(bytes / (k * k)).toFixed(dm)} MB`;
}
getBadgeSeverity(status: UploadingFile['status']): 'info' | 'warn' | 'success' | 'danger' {
switch (status) {
case 'Pending':
return 'warn';
case 'Uploading':
return 'info';
case 'Uploaded':
return 'success';
case 'Failed':
return 'danger';
default:
return 'info';
}
}
}
@@ -0,0 +1,37 @@
<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>
@@ -0,0 +1,28 @@
.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;
}
@@ -0,0 +1,81 @@
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 '../../../features/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';
}
}
@@ -0,0 +1,35 @@
<div class="h-[50rem] md:h-[50rem] md:w-[50rem] w-[25rem] flex flex-col">
<div class="mb-6 flex items-center gap-4">
<input
id="disabled-input"
type="text"
pInputText
[value]="selectedProductName"
[disabled]="true"
class="w-full p-2 text-base"
/>
<p-button label="Select" severity="success" (click)="onSelect()"></p-button>
</div>
<p-table [value]="paths" styleClass="responsive-table" class="flex-grow overflow-y-auto">
<ng-template pTemplate="header">
<tr>
<th class="w-[1%]"></th>
<th class="w-[99%]">Name</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-product>
<tr class="cursor-pointer hover:bg-white/10" (click)="onRowClick(product)">
<td>
@if (product === '...') {
<i class="pi pi-arrow-up"></i>
}
@if (product !== '...') {
<i class="pi pi-folder-open"></i>
}
</td>
<td>{{ product }}</td>
</tr>
</ng-template>
</p-table>
</div>
@@ -0,0 +1,8 @@
.responsive-table {
min-width: 50rem;
@media (max-width: 768px) {
min-width: 100% !important;
width: 100% !important;
}
}
@@ -0,0 +1,62 @@
import {Component, inject, OnInit} from '@angular/core';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UtilityService} from './utility.service';
import {Button} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {InputText} from 'primeng/inputtext';
@Component({
selector: 'app-directory-picker-v2',
standalone: true,
templateUrl: './directory-picker.component.html',
imports: [
Button,
TableModule,
InputText
],
styleUrls: ['./directory-picker.component.scss']
})
export class DirectoryPickerComponent implements OnInit {
value: any;
paths: string[] = ['...'];
selectedProductName: string = '';
private utilityService = inject(UtilityService);
private dynamicDialogRef = inject(DynamicDialogRef);
ngOnInit() {
const initialPath = '/';
this.getFolders(initialPath);
}
getFolders(path: string): void {
this.utilityService.getFolders(path).subscribe(
(folders: string[]) => {
this.paths = ['...', ...folders];
},
(error) => {
console.error('Error fetching folders:', error);
}
);
}
onRowClick(path: string): void {
if (path === '...') {
if (this.selectedProductName === '' || this.selectedProductName === '/') {
this.getFolders('/');
} else {
const result = this.selectedProductName.substring(0, this.selectedProductName.lastIndexOf('/')) || '/';
this.selectedProductName = result;
this.getFolders(result);
}
} else {
this.selectedProductName = path;
this.getFolders(path);
}
}
onSelect(): void {
this.dynamicDialogRef.close(this.selectedProductName);
}
}
@@ -0,0 +1,19 @@
import {inject, Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {API_CONFIG} from '../../../core/config/api-config';
@Injectable({
providedIn: 'root'
})
export class UtilityService {
private pathUrl = `${API_CONFIG.BASE_URL}/api/v1/path`;
private http = inject(HttpClient);
getFolders(path: string): Observable<string[]> {
const params = new HttpParams().set('path', path);
return this.http.get<string[]>(this.pathUrl, {params});
}
}
@@ -0,0 +1,84 @@
<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>
@@ -0,0 +1,235 @@
.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;
}
}
@@ -0,0 +1,86 @@
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 '../../../websocket/model/duplicate-file-notification.model';
import {DuplicateFileService} from '../../../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();
}
}
@@ -0,0 +1,22 @@
@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>
}
}
@@ -0,0 +1,10 @@
.duplicate-files-content {
max-height: 500px;
overflow: hidden;
}
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
@@ -0,0 +1,80 @@
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 '../../websocket/duplicate-file.service';
import {DuplicateFileNotification} from '../../websocket/model/duplicate-file-notification.model';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DuplicateFilesDialogComponent} from './duplicate-files-dialog/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();
}
}
}
@@ -0,0 +1 @@
<p>empty works!</p>
@@ -0,0 +1,11 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-empty',
imports: [],
templateUrl: './empty.component.html',
styleUrl: './empty.component.scss'
})
export class EmptyComponent {
}
@@ -0,0 +1,162 @@
<div class="p-fluid px-4 py-2 rounded-xl flex flex-col h-full">
<div class="px-4 mx-2 mb-4 py-3 rounded-lg border border-[var(--border-color)] transition-all">
<p class="text-[var(--primary-color)] font-semibold mb-1">
File Organization Preview
</p>
<div class="text-sm text-gray-300 space-y-3">
<p>
Your files will be automatically renamed, organized, and can be moved between libraries based on your preferences.
Check the preview below to see how your files will look, select target libraries if needed, then click <span class="font-semibold text-green-400">Move Files</span> to organize them.
</p>
<p>
<i class="pi pi-lightbulb text-blue-400 mr-1"></i>
<span class="text-blue-300">Want to change how files are named? Go to <strong>Settings → File Naming Pattern</strong>. Each library can have its own naming pattern!</span>
</p>
<p class="text-yellow-500 font-medium flex items-center gap-2">
<i class="pi pi-exclamation-triangle text-yellow-400"></i>
This will actually move and rename files on your computer across different library folders. Make sure you're happy with the preview first!
</p>
</div>
</div>
<div class="flex gap-4 mb-4 px-2 items-center w-full">
<div class="flex-1">
<div class="flex items-center justify-between cursor-pointer" (click)="togglePatternsCollapsed()">
<p-button
outlined
[icon]="patternsCollapsed ? 'pi pi-chevron-right' : 'pi pi-chevron-down'"
iconPos="right"
size="small"
severity="info"
[label]="patternsCollapsed ? 'Show Naming Rules' : 'Hide Naming Rules'">
</p-button>
</div>
@if (!patternsCollapsed) {
<div class="space-y-2 mt-2">
@for (pattern of libraryPatterns; track pattern.libraryId) {
<div class="p-3 border border-zinc-700 rounded-lg bg-zinc-800">
<div class="flex justify-between items-start">
<div class="flex-1">
<p class="text-xs text-gray-400 mb-1">Library: {{ pattern.libraryName }}</p>
<code class="text-[var(--primary-color)] font-mono text-sm">{{ pattern.pattern || 'No pattern available' }}</code>
<p class="text-xs text-gray-400 mt-1">Source: {{ pattern.source }}</p>
</div>
<span class="text-xs bg-blue-600 text-white px-2 py-1 rounded ml-2">{{ pattern.bookCount }} book{{ pattern.bookCount > 1 ? 's' : '' }}</span>
</div>
</div>
}
</div>
}
</div>
</div>
<div class="flex gap-4 mb-4 px-2 items-center">
<div class="flex items-center gap-3">
<label class="text-sm font-medium text-gray-300">Set all files to:</label>
<p-select
[options]="availableLibraries"
[(ngModel)]="defaultTargetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select default library"
(onChange)="onDefaultLibraryChange()"
class="min-w-[200px]"
size="small"
appendTo="body"
></p-select>
</div>
</div>
<div class="flex-grow overflow-y-auto">
<p-table
[value]="filePreviews"
[responsiveLayout]="'scroll'"
class="block min-w-full"
>
<ng-template pTemplate="header">
<tr>
<th>ID</th>
<th>Current Path</th>
<th>Target Library</th>
<th></th>
<th>New Path</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-preview let-i="rowIndex">
<tr>
<td class="text-center">{{ preview.bookId }}</td>
<td class="w-auto">
<p>
<span class="text-gray-400 select-none">{{ preview.currentLibraryName }}/</span><span class="text-gray-200">{{ preview.relativeOriginalPath }}</span>
</p>
</td>
<td class="w-auto">
<p-select
[options]="availableLibraries"
[(ngModel)]="preview.targetLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select Library"
(onChange)="onLibraryChange(preview)"
[disabled]="preview.isMoved"
class="w-full"
appendTo="body"
size="small"
></p-select>
</td>
<td class="w-auto text-[var(--primary-color)] text-center">→</td>
<td class="w-auto">
<p>
<span class="text-gray-400 select-none">{{ preview.targetLibraryName }}/</span><span class="text-gray-200">{{ preview.relativeNewPath }}</span>
</p>
</td>
<td class="w-auto text-center">
@if (preview.isMoved) {
<i class="pi pi-check-circle text-green-600"></i>
}
</td>
</tr>
</ng-template>
</p-table>
</div>
<p-divider></p-divider>
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4 pt-4">
@if (movedFileCount > 0) {
<span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none">
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
<i
class="pi pi-check-circle ml-2 text-green-500 animate-bounce"
style="animation-duration: 1.5s;"
aria-label="Success"
role="img"
></i>
</span>
}
@if (movedFileCount === 0) {
<p-button
[label]="loading ? 'Moving...' : 'Move Files'"
[icon]="loading ? 'pi pi-spin pi-spinner' : 'pi pi-arrows-h'"
severity="success"
(click)="saveChanges()"
[disabled]="loading || filePreviews.length === 0"
></p-button>
<p-button
label="Cancel"
icon="pi pi-times"
severity="danger"
(click)="cancel()"
></p-button>
} @else {
<p-button
label="Close"
icon="pi pi-times"
severity="success"
(click)="cancel()"
></p-button>
}
</div>
</div>
@@ -0,0 +1,3 @@
:host ::ng-deep .p-datatable-tbody > tr > td {
padding: 0.5rem 1rem !important;
}
@@ -0,0 +1,321 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {TableModule} from 'primeng/table';
import {Divider} from 'primeng/divider';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {MessageService} from 'primeng/api';
import {filter, take, takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {BookService} from '../../../features/book/service/book.service';
import {Book} from '../../../features/book/model/book.model';
import {FileMoveRequest, FileOperationsService} from '../../service/file-operations-service';
import {LibraryService} from "../../../features/book/service/library.service";
import {AppSettingsService} from '../../service/app-settings.service';
import {Select} from 'primeng/select';
interface FilePreview {
bookId: number;
originalPath: string;
relativeOriginalPath: string;
currentLibraryId: number | null;
currentLibraryName: string;
targetLibraryId: number | null;
targetLibraryName: string;
newPath: string;
relativeNewPath: string;
isMoved?: boolean;
}
@Component({
selector: 'app-file-mover-component',
standalone: true,
imports: [Button, FormsModule, TableModule, Divider, Select],
templateUrl: './file-mover-component.html',
styleUrl: './file-mover-component.scss'
})
export class FileMoverComponent implements OnDestroy {
private config = inject(DynamicDialogConfig);
private ref = inject(DynamicDialogRef);
private bookService = inject(BookService);
private libraryService = inject(LibraryService);
private fileOperationsService = inject(FileOperationsService);
private messageService = inject(MessageService);
private appSettingsService = inject(AppSettingsService);
private destroy$ = new Subject<void>();
libraryPatterns: {
libraryId: number | null;
libraryName: string;
pattern: string;
source: string;
bookCount: number;
}[] = [];
defaultMovePattern = '';
loading = false;
patternsCollapsed = false;
bookIds: Set<number> = new Set();
books: Book[] = [];
availableLibraries: { id: number | null; name: string }[] = [];
filePreviews: FilePreview[] = [];
defaultTargetLibraryId: number | null = null;
constructor() {
this.bookIds = new Set(this.config.data?.bookIds ?? []);
this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]);
this.loadAvailableLibraries();
this.loadDefaultPattern();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private loadDefaultPattern(): void {
this.appSettingsService.appSettings$.pipe(
filter(settings => settings != null),
take(1),
takeUntil(this.destroy$)
).subscribe(settings => {
this.defaultMovePattern = settings?.uploadPattern || '';
this.loadLibraryPatterns();
});
}
private loadLibraryPatterns(): void {
this.libraryService.libraryState$.pipe(
filter(state => state.loaded && state.libraries != null),
take(1),
takeUntil(this.destroy$)
).subscribe(state => {
const booksByLibrary = new Map<number | null, Book[]>();
this.books.forEach(book => {
const libraryId =
book.libraryId ??
book.libraryPath?.id ??
(book as any).library?.id ??
null;
if (!booksByLibrary.has(libraryId)) {
booksByLibrary.set(libraryId, []);
}
booksByLibrary.get(libraryId)!.push(book);
});
this.libraryPatterns = Array.from(booksByLibrary.entries()).map(([libraryId, books]) => {
let libraryName = 'Unknown Library';
let pattern = this.defaultMovePattern;
let source = 'App Default';
if (libraryId) {
const library = state.libraries?.find(lib => lib.id === libraryId);
if (library) {
libraryName = library.name;
if (library.fileNamingPattern) {
pattern = library.fileNamingPattern;
source = 'Library Setting';
}
}
}
return {
libraryId,
libraryName,
pattern,
source,
bookCount: books.length
};
});
this.applyPattern();
});
}
private loadAvailableLibraries(): void {
this.libraryService.libraryState$.pipe(
filter(state => state.loaded && state.libraries != null),
take(1),
takeUntil(this.destroy$)
).subscribe(state => {
this.availableLibraries = state.libraries?.map(lib => ({id: lib.id ?? null, name: lib.name})) || [];
});
}
applyPattern(): void {
this.filePreviews = this.books.map(book => {
const fileName = book.fileName ?? '';
const fileSubPath = book.fileSubPath ? `${book.fileSubPath.replace(/\/+$/g, '')}/` : '';
const relativeOriginalPath = `${fileSubPath}${fileName}`;
const currentLibraryId = book.libraryId ?? book.libraryPath?.id ?? (book as any).library?.id ?? null;
const currentLibraryName = this.getLibraryNameById(currentLibraryId);
const targetLibraryId = currentLibraryId;
const targetLibraryName = currentLibraryName;
const preview: FilePreview = {
bookId: book.id,
originalPath: this.getFullPath(currentLibraryId, relativeOriginalPath),
relativeOriginalPath,
currentLibraryId,
currentLibraryName,
targetLibraryId,
targetLibraryName,
newPath: '',
relativeNewPath: ''
};
this.updatePreviewPaths(preview, book);
return preview;
});
}
onDefaultLibraryChange(): void {
this.filePreviews.forEach(preview => {
if (!preview.isMoved) {
preview.targetLibraryId = this.defaultTargetLibraryId;
preview.targetLibraryName = this.getLibraryNameById(this.defaultTargetLibraryId);
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
});
}
onLibraryChange(preview: FilePreview): void {
preview.targetLibraryName = this.getLibraryNameById(preview.targetLibraryId);
const book = this.books.find(b => b.id === preview.bookId);
if (book) {
this.updatePreviewPaths(preview, book);
}
}
private updatePreviewPaths(preview: FilePreview, book: Book): void {
const meta = book.metadata!;
const fileName = book.fileName ?? '';
const extension = fileName.match(/\.[^.]+$/)?.[0] ?? '';
const libraryPattern = this.libraryPatterns.find(p => p.libraryId === preview.targetLibraryId);
const pattern = libraryPattern?.pattern || this.defaultMovePattern;
const values: Record<string, string> = {
authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'),
title: this.sanitize(meta.title || 'Untitled'),
year: this.formatYear(meta.publishedDate),
series: this.sanitize(meta.seriesName || ''),
seriesIndex: this.formatSeriesIndex(meta.seriesNumber ?? undefined),
language: this.sanitize(meta.language || ''),
publisher: this.sanitize(meta.publisher || ''),
isbn: this.sanitize(meta.isbn13 || meta.isbn10 || ''),
currentFilename: this.sanitize(fileName)
};
let newPath: string;
if (!pattern?.trim()) {
newPath = fileName;
} else {
newPath = pattern.replace(/<([^<>]+)>/g, (_, block) => {
const placeholders = [...block.matchAll(/{(.*?)}/g)].map(m => m[1]);
const allHaveValues = placeholders.every(key => values[key]?.trim());
return allHaveValues
? block.replace(/{(.*?)}/g, (_: string, key: string) => values[key] ?? '')
: '';
});
newPath = newPath.replace(/{(.*?)}/g, (_, key) => values[key] ?? '');
if (!newPath.endsWith(extension)) {
newPath += extension;
}
}
preview.relativeNewPath = newPath;
preview.newPath = this.getFullPath(preview.targetLibraryId, newPath);
}
private getLibraryNameById(libraryId: number | null): string {
if (libraryId === null) return 'Unknown Library';
return this.availableLibraries.find(lib => lib.id === libraryId)?.name || 'Unknown Library';
}
private getFullPath(libraryId: number | null, relativePath: string): string {
const libraryPath = libraryId ? this.libraryService.getLibraryPathById(libraryId)?.replace(/\/+$/g, '') : '';
return libraryPath ? `${libraryPath}/${relativePath}`.replace(/\/\/+/g, '/') : relativePath;
}
get movedFileCount(): number {
return this.filePreviews.filter(p => p.isMoved).length;
}
sanitize(input: string | undefined): string {
return input?.replace(/[\\/:*?"<>|]/g, '')
.replace(/[\x00-\x1F\x7F]/g, '')
.replace(/\s+/g, ' ')
.trim() ?? '';
}
formatYear(dateStr?: string): string {
if (!dateStr) return '';
const yearMatch = dateStr.match(/^(\d{4})/);
if (yearMatch) {
return yearMatch[1];
}
const date = new Date(dateStr);
return isNaN(date.getTime()) ? '' : date.getUTCFullYear().toString();
}
formatSeriesIndex(seriesNumber?: number): string {
if (seriesNumber == null) return '';
return this.sanitize(seriesNumber.toString());
}
saveChanges(): void {
this.loading = true;
const request: FileMoveRequest = {
bookIds: [...this.bookIds],
moves: this.filePreviews.map(preview => ({
bookId: preview.bookId,
targetLibraryId: preview.targetLibraryId
}))
};
this.fileOperationsService.moveFiles(request).pipe(
takeUntil(this.destroy$)
).subscribe({
next: () => {
this.loading = false;
this.filePreviews.forEach(p => (p.isMoved = true));
this.messageService.add({
severity: 'success',
summary: 'Files Organized!',
detail: `Successfully organized ${this.filePreviews.length} file${this.filePreviews.length === 1 ? '' : 's'}.`,
life: 3000
});
},
error: () => {
this.loading = false;
this.messageService.add({
severity: 'error',
summary: 'Oops! Something went wrong',
detail: 'We had trouble organizing your files. Please try again.',
life: 3000
});
}
});
}
cancel(): void {
this.ref.close();
}
togglePatternsCollapsed(): void {
this.patternsCollapsed = !this.patternsCollapsed;
}
}
@@ -0,0 +1,61 @@
<div class="flex flex-col items-center justify-center p-2 md:p-6 rounded-lg border border-neutral-700" style="max-width: 700px; margin: auto;">
<div class="mb-4 w-full text-center">
<span class="inline-block px-3 py-1 rounded-full bg-blue-800/60 text-blue-200 text-xs font-semibold tracking-wide mb-2">
Open Source & Community Driven
</span>
<h2 class="text-2xl font-bold text-white mb-2 tracking-tight">
Booklore
</h2>
<p class="text-base text-zinc-200 leading-relaxed">
Booklore is designed to help you manage your book collection with ease and enjoyment.<br>
If you find Booklore valuable, please consider supporting its continued development.
</p>
</div>
<div class="mb-4 w-full text-center">
<p class="text-zinc-200 italic text-sm">
Your feedback and support help me keep Booklore improving for everyone.<br>
<span class="text-zinc-300">- Aditya (Creator of Booklore)</span>
</p>
</div>
<div class="flex md:flex-row flex-col justify-center items-center gap-3 w-full mb-4">
<a href="https://github.com/booklore-app/booklore" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Star on GitHub"
icon="pi pi-github"
outlined
severity="success"
[style]="{ 'min-width': '160px' }">
</p-button>
</a>
<a href="https://opencollective.com/booklore" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Open Collective"
icon="pi pi-globe"
severity="info"
outlined>
</p-button>
</a>
<a href="https://account.venmo.com/u/AdityaChandel" target="_blank" rel="noopener noreferrer" class="sm:w-auto">
<p-button
label="Buy me a coffee"
icon="pi pi-heart"
outlined
severity="danger">
</p-button>
</a>
</div>
<div class="w-full text-center mt-2">
<span class="block mb-1 font-medium text-green-300 text-sm">Booklore will always remain free for everyone. That is my commitment to you.</span>
<div class="text-gray-400 text-sm space-y-2 mt-2">
<p>
<span class="font-semibold text-blue-300">Open Collective</span> contributions directly support development, infrastructure, and ongoing improvements.
</p>
<p>
<span class="font-semibold text-red-300">Venmo</span> is a wonderful way to show personal appreciation, think of it as buying me a coffee for my hard work.
</p>
<p class="text-yellow-200 pt-2">
Every contribution, no matter the size, helps keep Booklore open, growing, and accessible to all.
</p>
</div>
</div>
</div>
@@ -0,0 +1,16 @@
import { Component } from '@angular/core';
import {Button} from 'primeng/button';
@Component({
selector: 'app-github-support-dialog',
imports: [
Button
],
templateUrl: './github-support-dialog.html',
styleUrl: './github-support-dialog.scss'
})
export class GithubSupportDialog {
openGithub(): void {
window.open('https://github.com/adityachandelgit/booklore', '_blank');
}
}
@@ -0,0 +1,12 @@
<input type="text" placeholder="Search icons..." [(ngModel)]="searchText" class="icon-search"/>
<div class="icon-grid">
@for (icon of filteredIcons(); track icon) {
<div
class="icon-item"
(click)="selectIcon(icon)"
[class.selected]="icon === selectedIcon">
<i [class]="icon"></i>
</div>
}
</div>
@@ -0,0 +1,32 @@
.icon-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(25px, 1fr));
gap: 30px;
}
.icon-item {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.icon-search {
width: 100%;
padding: 8px 12px;
font-size: 16px;
border: 1px solid var(--text-color-secondary);
border-radius: 4px;
margin-bottom: 15px;
box-sizing: border-box;
}
.icon-search:focus {
border-color: var(--primary-color);
outline: none;
}
.icon-search::placeholder {
color: var(--text-color-secondary);
opacity: 1;
}
@@ -0,0 +1,77 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-icon-picker-component',
imports: [
FormsModule
],
templateUrl: './icon-picker-component.html',
styleUrl: './icon-picker-component.scss'
})
export class IconPickerComponent {
iconCategories: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "amazon", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right", "arrow-circle-up",
"arrow-down", "arrow-down-left", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-right", "arrow-left",
"arrow-right", "arrow-right-arrow-left", "arrow-up", "arrow-up-left", "arrow-up-right", "arrow-up-right-and-arrow-down-left-from-center",
"arrows-alt", "arrows-h", "arrows-v", "asterisk", "at", "backward", "ban", "barcode", "bars", "bell", "bell-slash",
"bitcoin", "bolt", "book", "bookmark", "bookmark-fill", "box", "briefcase", "building", "building-columns", "bullseye",
"calculator", "calendar", "calendar-clock", "calendar-minus", "calendar-plus", "calendar-times", "camera", "car",
"caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus", "chart-bar",
"chart-line", "chart-pie", "chart-scatter", "check", "check-circle", "check-square", "chevron-circle-down",
"chevron-circle-left", "chevron-circle-right", "chevron-circle-up", "chevron-down", "chevron-left", "chevron-right",
"chevron-up", "circle", "circle-fill", "circle-off", "circle-on", "clipboard", "clock", "clone", "cloud", "cloud-download",
"cloud-upload", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left",
"desktop", "directions", "directions-alt", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v",
"envelope", "equals", "eraser", "ethereum", "euro", "exclamation-circle", "exclamation-triangle", "expand",
"external-link", "eye", "eye-slash", "face-smile", "facebook", "fast-backward", "fast-forward", "file", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word",
"filter", "filter-fill", "filter-slash", "flag", "flag-fill", "folder", "folder-open", "folder-plus", "forward", "gauge",
"gift", "github", "globe", "google", "graduation-cap", "hammer", "hashtag", "headphones", "heart", "heart-fill", "history",
"home", "hourglass", "id-card", "image", "images", "inbox", "indian-rupee", "info", "info-circle", "instagram", "key",
"language", "lightbulb", "link", "linkedin", "list", "list-check", "lock", "lock-open", "map", "map-marker", "mars", "megaphone",
"microchip", "microchip-ai", "microphone", "microsoft", "minus", "minus-circle", "mobile", "money-bill", "moon", "objects-column",
"palette", "paperclip", "pause", "pause-circle", "paypal", "pen-to-square", "pencil", "percentage", "phone", "pinterest", "play",
"play-circle", "plus", "plus-circle", "pound", "power-off", "prime", "print", "qrcode", "question", "question-circle", "receipt",
"reddit", "refresh", "replay", "reply", "save", "search", "search-minus", "search-plus", "send", "server", "share-alt", "shield",
"shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort",
"sort-alpha-down", "sort-alpha-down-alt", "sort-alpha-up", "sort-alpha-up-alt", "sort-alt", "sort-alt-slash",
"sort-amount-down", "sort-amount-down-alt", "sort-amount-up", "sort-amount-up-alt", "sort-down", "sort-down-fill",
"sort-numeric-down", "sort-numeric-down-alt", "sort-numeric-up", "sort-numeric-up-alt", "sort-up", "sort-up-fill", "sparkles",
"spinner", "spinner-dotted", "star", "star-fill", "star-half", "star-half-fill", "step-backward", "step-backward-alt",
"step-forward", "step-forward-alt", "stop", "stop-circle", "stopwatch", "sun", "sync", "table", "tablet", "tag", "tags",
"telegram", "th-large", "thumbs-down", "thumbs-down-fill", "thumbs-up", "thumbs-up-fill", "thumbtack", "ticket", "tiktok",
"times", "times-circle", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user",
"user-edit", "user-minus", "user-plus", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off",
"volume-up", "wallet", "warehouse", "wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench",
"youtube"
];
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = this.createIconList(this.iconCategories);
ref = inject(DynamicDialogRef);
createIconList(categories: string[]): string[] {
return categories.map(iconName => `pi pi-${iconName}`);
}
filteredIcons(): string[] {
if (!this.searchText) return this.icons;
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
selectIcon(icon: string) {
this.selectedIcon = icon;
this.ref.close(icon);
}
cancel() {
this.ref.close();
}
}
@@ -0,0 +1,4 @@
<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>
@@ -0,0 +1,5 @@
.live-border {
background: var(--card-background);
border: 1px solid var(--primary-color);
border-radius: 0.5rem;
}
@@ -0,0 +1,24 @@
import {Component, inject} from '@angular/core';
import {NotificationEventService} from '../../websocket/notification-event.service';
import {LogNotification} from '../../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,6 +1,6 @@
import {Component, OnInit, OnDestroy, inject} from '@angular/core';
import { Subscription } from 'rxjs';
import {LoadingService} from '../../../core/service/loading.service';
import {LoadingService} from '../../service/loading.service';
import {ProgressSpinner} from 'primeng/progressspinner';
@@ -0,0 +1,133 @@
<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>
@@ -0,0 +1,146 @@
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 '../../../core/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();
}
}
@@ -0,0 +1,93 @@
<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>
@@ -0,0 +1,34 @@
.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;
}
@@ -0,0 +1,172 @@
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 '../../../features/metadata/component/metadata-review-dialog-component/metadata-review-dialog-component';
import {MetadataTaskService} from '../../../features/book/service/metadata-task';
import {TaskService} from '../../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;
}
@@ -0,0 +1,30 @@
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 '../../../core/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);
})
);
}
}
@@ -0,0 +1,28 @@
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 '../../../core/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;
})
);
}
}
@@ -0,0 +1,113 @@
<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>
@@ -0,0 +1,58 @@
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.';
},
});
}
}
@@ -0,0 +1,32 @@
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 '../../../core/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;
})
);
}
}
@@ -0,0 +1,21 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../core/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);
}
}
@@ -0,0 +1,12 @@
<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>
@@ -0,0 +1,9 @@
.metadata-progress-box {
overflow-y: auto;
border-radius: 0.5rem;
}
::ng-deep .p-divider-horizontal {
margin: 0 !important;
padding: 0 !important;
}
@@ -0,0 +1,39 @@
import {Component, inject} from '@angular/core';
import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component';
import {MetadataProgressService} from '../../service/metadata-progress-service';
import {map} from 'rxjs/operators';
import {AsyncPipe} from '@angular/common';
import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service';
import {DuplicateFilesNotificationComponent} from '../duplicate-files-notification/duplicate-files-notification.component';
import {DuplicateFileService} from '../../websocket/duplicate-file.service';
import {BookdropFilesWidgetComponent} from '../../../features/bookdrop/component/bookdrop-files-widget/bookdrop-files-widget.component';
import {MetadataProgressWidgetComponent} from '../metadata-progress-widget/metadata-progress-widget-component';
@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,4 @@
export interface MenuChangeEvent {
key: string;
routeEvent?: boolean;
}
@@ -0,0 +1,12 @@
<div class="layout-wrapper" [ngClass]="containerClass">
<app-topbar></app-topbar>
<div class="layout-sidebar layout-sidebar-custom">
<app-sidebar></app-sidebar>
</div>
<div class="layout-main-container">
<div class="layout-main">
<router-outlet></router-outlet>
</div>
</div>
<div class="layout-mask"></div>
</div>
@@ -0,0 +1,119 @@
import {Component, OnDestroy, Renderer2, ViewChild} from '@angular/core';
import {NavigationEnd, Router, RouterOutlet} from '@angular/router';
import {filter, Subscription} from 'rxjs';
import {LayoutService} from "./service/app.layout.service";
import {AppSidebarComponent} from "../layout-sidebar/app.sidebar.component";
import {AppTopBarComponent} from '../layout-topbar/app.topbar.component';
import {NgClass} from '@angular/common';
import {ToastModule} from 'primeng/toast';
@Component({
selector: 'app-layout',
imports: [
RouterOutlet,
AppSidebarComponent,
AppTopBarComponent,
NgClass,
ToastModule
],
templateUrl: './app.layout.component.html'
})
export class AppLayoutComponent implements OnDestroy {
overlayMenuOpenSubscription: Subscription;
menuOutsideClickListener: any;
profileMenuOutsideClickListener: any;
@ViewChild(AppSidebarComponent) appSidebar!: AppSidebarComponent;
@ViewChild(AppTopBarComponent) appTopbar!: AppTopBarComponent;
constructor(public layoutService: LayoutService, public renderer: Renderer2, public router: Router) {
this.overlayMenuOpenSubscription = this.layoutService.overlayOpen$.subscribe(() => {
if (!this.menuOutsideClickListener) {
this.menuOutsideClickListener = this.renderer.listen('document', 'click', (event) => {
if (this.isOutsideClicked(event)) {
this.hideMenu();
}
});
}
if (this.layoutService.state.staticMenuMobileActive) {
this.blockBodyScroll();
}
});
this.router.events.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => {
this.hideMenu();
this.hideProfileMenu();
});
}
isOutsideClicked(event: MouseEvent): boolean {
const sidebarEl = document.querySelector('.layout-sidebar');
const topbarEl = document.querySelector('.layout-menu-button');
const eventTarget = event.target as Node;
const clickedInsideSidebar = sidebarEl?.isSameNode(eventTarget) || sidebarEl?.contains(eventTarget);
const clickedInsideTopbar = topbarEl?.isSameNode(eventTarget) || topbarEl?.contains(eventTarget);
return !(clickedInsideSidebar || clickedInsideTopbar);
}
hideMenu() {
this.layoutService.state.overlayMenuActive = false;
this.layoutService.state.staticMenuMobileActive = false;
this.layoutService.state.menuHoverActive = false;
if (this.menuOutsideClickListener) {
this.menuOutsideClickListener();
this.menuOutsideClickListener = null;
}
this.unblockBodyScroll();
}
hideProfileMenu() {
this.layoutService.state.profileSidebarVisible = false;
if (this.profileMenuOutsideClickListener) {
this.profileMenuOutsideClickListener();
this.profileMenuOutsideClickListener = null;
}
}
blockBodyScroll(): void {
if (document.body.classList) {
document.body.classList.add('blocked-scroll');
} else {
document.body.className += ' blocked-scroll';
}
}
unblockBodyScroll(): void {
if (document.body.classList) {
document.body.classList.remove('blocked-scroll');
} else {
document.body.className = document.body.className.replace(new RegExp('(^|\\b)' +
'blocked-scroll'.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
get containerClass() {
return {
'layout-overlay': this.layoutService.config().menuMode === 'overlay',
'layout-static': this.layoutService.config().menuMode === 'static',
'layout-static-inactive': this.layoutService.state.staticMenuDesktopInactive && this.layoutService.config().menuMode === 'static',
'layout-overlay-active': this.layoutService.state.overlayMenuActive,
'layout-mobile-active': this.layoutService.state.staticMenuMobileActive
}
}
ngOnDestroy() {
if (this.overlayMenuOpenSubscription) {
this.overlayMenuOpenSubscription.unsubscribe();
}
if (this.menuOutsideClickListener) {
this.menuOutsideClickListener();
}
}
}
@@ -0,0 +1,138 @@
import {Injectable, effect, signal} from '@angular/core';
import {Subject} from 'rxjs';
export interface AppConfig {
inputStyle: string;
colorScheme: string;
theme: string;
ripple: boolean;
menuMode: string;
scale: number;
}
interface LayoutState {
staticMenuDesktopInactive: boolean;
overlayMenuActive: boolean;
profileSidebarVisible: boolean;
configSidebarVisible: boolean;
staticMenuMobileActive: boolean;
menuHoverActive: boolean;
}
@Injectable({
providedIn: 'root',
})
export class LayoutService {
_config: AppConfig = {
ripple: false,
inputStyle: 'outlined',
menuMode: 'static',
colorScheme: 'light',
theme: 'lara-light-indigo',
scale: 14,
};
config = signal<AppConfig>(this._config);
state: LayoutState = {
staticMenuDesktopInactive: false,
overlayMenuActive: false,
profileSidebarVisible: false,
configSidebarVisible: false,
staticMenuMobileActive: false,
menuHoverActive: false,
};
private configUpdate = new Subject<AppConfig>();
private overlayOpen = new Subject<any>();
overlayOpen$ = this.overlayOpen.asObservable();
constructor() {
effect(() => {
const config = this.config();
if (this.updateStyle(config)) {
this.changeTheme();
}
this.changeScale(config.scale);
this.onConfigUpdate();
});
}
updateStyle(config: AppConfig) {
return (
config.theme !== this._config.theme ||
config.colorScheme !== this._config.colorScheme
);
}
onMenuToggle() {
if (this.isOverlay()) {
this.state.overlayMenuActive = !this.state.overlayMenuActive;
if (this.state.overlayMenuActive) {
this.overlayOpen.next(null);
}
}
if (this.isDesktop()) {
this.state.staticMenuDesktopInactive = !this.state.staticMenuDesktopInactive;
} else {
this.state.staticMenuMobileActive = !this.state.staticMenuMobileActive;
if (this.state.staticMenuMobileActive) {
this.overlayOpen.next(null);
}
}
}
isOverlay() {
return this.config().menuMode === 'overlay';
}
isDesktop() {
return window.innerWidth > 991;
}
onConfigUpdate() {
this._config = {...this.config()};
this.configUpdate.next(this.config());
}
changeTheme() {
const config = this.config();
const themeLink = document.getElementById('theme-css') as HTMLLinkElement;
const themeLinkHref = themeLink.getAttribute('href')!;
const newHref = themeLinkHref
.split('/')
.map((el) =>
el == this._config.theme
? (el = config.theme)
: el == `theme-${this._config.colorScheme}`
? (el = `theme-${config.colorScheme}`)
: el
)
.join('/');
this.replaceThemeLink(newHref);
}
replaceThemeLink(href: string) {
const id = 'theme-css';
const themeLink = document.getElementById(id) as HTMLLinkElement;
const cloneLinkElement = themeLink.cloneNode(true) as HTMLLinkElement;
cloneLinkElement.setAttribute('href', href);
cloneLinkElement.setAttribute('id', id + '-clone');
themeLink.parentNode!.insertBefore(
cloneLinkElement,
themeLink.nextSibling
);
cloneLinkElement.addEventListener('load', () => {
themeLink.remove();
cloneLinkElement.setAttribute('id', id);
});
}
changeScale(value: number) {
document.documentElement.style.fontSize = `${value}px`;
}
}
@@ -0,0 +1,68 @@
<div class="flex flex-col h-full">
<div>
<ul class="layout-menu">
@if (homeMenu$ | async; as homeMenu) {
@for (item of homeMenu; track item; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
}
}
</ul>
<ul class="layout-menu">
@if (libraryMenu$ | async; as libraryMenu) {
@for (item of libraryMenu; track item; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
}
}
</ul>
<ul class="layout-menu">
@if (shelfMenu$ | async; as shelfMenu) {
@for (item of shelfMenu; track item; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
}
}
</ul>
<ul class="layout-menu">
@if (magicShelfMenu$ | async; as shelfMenu) {
@for (item of shelfMenu; track item; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
}
}
</ul>
</div>
@if (versionInfo) {
<div style="margin-top: auto;" class="p-4 text-center w-full text-sm">
<div class="text-gray-200">
<a
[href]="getVersionUrl(versionInfo.current)"
target="_blank"
rel="noopener noreferrer"
class="hover:underline hover:text-gray-100 text-sm"
>
{{ versionInfo.current }}
</a>
</div>
@if (versionInfo.latest && versionInfo.latest !== versionInfo.current) {
<div>
<a
(click)="openChangelogDialog()"
class="cursor-pointer text-orange-400 hover:underline hover:text-orange-300 text-xs"
>
(Update)
</a>
</div>
}
</div>
}
</div>
@@ -0,0 +1,236 @@
import {Component, inject, OnInit} from '@angular/core';
import {AppMenuitemComponent} from './app.menuitem.component';
import {AsyncPipe} from '@angular/common';
import {MenuModule} from 'primeng/menu';
import {LibraryService} from '../../../../features/book/service/library.service';
import {Observable, of} from 'rxjs';
import {filter, map} from 'rxjs/operators';
import {ShelfService} from '../../../../features/book/service/shelf.service';
import {BookService} from '../../../../features/book/service/book.service';
import {LibraryShelfMenuService} from '../../../../features/book/service/library-shelf-menu.service';
import {AppVersion, VersionService} from '../../../service/version.service';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {MagicShelfService, MagicShelfState} from '../../../../features/magic-shelf/service/magic-shelf.service';
@Component({
selector: 'app-menu',
standalone: true,
imports: [AppMenuitemComponent, MenuModule, AsyncPipe],
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;
versionInfo: AppVersion | null = null;
dynamicDialogRef: DynamicDialogRef | undefined;
private libraryService = inject(LibraryService);
private shelfService = inject(ShelfService);
private bookService = inject(BookService);
private versionService = inject(VersionService);
private libraryShelfMenuService = inject(LibraryShelfMenuService);
private dialogService = inject(DialogService);
private userService = inject(UserService);
private magicShelfService = inject(MagicShelfService);
librarySortField: 'name' | 'id' = 'name';
librarySortOrder: 'asc' | 'desc' = 'desc';
shelfSortField: 'name' | 'id' = 'name';
shelfSortOrder: 'asc' | 'desc' = 'asc';
ngOnInit(): void {
this.versionService.getVersion().subscribe((data) => {
this.versionInfo = data;
});
this.userService.userState$.pipe(
filter(userState => !!userState?.user && userState.loaded))
.subscribe(userState => {
if (userState.user?.userSettings.sidebarLibrarySorting) {
this.librarySortField = this.validateSortField(userState.user.userSettings.sidebarLibrarySorting.field);
this.librarySortOrder = this.validateSortOrder(userState.user.userSettings.sidebarLibrarySorting.order);
}
if (userState.user?.userSettings.sidebarShelfSorting) {
this.shelfSortField = this.validateSortField(userState.user.userSettings.sidebarShelfSorting.field);
this.shelfSortOrder = this.validateSortOrder(userState.user.userSettings.sidebarShelfSorting.order);
}
this.initMenus();
});
this.homeMenu$ = this.bookService.bookState$.pipe(
map((bookState) => [
{
label: 'Home',
items: [
{
label: 'Dashboard',
icon: 'pi pi-fw pi-home',
routerLink: ['/dashboard'],
},
{
label: 'All Books',
type: 'All Books',
icon: 'pi pi-fw pi-book',
routerLink: ['/all-books'],
bookCount$: of(bookState.books ? bookState.books.length : 0),
}
],
},
])
);
}
private initMenus(): void {
this.libraryMenu$ = this.libraryService.libraryState$.pipe(
map((state) => {
const libraries = state.libraries ?? [];
const sortedLibraries = this.sortArray(libraries, this.librarySortField, this.librarySortOrder);
return [
{
label: 'Libraries',
type: 'library',
hasDropDown: true,
hasCreate: true,
items: sortedLibraries.map((library) => ({
menu: this.libraryShelfMenuService.initializeLibraryMenuItems(library),
label: library.name,
type: 'Library',
icon: 'pi pi-' + library.icon,
routerLink: [`/library/${library.id}/books`],
bookCount$: this.libraryService.getBookCount(library.id ?? 0),
})),
},
];
})
);
this.magicShelfMenu$ = this.magicShelfService.shelvesState$.pipe(
map((state: MagicShelfState) => {
const shelves = state.shelves ?? [];
const sortedShelves = this.sortArray(shelves, 'name', 'asc');
return [
{
label: 'Magic Shelves',
type: 'magicShelf',
hasDropDown: true,
hasCreate: true,
items: sortedShelves.map((shelf) => ({
label: shelf.name,
type: 'magicShelfItem',
icon: 'pi pi-' + shelf.icon,
menu: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf),
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount$: this.magicShelfService.getBookCount(shelf.id ?? 0),
})),
},
];
})
);
this.shelfMenu$ = this.shelfService.shelfState$.pipe(
map((state) => {
const shelves = state.shelves ?? [];
const sortedShelves = this.sortArray(shelves, this.shelfSortField, this.shelfSortOrder);
const koboShelfIndex = sortedShelves.findIndex(shelf => shelf.name === 'Kobo');
let koboShelf = null;
if (koboShelfIndex !== -1) {
koboShelf = sortedShelves.splice(koboShelfIndex, 1)[0];
}
const shelfItems = sortedShelves.map((shelf) => ({
menu: this.libraryShelfMenuService.initializeShelfMenuItems(shelf),
label: shelf.name,
type: 'Shelf',
icon: 'pi pi-' + shelf.icon,
routerLink: [`/shelf/${shelf.id}/books`],
bookCount$: this.shelfService.getBookCount(shelf.id ?? 0),
}));
const unshelvedItem = {
label: 'Unshelved',
type: 'Shelf',
icon: 'pi pi-inbox',
routerLink: ['/unshelved-books'],
bookCount$: this.shelfService.getUnshelvedBookCount?.() ?? of(0),
};
const items = [unshelvedItem];
if (koboShelf) {
items.push({
label: koboShelf.name,
type: 'Shelf',
icon: 'pi pi-' + koboShelf.icon,
routerLink: [`/shelf/${koboShelf.id}/books`],
bookCount$: this.shelfService.getBookCount(koboShelf.id ?? 0),
});
}
items.push(...shelfItems);
return [
{
type: 'shelf',
label: 'Shelves',
hasDropDown: true,
hasCreate: false,
items,
},
];
})
);
}
openChangelogDialog() {
const isMobile = window.innerWidth <= 768;
this.dynamicDialogRef = this.dialogService.open(VersionChangelogDialogComponent, {
header: 'What’s New',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
},
});
}
getVersionUrl(version: string | undefined): string {
if (!version) return '#';
return version.startsWith('v')
? `https://github.com/adityachandelgit/BookLore/releases/tag/${version}`
: `https://github.com/adityachandelgit/BookLore/commit/${version}`;
}
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] ?? '';
let comparison = 0;
if (typeof aVal === 'string' && typeof bVal === 'string') {
comparison = aVal.localeCompare(bVal);
} else if (typeof aVal === 'number' && typeof bVal === 'number') {
comparison = aVal - bVal;
}
return order === 'asc' ? comparison : -comparison;
});
}
private validateSortField(field: string): 'name' | 'id' {
return field === 'id' ? 'id' : 'name';
}
private validateSortOrder(order: string): 'asc' | 'desc' {
return order === 'desc' ? 'desc' : 'asc';
}
}
@@ -0,0 +1,101 @@
<ng-container>
@if (root) {
@if (item.hasDropDown) {
<div class=" flex items-center justify-between layout-menuitem-root-text cursor-pointer pt-4">
<div class="flex items-center justify-between gap-2 cursor-pointer">
<div>{{ item.label }}</div>
@if (item.hasCreate) {
<i
class="pi pi-plus text-surface-500 hover:text-surface-200"
style="font-size: 0.8rem"
(click)="openDialog(item)"
></i>
}
</div>
<i
(click)="toggleExpand(key)"
[ngClass]="{
'pi': true,
'pi-angle-up': isExpanded(key),
'pi-angle-down': !isExpanded(key),
'text-surface-500': true,
'hover:text-surface-200': true,
'pr-3': true
}"></i>
</div>
} @else {
<div class="flex items-center justify-between layout-menuitem-root-text">
<div>{{ item.label }}</div>
</div>
}
}
<div>
<div
class="flex flex-row items-center justify-between hover:bg-surface-800 rounded-md cursor-pointer"
(click)="triggerLink()"
>
@if ((item.routerLink && !item.items)) {
<a
#link
(click)="itemClick($event)"
[ngClass]="item.class + ' flex items-center gap-2 w-full'"
[routerLink]="item.routerLink"
routerLinkActive="active-route"
[routerLinkActiveOptions]="item.routerLinkActiveOptions || { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
[fragment]="item.fragment"
[queryParamsHandling]="item.queryParamsHandling"
[preserveFragment]="item.preserveFragment"
[skipLocationChange]="item.skipLocationChange"
[replaceUrl]="item.replaceUrl"
[state]="item.state"
[queryParams]="item.queryParams"
[attr.target]="item.target"
tabindex="0"
pRipple
>
<i [ngClass]="item.icon" class="layout-menuitem-icon"></i>
<span class="layout-menuitem-text w-full truncate">
{{ item.label }}
</span>
</a>
}
<span>
@if (item.type === 'Library' || item.type === 'Shelf' || item.type === 'magicShelfItem') {
@if ((item.type !== 'Library' || (admin || canManipulateLibrary)) && item.label !== 'Unshelved' && item.label !== 'Kobo') {
<p-button
(click)="entitymenu.toggle($event); $event.stopPropagation()"
(mouseover)="hovered = true"
(mouseleave)="hovered = false"
[text]="true"
[outlined]="false"
[rounded]="true"
[label]="hovered ? '' : (item.bookCount$ | async)?.toString() || ''"
[icon]="hovered ? 'pi pi-ellipsis-v' : ''"
[style.height]="'30px'"
[style.display]="'flex'"
></p-button>
}
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
}
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.label === 'Unshelved' || item.label === 'Kobo') {
<p class="text-[var(--primary-color)] pr-3">
{{ (item.bookCount$ | async)?.toString() || '0' }}
</p>
}
</span>
</div>
<div [@children]="isExpanded(key) ? 'expanded' : 'collapsed'" style="overflow: hidden;">
@if (item.items) {
<ul>
@for (child of item.items; track child; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key" [class]="child.badgeClass"></li>
}
</ul>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,166 @@
import {Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {NavigationEnd, Router, RouterLink, RouterLinkActive} from '@angular/router';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {Subscription} from 'rxjs';
import {filter} from 'rxjs/operators';
import {MenuService} from './service/app.menu.service';
import {AsyncPipe, NgClass} from '@angular/common';
import {Ripple} from 'primeng/ripple';
import {Button} from 'primeng/button';
import {Menu} from 'primeng/menu';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {DialogLauncherService} from '../../../../core/service/dialog-launcher.service';
@Component({
selector: '[app-menuitem]',
templateUrl: './app.menuitem.component.html',
styleUrls: ['./app.menuitem.component.scss'],
imports: [
RouterLink,
RouterLinkActive,
NgClass,
Ripple,
AsyncPipe,
Button,
Menu
],
animations: [
trigger('children', [
state('collapsed', style({
height: '0'
})),
state('expanded', style({
height: '*'
})),
transition('collapsed <=> expanded', animate('400ms cubic-bezier(0.86, 0, 0.07, 1)'))
])
]
})
export class AppMenuitemComponent implements OnInit, OnDestroy {
@Input() item: any;
@Input() index!: number;
@Input() @HostBinding('class.layout-root-menuitem') root!: boolean;
@Input() parentKey!: string;
@ViewChild('linkRef') linkRef!: ElementRef<HTMLAnchorElement>;
hovered = false;
active = false;
key: string = "";
canManipulateLibrary: boolean = false;
admin: boolean = false;
expandedItems = new Set<string>();
menuSourceSubscription: Subscription;
menuResetSubscription: Subscription;
constructor(
public router: Router,
private menuService: MenuService,
private userService: UserService,
private dialogLauncher: DialogLauncherService
) {
this.userService.userState$.subscribe(userState => {
if (userState?.user) {
this.canManipulateLibrary = userState.user.permissions.canManipulateLibrary;
this.admin = userState.user.permissions.admin;
}
});
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
Promise.resolve(null).then(() => {
if (value.routeEvent) {
this.active = (value.key === this.key || value.key.startsWith(this.key + '-')) ? true : false;
} else {
if (value.key !== this.key && !value.key.startsWith(this.key + '-')) {
this.active = false;
}
}
});
});
this.menuResetSubscription = this.menuService.resetSource$.subscribe(() => {
this.active = false;
});
this.router.events.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(() => {
if (this.item.routerLink) {
this.updateActiveStateFromRoute();
}
});
}
ngOnInit() {
this.key = this.parentKey ? this.parentKey + '-' + this.index : String(this.index);
this.expandedItems.add(this.key);
if (this.item.routerLink) {
this.updateActiveStateFromRoute();
}
}
ngOnDestroy() {
if (this.menuSourceSubscription) {
this.menuSourceSubscription.unsubscribe();
}
if (this.menuResetSubscription) {
this.menuResetSubscription.unsubscribe();
}
}
toggleExpand(key: string) {
if (this.expandedItems.has(key)) {
this.expandedItems.delete(key);
} else {
this.expandedItems.add(key);
}
}
isExpanded(key: string): boolean {
return this.expandedItems.has(key);
}
updateActiveStateFromRoute() {
const activeRoute = this.router.isActive(this.item.routerLink[0], {
paths: 'exact',
queryParams: 'ignored',
matrixParams: 'ignored',
fragment: 'ignored'
});
if (activeRoute) {
this.menuService.onMenuStateChange({key: this.key, routeEvent: true});
}
}
itemClick(event: Event) {
if (this.item.disabled) {
event.preventDefault();
return;
}
if (this.item.command) {
this.item.command({originalEvent: event, item: this.item});
}
if (this.item.items) {
this.active = !this.active;
}
this.menuService.onMenuStateChange({key: this.key});
}
openDialog(item: any) {
if (item.type === 'library' && this.canManipulateLibrary) {
this.dialogLauncher.openLibraryCreatorDialog();
}
if (item.type === 'magicShelf') {
this.dialogLauncher.openMagicShelfDialog();
}
}
triggerLink() {
if (this.item.routerLink && !this.item.items && this.linkRef) {
this.linkRef.nativeElement.click();
}
}
@HostBinding('class.active-menuitem')
get activeClass() {
return this.active && !this.root;
}
}
@@ -0,0 +1,23 @@
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { MenuChangeEvent } from '../../../api/menuchangeevent';
@Injectable({
providedIn: 'root'
})
export class MenuService {
private menuSource = new Subject<MenuChangeEvent>();
private resetSource = new Subject();
menuSource$ = this.menuSource.asObservable();
resetSource$ = this.resetSource.asObservable();
onMenuStateChange(event: MenuChangeEvent) {
this.menuSource.next(event);
}
reset() {
this.resetSource.next(true);
}
}
@@ -0,0 +1,26 @@
@if (loading) {
<div class="p-4 text-center text-gray-400">
Loading changelog...
</div>
}
@if (!loading && changelog.length === 0) {
<div class="p-4 text-center text-gray-400">
No updates available.
</div>
}
@if (!loading && changelog.length > 0) {
<div class="space-y-6 p-4 max-h-[70vh] overflow-auto">
@for (release of changelog; track release) {
<div class="border-b pb-4">
<p class="font-bold text-2xl pb-2">
<a [href]="release.url" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:underline">
{{ release.name }} ({{ release.publishedAt | date: 'mediumDate' }})
</a>
</p>
<div [innerHTML]="markdownToHtml(release.changelog)" class="prose prose-invert w-full max-w-full"></div>
</div>
}
</div>
}
@@ -0,0 +1,3 @@
:host ::ng-deep .prose h3 {
margin-top: 0px;
}
@@ -0,0 +1,44 @@
import { Component, inject, OnInit } from '@angular/core';
import { ReleaseNote, VersionService } from '../../../../service/version.service';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import showdown from 'showdown';
import {DatePipe} from '@angular/common';
@Component({
selector: 'app-version-changelog-dialog',
standalone: true,
imports: [
DatePipe
],
templateUrl: './version-changelog-dialog.component.html',
styleUrl: './version-changelog-dialog.component.scss'
})
export class VersionChangelogDialogComponent implements OnInit {
private versionService = inject(VersionService);
private sanitizer = inject(DomSanitizer);
changelog: ReleaseNote[] = [];
loading = true;
private converter = new showdown.Converter({ tables: true, emoji: true });
ngOnInit(): void {
this.versionService.getChangelog().subscribe({
next: (data) => {
this.changelog = data;
this.loading = false;
},
error: () => {
this.loading = false;
}
});
}
markdownToHtml(markdown: string): SafeHtml {
let html = this.converter.makeHtml(markdown);
html = html.replace(/<h2\b([^>]*)>/g, '<h3$1>').replace(/<\/h2>/g, '</h3>');
return this.sanitizer.bypassSecurityTrustHtml(html);
}
}
@@ -0,0 +1 @@
<app-menu></app-menu>
@@ -0,0 +1,3 @@
.layout-sidebar-custom {
width: 250px !important;
}
@@ -0,0 +1,15 @@
import { Component, ElementRef } from '@angular/core';
import { LayoutService } from "../layout-main/service/app.layout.service";
import {AppMenuComponent} from '../layout-menu/app.menu.component';
@Component({
selector: 'app-sidebar',
imports: [
AppMenuComponent
],
templateUrl: './app.sidebar.component.html'
})
export class AppSidebarComponent {
constructor(public layoutService: LayoutService, public el: ElementRef) { }
}
@@ -0,0 +1,249 @@
<div class="layout-topbar">
<a class="layout-topbar-logo pl-5 pr-24 flex gap-2" routerLink="">
<svg class="w-[1.875rem] h-[1.875rem] half-title" viewBox="0 0 126 126" fill="currentColor" 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>
<span class="flex items-center pt-2">
<p>Book</p>
<p class="half-title text-3xl">lore</p>
</span>
</a>
<p-button
class="layout-menu-button"
#menubutton
icon="pi pi-bars"
[rounded]="true"
[outlined]="true"
(click)="toggleMenu()"
[ngClass]="{ 'rotate-right': !isMenuVisible, 'rotate-left': isMenuVisible }"
>
</p-button>
<div class="flex items-center w-full gap-4">
<app-book-searcher class="md:block flex-grow"></app-book-searcher>
<ul class="topbar-items hidden md:flex items-center gap-3 ml-auto pl-4">
<div class="flex gap-4">
@if (userService.userState$ | async; as userState) {
<li>
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="navigateToBookdrop()" pTooltip="Bookdrop" tooltipPosition="bottom">
<i class="pi pi-inbox text-surface-100"></i>
</a>
}
</li>
<li>
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="openLibraryCreatorDialog()" pTooltip="Create New Library" tooltipPosition="bottom">
<i class="pi pi-plus-circle text-surface-100"></i>
</a>
}
</li>
<li>
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="openFileUploadDialog()" pTooltip="Upload Book" tooltipPosition="bottom">
<i class="pi pi-upload text-surface-100"></i>
</a>
}
</li>
}
<li>
<a class="topbar-item" (click)="navigateToStats()" pTooltip="Stats" tooltipPosition="bottom">
<i class="pi pi-chart-bar text-surface-100"></i>
</a>
</li>
@if (userService.userState$ | async; as userState) {
<li>
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="navigateToMetadataManager()" pTooltip="Metadata Manager" tooltipPosition="bottom">
<i class="pi pi-sparkles text-surface-100"></i>
</a>
}
</li>
}
<li>
<a class="topbar-item" (click)="navigateToSettings()" pTooltip="Settings" tooltipPosition="bottom">
<i class="pi pi-cog text-surface-100"></i>
</a>
</li>
</div>
<p-divider layout="vertical"/>
<div class="flex gap-4">
<li class="relative">
<button
type="button"
class="topbar-item"
(click)="notificationPopover.toggle($event)"
>
<i
class="pi"
[ngClass]="iconClass"
[ngStyle]="{ color: iconColor }"
style="font-size: 1.25rem"
[class.pulsating]="iconPulsating"
aria-label="Unified Notification Icon"
></i>
</button>
@if (shouldShowNotificationBadge) {
<span class="notification-badge">{{ completedTaskCount }}</span>
}
<p-popover #notificationPopover>
<app-unified-notification-popover-component></app-unified-notification-popover-component>
</p-popover>
</li>
<li class="relative group overflow-hidden !border-transparent topbar-item" (click)="openGithubSupportDialog()">
<span
style="animation-duration: 2s; background: conic-gradient(from 90deg, #f97316, #f59e0b, #eab308, #84cc16, #22c55e, #10b981, #14a8a6, #06b6d4, #0ea5e9, #3b82f6, #6366f1, #8b5cf6, #a855f7, #d946ef, #ec4899, #f43f5e)"
class="absolute -top-5 -left-5 w-20 h-20 animate-spin">
</span>
<span style="inset: 1px; border-radius: 4px" class="absolute z-2 bg-surface-900 transition-all"></span>
<i class="pi pi-heart z-10"></i>
</li>
<li class="relative">
<button type="button"
class="topbar-item config-item"
enterActiveClass="animate-scalein"
enterFromClass="hidden"
leaveActiveClass="animate-fadeout"
leaveToClass="hidden"
pStyleClass="@next" [hideOnOutsideClick]="true">
<i class="pi pi-palette"></i>
</button>
<app-theme-configurator></app-theme-configurator>
</li>
</div>
<p-divider layout="vertical"/>
<div class="flex gap-4">
<li>
<a class="topbar-item"
href="https://booklore-app.github.io/booklore-docs/docs/getting-started/"
target="_blank"
rel="noopener noreferrer"
pTooltip="Documentation"
tooltipPosition="bottom">
<i class="pi pi-info-circle text-surface-100"></i>
</a>
</li>
<li>
<button class="topbar-item" (click)="openUserProfileDialog()" pTooltip="Profile" tooltipPosition="bottom">
<i class="pi pi-user text-surface-100"></i>
</button>
</li>
<li>
<button class="topbar-item" (click)="logout()" pTooltip="Logout" tooltipPosition="left">
<i class="pi pi-sign-out text-surface-100"></i>
</button>
</li>
</div>
</ul>
<!-- Trigger Button -->
<div class="md:hidden relative ml-auto">
<p-button
icon="pi pi-ellipsis-v"
outlined
(click)="mobileMenu.toggle($event)"
/>
<p-popover #mobileMenu>
<ul class="flex flex-col gap-1 w-48">
@if (userService.userState$ | async; as userState) {
@if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="openLibraryCreatorDialog(); mobileMenu.hide()"
>
<i class="pi pi-plus-circle text-surface-100"></i>
Create Library
</button>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="openFileUploadDialog(); mobileMenu.hide()"
>
<i class="pi pi-upload text-surface-100"></i>
Upload Book
</button>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="navigateToBookdrop(); mobileMenu.hide()"
>
<i class="pi pi-inbox text-surface-100"></i>
Bookdrop
</button>
</li>
}
}
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="navigateToStats(); mobileMenu.hide()"
>
<i class="pi pi-chart-bar text-surface-100"></i>
Charts
</button>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="navigateToSettings(); mobileMenu.hide()"
>
<i class="pi pi-cog text-surface-100"></i>
Settings
</button>
</li>
<li>
<a
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
href="https://booklore-app.github.io/booklore-docs/docs/getting-started/"
target="_blank"
rel="noopener noreferrer">
<i class="pi pi-info-circle text-surface-100"></i>
Documentation
</a>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="openGithubSupportDialog(); mobileMenu.hide()"
>
<i class="pi pi-thumbs-up text-surface-100"></i>
Support BookLore
</button>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="openUserProfileDialog(); mobileMenu.hide()"
>
<i class="pi pi-user text-surface-100"></i>
Profile
</button>
</li>
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="logout(); mobileMenu.hide()"
>
<i class="pi pi-sign-out text-surface-100"></i>
Logout
</button>
</li>
</ul>
</p-popover>
</div>
</div>
</div>
@@ -0,0 +1,40 @@
.highlight {
color: red !important;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.spin {
animation: spin 1.5s linear infinite;
}
@keyframes pulsate {
0% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.25); opacity: 0.8; }
100% { transform: scale(1); opacity: 1; }
}
.pulsating {
animation: pulsate 1.5s infinite ease-in-out;
}
.notification-badge {
position: absolute;
top: -0.4rem;
right: -0.4rem;
background-color: red;
color: white;
border-radius: 50%;
width: 1.2rem;
height: 1.2rem;
font-size: 0.75rem;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
user-select: none;
}
@@ -0,0 +1,247 @@
import {Component, ElementRef, OnDestroy, ViewChild} from '@angular/core';
import {MenuItem} from 'primeng/api';
import {LayoutService} from '../layout-main/service/app.layout.service';
import {Router, RouterLink} from '@angular/router';
import {DialogService as PrimeDialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {TooltipModule} from 'primeng/tooltip';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
import {BookSearcherComponent} from '../../../../features/book/components/book-searcher/book-searcher.component';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {NotificationEventService} from '../../../websocket/notification-event.service';
import {Button} from 'primeng/button';
import {StyleClass} from 'primeng/styleclass';
import {Divider} from 'primeng/divider';
import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component';
import {AuthService} from '../../../service/auth.service';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {Popover} from 'primeng/popover';
import {MetadataProgressService} from '../../../service/metadata-progress-service';
import {takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
import {MetadataBatchProgressNotification} from '../../../model/metadata-batch-progress.model';
import {BookdropFileService} from '../../../../features/bookdrop/service/bookdrop-file.service';
import {DialogLauncherService} from '../../../../core/service/dialog-launcher.service';
import {DuplicateFileService} from '../../../websocket/duplicate-file.service';
import {UnifiedNotificationBoxComponent} from '../../../components/unified-notification-popover/unified-notification-popover-component';
@Component({
selector: 'app-topbar',
templateUrl: './app.topbar.component.html',
styleUrls: ['./app.topbar.component.scss'],
standalone: true,
imports: [
RouterLink,
TooltipModule,
FormsModule,
InputTextModule,
BookSearcherComponent,
Button,
ThemeConfiguratorComponent,
StyleClass,
NgClass,
Divider,
AsyncPipe,
Popover,
UnifiedNotificationBoxComponent,
NgStyle,
],
})
export class AppTopBarComponent implements OnDestroy {
items!: MenuItem[];
ref?: DynamicDialogRef;
@ViewChild('menubutton') menuButton!: ElementRef;
@ViewChild('topbarmenubutton') topbarMenuButton!: ElementRef;
@ViewChild('topbarmenu') menu!: ElementRef;
isMenuVisible = true;
progressHighlight = false;
completedTaskCount = 0;
hasActiveOrCompletedTasks = false;
showPulse = false;
hasAnyTasks = false;
hasPendingBookdropFiles = false;
hasDuplicateFiles = false;
private eventTimer: any;
private destroy$ = new Subject<void>();
private latestTasks: { [taskId: string]: MetadataBatchProgressNotification } = {};
private latestHasPendingFiles = false;
private latestHasDuplicateFiles = false;
constructor(
public layoutService: LayoutService,
public dialogService: PrimeDialogService,
private notificationService: NotificationEventService,
private router: Router,
private authService: AuthService,
protected userService: UserService,
private metadataProgressService: MetadataProgressService,
private bookdropFileService: BookdropFileService,
private dialogLauncher: DialogLauncherService,
private duplicateFileService: DuplicateFileService
) {
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
this.subscribeToDuplicateFiles();
this.metadataProgressService.activeTasks$
.pipe(takeUntil(this.destroy$))
.subscribe((tasks) => {
this.latestTasks = tasks;
this.hasAnyTasks = Object.keys(tasks).length > 0;
this.updateCompletedTaskCount();
this.updateTaskVisibility(tasks);
});
this.bookdropFileService.hasPendingFiles$
.pipe(takeUntil(this.destroy$))
.subscribe((hasPending) => {
this.latestHasPendingFiles = hasPending;
this.hasPendingBookdropFiles = hasPending;
this.updateCompletedTaskCount();
this.updateTaskVisibilityWithBookdrop();
});
this.duplicateFileService.duplicateFiles$
.pipe(takeUntil(this.destroy$))
.subscribe((duplicateFiles) => {
this.latestHasDuplicateFiles = duplicateFiles && duplicateFiles.length > 0;
this.hasDuplicateFiles = this.latestHasDuplicateFiles;
this.updateCompletedTaskCount();
this.updateTaskVisibilityWithDuplicates();
});
}
ngOnDestroy(): void {
if (this.ref) this.ref.close();
clearTimeout(this.eventTimer);
this.destroy$.next();
this.destroy$.complete();
}
toggleMenu() {
this.isMenuVisible = !this.isMenuVisible;
this.layoutService.onMenuToggle();
}
openGithubSupportDialog(): void {
this.dialogLauncher.openGithubSupportDialog();
}
openLibraryCreatorDialog(): void {
this.dialogLauncher.openLibraryCreatorDialog();
}
openFileUploadDialog(): void {
this.dialogLauncher.openFileUploadDialog();
}
openUserProfileDialog(): void {
this.dialogLauncher.openUserProfileDialog();
}
navigateToSettings() {
this.router.navigate(['/settings']);
}
navigateToBookdrop() {
this.router.navigate(['/bookdrop']);
}
navigateToMetadataManager() {
this.router.navigate(['/metadata-manager']);
}
navigateToStats() {
this.router.navigate(['/stats']);
}
logout() {
this.authService.logout();
}
private subscribeToMetadataProgress() {
this.metadataProgressService.progressUpdates$
.pipe(takeUntil(this.destroy$))
.subscribe((progress) => {
this.progressHighlight = progress.status === 'IN_PROGRESS';
});
}
private subscribeToNotifications() {
this.notificationService.latestNotification$
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.triggerPulseEffect();
});
}
private subscribeToDuplicateFiles() {
this.duplicateFileService.duplicateFiles$
.pipe(takeUntil(this.destroy$))
.subscribe((duplicateFiles) => {
if (duplicateFiles && duplicateFiles.length > 0) {
this.triggerPulseEffect();
}
});
}
private triggerPulseEffect() {
this.showPulse = true;
clearTimeout(this.eventTimer);
this.eventTimer = setTimeout(() => {
this.showPulse = false;
}, 4000);
}
private updateCompletedTaskCount() {
const completedMetadataTasks = Object.values(this.latestTasks).length;
const bookdropFileTaskCount = this.latestHasPendingFiles ? 1 : 0;
const duplicateFileTaskCount = this.latestHasDuplicateFiles ? 1 : 0;
this.completedTaskCount = completedMetadataTasks + bookdropFileTaskCount + duplicateFileTaskCount;
}
private updateTaskVisibility(tasks: { [taskId: string]: MetadataBatchProgressNotification }) {
this.hasActiveOrCompletedTasks =
this.progressHighlight || this.completedTaskCount > 0 || Object.keys(tasks).length > 0;
this.updateTaskVisibilityWithBookdrop();
}
private updateTaskVisibilityWithBookdrop() {
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasPendingBookdropFiles;
this.updateTaskVisibilityWithDuplicates();
}
private updateTaskVisibilityWithDuplicates() {
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasDuplicateFiles;
}
get iconClass(): string {
if (this.progressHighlight) return 'pi-spinner spin';
if (this.iconPulsating) return 'pi-wave-pulse';
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles) return 'pi-bell';
return 'pi-wave-pulse';
}
get iconColor(): string {
if (this.progressHighlight) return 'yellow';
if (this.showPulse) return 'orange';
if (this.completedTaskCount > 0 || this.hasPendingBookdropFiles || this.hasDuplicateFiles) return 'yellowgreen';
return 'inherit';
}
get iconPulsating(): boolean {
return !this.progressHighlight && (this.showPulse);
}
get shouldShowNotificationBadge(): boolean {
return (
(this.completedTaskCount > 0 || this.hasPendingBookdropFiles || this.hasDuplicateFiles) &&
!this.progressHighlight &&
!this.showPulse
);
}
}
@@ -0,0 +1,32 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, map, tap} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config';
@Injectable({providedIn: 'root'})
export class BackgroundUploadService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/background`;
private readonly http = inject(HttpClient);
uploadFile(file: File): Observable<string> {
const formData = new FormData();
formData.append('file', file);
return this.http.post<{ url: string }>(`${this.baseUrl}/upload`, formData).pipe(
tap(response => console.log('File upload response:', response)),
map(resp => resp?.url)
);
}
uploadUrl(url: string): Observable<string> {
return this.http.post<{ url: string }>(`${this.baseUrl}/url`, {url}).pipe(
tap(response => console.log('URL upload response:', response)),
map(resp => resp?.url)
);
}
resetToDefault(): Observable<void> {
return this.http.delete<void>(this.baseUrl).pipe(
tap(() => console.log('Background reset to default'))
);
}
}
@@ -0,0 +1,27 @@
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class FaviconService {
private svgTemplate = (color: string) => `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 126 126" fill="currentColor">
<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" fill="${color}"/>
<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>
`;
updateFavicon(color: string) {
const svg = this.svgTemplate(color);
const blob = new Blob([svg], {type: 'image/svg+xml'});
const url = URL.createObjectURL(blob);
let favicon = document.querySelector("link[rel*='icon']") as HTMLLinkElement;
if (!favicon) {
favicon = document.createElement('link');
favicon.rel = 'icon';
document.head.appendChild(favicon);
}
favicon.type = 'image/svg+xml';
favicon.href = url;
}
}
@@ -0,0 +1,33 @@
<div class="config-panel-content">
<div class="config-panel-colors">
<span class="config-panel-label">Primary</span>
<div>
@for (primaryColor of primaryColors(); track primaryColor.name) {
<button
type="button"
[title]="primaryColor.name"
(click)="updateColors($event, 'primary', primaryColor)"
[ngClass]="{ 'active-color': primaryColor.name === selectedPrimaryColor() }"
[style]="{ 'background-color': primaryColor.name === 'noir' ? 'var(--text-color)' : primaryColor.palette['500'] || 'transparent' }"
></button>
}
</div>
</div>
<div class="config-panel-colors">
<span class="config-panel-label">Surface</span>
<div>
@for (surface of surfaces; track surface.name) {
<button
type="button"
[title]="surface.name"
(click)="updateColors($event, 'surface', surface)"
[ngClass]="{ 'active-color': selectedSurfaceColor() ? selectedSurfaceColor() === surface.name : surface.name === 'zinc' }"
[style]="{'background-color': surface.name === 'noir' ? 'var(--text-color)' : surface.palette['500'] }">
</button>
}
</div>
</div>
</div>
@@ -0,0 +1,81 @@
import {CommonModule} from '@angular/common';
import {Component, computed, effect, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {ButtonModule} from 'primeng/button';
import {RadioButtonModule} from 'primeng/radiobutton';
import {ToggleSwitchModule} from 'primeng/toggleswitch';
import Aura from '../theme-palette-extend';
import {AppConfigService} from '../../../service/app-config.service';
import {FaviconService} from './favicon-service';
type ColorPalette = Record<string, string>;
interface Palette {
name: string;
palette: ColorPalette;
}
@Component({
selector: 'app-theme-configurator',
standalone: true,
templateUrl: './theme-configurator.component.html',
host: {
class: 'config-panel hidden'
},
imports: [
CommonModule,
FormsModule,
ButtonModule,
RadioButtonModule,
ToggleSwitchModule
]
})
export class ThemeConfiguratorComponent {
readonly configService = inject(AppConfigService);
readonly faviconService = inject(FaviconService);
readonly surfaces = this.configService.surfaces;
readonly selectedPrimaryColor = computed(() => this.configService.appState().primary);
readonly selectedSurfaceColor = computed(() => this.configService.appState().surface);
readonly faviconColor = computed(() => {
const name = this.selectedPrimaryColor() ?? 'green';
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const colorPalette = presetPalette[name];
return colorPalette?.[500] ?? name;
});
private readonly _faviconSyncEffect = effect(() => {
this.faviconService.updateFavicon(this.faviconColor());
});
readonly primaryColors = computed<Palette[]>(() => {
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const colors = [
'emerald', 'green', 'lime', 'orange', 'amber', 'yellow',
'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet',
'purple', 'fuchsia', 'pink', 'rose', 'red',
'coralSunset', 'roseBlush', 'melonBlush', 'cottonCandy',
'apricotSunrise', 'antiqueBronze', 'butteryYellow', 'vanillaCream',
'citrusMint', 'freshMint', 'sagePearl', 'skyBlue','periwinkleCream',
'pastelRoyalBlue', 'lavenderDream', 'dustyNeutral'
];
return [{name: 'noir', palette: {}}].concat(
colors.map(name => ({
name,
palette: presetPalette[name] ?? {}
}))
);
});
updateColors(event: Event, type: 'primary' | 'surface', color: { name: string; palette?: ColorPalette }) {
this.configService.appState.update((state) => ({
...state,
[type]: color.name
}));
event.stopPropagation();
}
}
@@ -0,0 +1,59 @@
<div class="upload-dialog-content">
<div class="upload-section">
<div class="file-selector">
<label class="file-label">Choose File:</label>
<p-button
label="Select Image"
icon="pi pi-upload"
(click)="fileInput.click()"
outlined
severity="info">
</p-button>
</div>
<input
#fileInput
type="file"
accept=".jpg,.jpeg,.png,image/jpeg,image/png"
(change)="onFileSelected($event)"
style="display: none;">
<small class="file-note">Supported formats: JPEG, PNG • Maximum file size: 5 MB</small>
@if (uploadFile) {
<small class="selected-file">{{ uploadFile.name }}</small>
}
</div>
<p-divider align="center" type="solid">
<span class="or-text">OR</span>
</p-divider>
<div class="url-section">
<label for="urlInput" class="url-label">Image URL:</label>
<input
id="urlInput"
type="text"
[(ngModel)]="uploadImageUrl"
placeholder="Paste image URL here"
class="url-input"
pInputText>
<small class="url-note">Supported formats: JPEG, PNG • Maximum file size: 5 MB</small>
</div>
@if (uploadError) {
<p-message severity="error">{{uploadError}}</p-message>
}
<div class="dialog-footer">
<p-button
label="Cancel"
icon="pi pi-times"
(click)="cancel()"
severity="secondary"
outlined>
</p-button>
<p-button
label="Submit"
icon="pi pi-check"
(click)="submit()">
</p-button>
</div>
</div>
@@ -0,0 +1,82 @@
.upload-dialog-content {
display: flex;
flex-direction: column;
gap: 1.5rem;
padding: 1rem 0;
.upload-section {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
.file-selector {
display: flex;
align-items: center;
gap: 1rem;
}
.file-label {
font-weight: 500;
color: var(--text-color);
}
.file-input {
padding: 0.75rem;
border: 1px solid var(--border-color);
border-radius: var(--p-border-radius);
background: var(--ground-background);
}
.file-note {
color: var(--text-secondary-color);
font-size: 0.875rem;
margin-top: 0.25rem;
}
.selected-file {
color: var(--text-secondary-color);
font-style: italic;
}
}
.url-section {
display: flex;
flex-direction: column;
gap: 0.25rem;
.url-label {
font-weight: 500;
color: var(--text-color);
margin-bottom: 0.5rem;
}
.url-input {
width: 100%;
padding: 0.75rem;
}
.url-note {
color: var(--text-secondary-color);
font-size: 0.875rem;
margin-top: 0.25rem;
}
}
.or-text {
font-size: 0.9rem;
color: var(--text-color);
font-weight: 500;
}
p-message {
margin-top: 1rem;
}
.dialog-footer {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 1rem;
}
}
@@ -0,0 +1,72 @@
import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {ButtonModule} from 'primeng/button';
import {InputTextModule} from 'primeng/inputtext';
import {DividerModule} from 'primeng/divider';
import {MessageModule} from 'primeng/message';
import {BackgroundUploadService} from '../background-upload.service';
import {take} from 'rxjs';
@Component({
selector: 'app-upload-dialog',
standalone: true,
templateUrl: './upload-dialog.component.html',
styleUrls: ['./upload-dialog.component.scss'],
imports: [
CommonModule,
FormsModule,
ButtonModule,
InputTextModule,
DividerModule,
MessageModule
]
})
export class UploadDialogComponent {
private readonly dialogRef = inject(DynamicDialogRef);
private readonly backgroundUploadService = inject(BackgroundUploadService);
uploadImageUrl = '';
uploadFile: File | null = null;
uploadError = '';
onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
this.uploadFile = input.files[0];
this.uploadImageUrl = '';
}
}
submit() {
this.uploadError = '';
let upload$;
if (this.uploadFile) {
upload$ = this.backgroundUploadService.uploadFile(this.uploadFile);
} else if (this.uploadImageUrl.trim()) {
upload$ = this.backgroundUploadService.uploadUrl(this.uploadImageUrl.trim());
} else {
this.uploadError = 'Please select a file or paste a URL.';
return;
}
upload$.pipe(take(1)).subscribe({
next: (imageUrl) => {
if (imageUrl) {
this.dialogRef.close({ imageUrl });
} else {
this.uploadError = 'Failed to upload image.';
}
},
error: (err) => {
console.error('Upload failed:', err);
this.uploadError = 'Upload failed. Please try again.';
}
});
}
cancel() {
this.dialogRef.close();
}
}
@@ -0,0 +1,222 @@
import Aura from '@primeng/themes/aura';
type ColorPalette = Record<string, string>;
const customPalettes: Record<string, ColorPalette> = {
coralSunset: {
50: '#fef7f0',
100: '#feede1',
200: '#fcd9c2',
300: '#f9be9e',
400: '#f59673',
500: '#ef7550',
600: '#de5a3a',
700: '#b94730',
800: '#943a2e',
900: '#78322a',
950: '#401814'
},
roseBlush: {
50: '#fef7f7',
100: '#feebeb',
200: '#fddcdc',
300: '#fbbfbf',
400: '#f69393',
500: '#ed6767',
600: '#d93f3f',
700: '#b73030',
800: '#982d2d',
900: '#7f2d2d',
950: '#451313'
},
melonBlush: {
50: '#fffafb',
100: '#fff2f4',
200: '#ffdfe7',
300: '#ffcbd4',
400: '#ffaebb',
500: '#ff90a2',
600: '#ff6f88',
700: '#e8506b',
800: '#b7384d',
900: '#7f2231',
950: '#3f1118'
},
cottonCandy: {
50: '#fff9fb',
100: '#fff0f6',
200: '#ffdfee',
300: '#ffc0e0',
400: '#ffa3cf',
500: '#ff86bf',
600: '#ff69ad',
700: '#e14f93',
800: '#b93a72',
900: '#86284f',
950: '#42142a'
},
apricotSunrise: {
50: '#fffaf7',
100: '#fff1e8',
200: '#ffe2c9',
300: '#ffd2a8',
400: '#ffbf88',
500: '#ffad68',
600: '#ff974f',
700: '#e67a3b',
800: '#b6572b',
900: '#7f351b',
950: '#3f190f'
},
antiqueBronze: {
50: '#faf7f2',
100: '#f4ede0',
200: '#e8d9c0',
300: '#d9c199',
400: '#c8a56f',
500: '#b8904f',
600: '#a67c44',
700: '#8a6439',
800: '#715233',
900: '#5c442c',
950: '#302316'
},
butteryYellow: {
50: '#fffef7',
100: '#fffceb',
200: '#fff7d1',
300: '#ffeea7',
400: '#ffe072',
500: '#ffcf45',
600: '#ffb61f',
700: '#ff9b0a',
800: '#cc7606',
900: '#a35f0c',
950: '#633204'
},
vanillaCream: {
50: '#fefdfb',
100: '#fefbf6',
200: '#fdf5ea',
300: '#fbecd5',
400: '#f7dbb5',
500: '#f1c589',
600: '#e8a95c',
700: '#d88d3e',
800: '#b47134',
900: '#915c2e',
950: '#4e2f17'
},
citrusMint: {
50: '#fbfff9',
100: '#f4fff2',
200: '#e8ffd9',
300: '#d1ffbc',
400: '#b7ffa0',
500: '#96ff84',
600: '#76e96e',
700: '#4fb84c',
800: '#2f7f32',
900: '#1a4f20',
950: '#0a2410'
},
freshMint: {
50: '#f8fff9',
100: '#f0fff3',
200: '#dcffea',
300: '#bfffd6',
400: '#99ffc2',
500: '#7fffae',
600: '#5fe592',
700: '#3fbf75',
800: '#2d8f55',
900: '#1e5f39',
950: '#0f2f1d'
},
sagePearl: {
50: '#fbfdfb',
100: '#f4f8f4',
200: '#e6efe6',
300: '#d1e6d1',
400: '#bcdcbf',
500: '#9fcfa8',
600: '#84b792',
700: '#5f8f6e',
800: '#3f6648',
900: '#25442e',
950: '#0f2118'
},
skyBlue: {
50: '#f7fbff',
100: '#eef6ff',
200: '#dceefd',
300: '#c1e8ff',
400: '#99dfff',
500: '#6fc8ff',
600: '#48afff',
700: '#2e88e6',
800: '#2360b3',
900: '#153d80',
950: '#071d40'
},
periwinkleCream: {
50: '#fbfbff',
100: '#f2f3ff',
200: '#e7eaff',
300: '#d2dcff',
400: '#b9c9ff',
500: '#9fb2ff',
600: '#7f97ff',
700: '#5f78e6',
800: '#4559b3',
900: '#2b387f',
950: '#151c40'
},
pastelRoyalBlue: {
50: '#f6fbff',
100: '#eef6ff',
200: '#dbeeff',
300: '#b9ddff',
400: '#92c7ff',
500: '#63aaff',
600: '#3b88ff',
700: '#2e66cc',
800: '#235099',
900: '#183366',
950: '#0d1a33'
},
lavenderDream: {
50: '#fbf7ff',
100: '#f6eeff',
200: '#ebdcff',
300: '#dcc0ff',
400: '#caa1ff',
500: '#b47fff',
600: '#9366e6',
700: '#6f45b3',
800: '#4c2f80',
900: '#2d1b4f',
950: '#15082a'
},
dustyNeutral: {
50: '#faf9f7',
100: '#f3f1ed',
200: '#e8e3db',
300: '#d8cfc2',
400: '#c4b5a3',
500: '#b39c85',
600: '#a28a70',
700: '#87725d',
800: '#6f5e4e',
900: '#5a4e42',
950: '#2f2821'
}
};
if (!Aura.primitive) {
Aura.primitive = {};
}
Object.assign(Aura.primitive, customPalettes);
export default Aura;
@@ -0,0 +1,145 @@
import {MetadataRefreshOptions} from '../../features/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'
}
@@ -0,0 +1,5 @@
export interface AppState {
preset?: string;
primary?: string;
surface?: string;
}
@@ -0,0 +1,20 @@
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;
}
@@ -0,0 +1,435 @@
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});
}
}
@@ -0,0 +1,143 @@
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 '../../core/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,109 @@
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs';
import {RxStompService} from '../websocket/rx-stomp.service';
import {API_CONFIG} from '../../core/config/api-config';
import {createRxStompConfig} from '../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();
}
@@ -0,0 +1,15 @@
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({ providedIn: 'root' })
export class BookMetadataHostService {
private bookSwitchRequest$ = new Subject<number>();
requestBookSwitch(bookId: number) {
this.bookSwitchRequest$.next(bookId);
}
get bookSwitches$() {
return this.bookSwitchRequest$.asObservable();
}
}
@@ -0,0 +1,42 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/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,25 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface FileMoveRequest {
bookIds: number[];
moves: {
bookId: number;
targetLibraryId: number | null;
}[];
}
@Injectable({
providedIn: 'root'
})
export class FileOperationsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/files`;
private http = inject(HttpClient);
moveFiles(request: FileMoveRequest): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/move`, request);
}
}
@@ -0,0 +1,27 @@
import { Injectable, inject } from '@angular/core';
import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import { IconPickerComponent } from '../components/icon-picker-component/icon-picker-component';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class IconPickerService {
private dialog = inject(DialogService);
open(): Observable<string> {
const isMobile = window.innerWidth <= 768;
const ref: DynamicDialogRef = this.dialog.open(IconPickerComponent, {
header: 'Choose an Icon',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
}
});
return ref.onClose as Observable<string>;
}
}
@@ -0,0 +1,18 @@
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);
}
}
@@ -0,0 +1,25 @@
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);
}
}
@@ -0,0 +1,38 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface MetadataMatchWeights {
title: number;
subtitle: number;
description: number;
publisher: number;
publishedDate: number;
authors: number;
categories: number;
seriesName: number;
seriesNumber: number;
isbn13: number;
isbn10: number;
pageCount: number;
language: number;
amazonRating: number;
amazonReviewCount: number;
goodreadsRating: number;
goodreadsReviewCount: number;
hardcoverRating: number;
hardcoverReviewCount: number;
coverImage: number;
}
@Injectable({providedIn: 'root'})
export class MetadataMatchWeightsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
private http = inject(HttpClient);
recalculateAll(): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {});
}
}
@@ -0,0 +1,87 @@
import {inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subject, Subscription} from 'rxjs';
import {MetadataBatchProgressNotification} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../features/book/service/metadata-task';
import {UserService} from '../../features/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();
}
}
@@ -0,0 +1,60 @@
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});
}
}
@@ -0,0 +1,28 @@
import {Injectable, inject} from '@angular/core';
import {AuthService} from './auth.service';
import {UserService} from '../../features/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();
}
}
@@ -0,0 +1,26 @@
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 });
}
}
@@ -0,0 +1,55 @@
import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class UrlHelperService {
private readonly baseUrl = API_CONFIG.BASE_URL;
private readonly mediaBaseUrl = `${this.baseUrl}/api/v1/media`;
private authService = inject(AuthService);
private getToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
private appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getThumbnailUrl(bookId: number, coverUpdatedOn?: string): string {
if (!coverUpdatedOn) return 'assets/images/missing-cover.jpg';
const url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail?${coverUpdatedOn}`;
return this.appendToken(url);
}
getCoverUrl(bookId: number, coverUpdatedOn?: string): string {
if (!coverUpdatedOn) return 'assets/images/missing-cover.jpg';
const url = `${this.mediaBaseUrl}/book/${bookId}/cover?${coverUpdatedOn}`;
return this.appendToken(url);
}
getBackupCoverUrl(bookId: number): string {
const url = `${this.mediaBaseUrl}/book/${bookId}/backup-cover`;
return this.appendToken(url);
}
getBookdropCoverUrl(bookdropId: number): string {
const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`;
return this.appendToken(url);
}
getBackgroundImageUrl(lastUpdated?: number): string {
let url = `${this.mediaBaseUrl}/background`;
if (lastUpdated) {
url += `?t=${lastUpdated}`;
}
const token = this.getToken();
if (token) {
url += `${url.includes('?') ? '&' : '?'}token=${token}`;
}
return url;
}
}
@@ -0,0 +1,34 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import {API_CONFIG} from '../../core/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,7 +1,7 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
import {API_CONFIG} from '../../core/config/api-config';
export interface CoverImage {
url: string;
@@ -1,7 +1,7 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../config/api-config';
import {API_CONFIG} from '../../core/config/api-config';
@Injectable({
providedIn: 'root'
@@ -1,6 +1,6 @@
import { RxStompService } from './rx-stomp.service';
import { createRxStompConfig } from './rx-stomp.config';
import {AuthService} from '../../core/service/auth.service';
import {AuthService} from '../service/auth.service';
export function rxStompServiceFactory(authService: AuthService) {
const rxStomp = new RxStompService(authService);
@@ -1,6 +1,6 @@
import {RxStompConfig} from '@stomp/rx-stomp';
import {AuthService} from '../../core/service/auth.service';
import {API_CONFIG} from '../../config/api-config';
import {AuthService} from '../service/auth.service';
import {API_CONFIG} from '../../core/config/api-config';
export function createRxStompConfig(authService: AuthService): RxStompConfig {
return {

Some files were not shown because too many files have changed in this diff Show More