Introduce multi-format book support, including audiobooks (#2486)

* fix: support reading alternative book formats using bookType query param

* feat: add streaming reader support for alternative EPUB formats

* refactor: extract tabs section into MetadataTabsComponent

* feat: implement per-file reading progress tracking

* feat: add configurable format priority with cascading fallback

* refactor: redesign library creator with single-page layout

* refactor: unify reading progress into ReadingProgressService

* refactor: improve delete options with clearer file format and book deletion

* refactor: improve book format matching with normalization and fuzzy fallback

* feat: add folder-based audiobook support with ZIP downloads and preparing state

* fix: display unique format types in metadata viewer

* refactor: auto-attach files to single book in folder during rescan

* feat: implement folder-centric book file grouping with fuzzy matching

* refactor: consolidate book grouping with organization mode support

* fix: use folder hash for folder-based audiobooks in auto-attach

* fix: delete only BookFileEntity on file removal, not entire book

* fix: set folderBased flag and correct file size for auto-attached audiobook folders

* fix: use count query to avoid lazy initialization in file delete handler

* fix: preserve book metadata when file is moved by detecting hash match

* fix: skip books with no files in restoration to avoid NPE

* fix: round all progress percentages to one decimal place before sending to UI

* style: improve library creator dialog spacing and layout

* fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility

* fix: FileMoveService now handles multi-file BookEntity properly

* style: redesign metadata-picker and file-mover UI components

* style: redesign file-naming-pattern UI and improve theme contrast

* style: relax spacing in library-creator component

* style: tighten directory-picker layout for consistency

* fix: PathPatternResolver now respects folderBased flag for audiobooks

* style: move checkmark column to left side and add pending status in file-mover

* refactor: consolidate BookFileType into BookType and add audiobook styling

* feat: show 'Continue Reading' button for in-progress books

* fix: preserve dots in folder names during grouping and prevent duplicate attachments

* style: reduce gap between download-all button and primary file section

* style: shorten 'Continue Reading' button to 'Read' on mobile

* feat: add DISK_TYPE config to disable file moves on network storage

* style: standardize settings pages with shared styles and consistent spacing

* style: revamp settings pages with modern card-based layouts

* style: revamp OPDS, auth, and task management settings layouts

* fix: update FileMoveService tests to include AppProperties parameter

* fix: derive BookFileType from extension when uploading additional book files

* feat: show format type and size in download button with dropdown for alternatives

* feat: add audiobook streaming player with HTTP Range support

* feat: add M4B chapter extraction and chapter navigation

* feat: add audiobook bookmarks and sleep timer

* refactor: split AudiobookReaderService into focused services

* feat: add Media Session API for background audio playback

* feat: display file extensions in format tags with distinct colors and add audiobook upload support

* feat: require bookFileId for viewer settings API

* fix: show split button for audiobooks with readable alternatives

* feat: improve reading sessions table with book type badges and better formatting

* feat: add audiobook play button in files tab

* feat: use file extension for format display and meaningful tab values

* feat: add extension field to BookFile DTO

* feat: use extension field for book card format pill

* fix: use mixed orientation for format priority drag-drop to support multi-line layout

* feat: add attach book files feature to consolidate single-file books

* fix: increase drag handle size for format priority chips

* fix: add missing BookFileRepository mock to BookServiceDeleteTests

* feat: add delete buttons to files tab and move shelf to other items menu

* feat: add physical books support for cataloging books without digital files

* refactor: redesign icon-picker component with improved styling

* refactor: redesign metadata-picker component with improved layout and alignment

* refactor: move Add Physical Book to top of library menu

* refactor: use p-autoComplete for authors/categories in add-physical-book dialog

* feat: add square cover search and display support for audiobooks

* fix: navigate to first page when opening unread ebooks

* fix: exclude API requests from service worker interception

* feat: support fileless books with automatic file attachment

* fix: bypass service worker for audiobook streaming requests

* refactor: remove alphabetical filter sorting, default to count, limit filters to 100

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-27 10:12:50 -07:00
committed by GitHub
co-authored by acx10
parent c23e38b5a5
commit 3f334202b6
340 changed files with 23225 additions and 20727 deletions
@@ -0,0 +1,238 @@
<div class="add-physical-book">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-book header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Add Physical Book</h2>
<p class="panel-description">Catalog a physical book without a digital file</p>
</div>
<p-button
icon="pi pi-times"
(click)="cancel()"
severity="secondary"
[text]="true"
[rounded]="true"
class="close-button"
pTooltip="Close"
tooltipPosition="left"/>
</div>
<div class="form-container">
<div class="form-group highlight-group">
<label for="library" class="form-label">
<i class="pi pi-folder label-icon"></i>
Library
<span class="required-indicator">*</span>
</label>
<p-select
id="library"
[options]="libraries"
[(ngModel)]="selectedLibraryId"
optionLabel="name"
optionValue="id"
placeholder="Select a library"
[style]="{'width': '100%'}"/>
</div>
<div class="gradient-divider"></div>
<div class="form-row">
<div class="form-group highlight-group flex-2">
<label for="title" class="form-label">
<i class="pi pi-tag label-icon"></i>
Title
</label>
<div class="input-wrapper">
<input
id="title"
type="text"
pInputText
[(ngModel)]="title"
class="input-full"
placeholder="e.g., The Great Gatsby"
[class.filled]="title.trim()"/>
</div>
</div>
<div class="form-group highlight-group flex-1">
<label for="isbn" class="form-label">
<i class="pi pi-barcode label-icon"></i>
ISBN
</label>
<div class="input-wrapper">
<input
id="isbn"
type="text"
pInputText
[(ngModel)]="isbn"
class="input-full"
placeholder="e.g., 9780134685991"/>
</div>
</div>
</div>
<div class="gradient-divider"></div>
<div class="form-group highlight-group">
<label for="authors" class="form-label">
<i class="pi pi-user label-icon"></i>
Authors
</label>
<div class="autocomplete-wrapper">
<p-autoComplete
appendTo="body"
[(ngModel)]="authors"
[multiple]="true"
[fluid]="true"
[dropdown]="false"
[suggestions]="filteredAuthors"
[forceSelection]="false"
[showClear]="false"
placeholder="Type author name and press Enter"
(completeMethod)="filterAuthors($event)"
(onKeyUp)="onAutoCompleteKeyUp('authors', $event)"
(onSelect)="onAutoCompleteSelect('authors', $event)">
</p-autoComplete>
</div>
</div>
<div class="gradient-divider"></div>
<div class="form-group highlight-group">
<label for="description" class="form-label">
<i class="pi pi-align-left label-icon"></i>
Description
</label>
<textarea
id="description"
pTextarea
[(ngModel)]="description"
rows="3"
placeholder="Brief description of the book..."
class="input-full"></textarea>
</div>
<div class="gradient-divider"></div>
<div class="form-row">
<div class="form-group highlight-group flex-1">
<label for="publisher" class="form-label">
<i class="pi pi-building label-icon"></i>
Publisher
</label>
<input
id="publisher"
type="text"
pInputText
[(ngModel)]="publisher"
class="input-full"
placeholder="Publisher name"/>
</div>
<div class="form-group highlight-group flex-1">
<label for="publishedDate" class="form-label">
<i class="pi pi-calendar label-icon"></i>
Published Date
</label>
<input
id="publishedDate"
type="text"
pInputText
[(ngModel)]="publishedDate"
class="input-full"
placeholder="e.g., 2020 or 2020-05-15"/>
</div>
</div>
<div class="form-row">
<div class="form-group highlight-group flex-1">
<label for="language" class="form-label">
<i class="pi pi-globe label-icon"></i>
Language
</label>
<input
id="language"
type="text"
pInputText
[(ngModel)]="language"
class="input-full"
placeholder="e.g., English"/>
</div>
<div class="form-group highlight-group flex-1">
<label for="pageCount" class="form-label">
<i class="pi pi-file label-icon"></i>
Page Count
</label>
<p-inputnumber
id="pageCount"
[(ngModel)]="pageCount"
[useGrouping]="false"
placeholder="Number of pages"
class="input-full">
</p-inputnumber>
</div>
</div>
<div class="gradient-divider"></div>
<div class="form-group highlight-group">
<label for="categories" class="form-label">
<i class="pi pi-tags label-icon"></i>
Categories/Genres
</label>
<div class="autocomplete-wrapper">
<p-autoComplete
appendTo="body"
[(ngModel)]="categories"
[multiple]="true"
[fluid]="true"
[dropdown]="false"
[suggestions]="filteredCategories"
[forceSelection]="false"
[showClear]="true"
placeholder="Type category and press Enter"
(completeMethod)="filterCategories($event)"
(onKeyUp)="onAutoCompleteKeyUp('categories', $event)"
(onSelect)="onAutoCompleteSelect('categories', $event)">
</p-autoComplete>
</div>
</div>
</div>
<div class="dialog-footer">
<div class="validation-status">
@if (!selectedLibraryId) {
<div class="validation-message error">
<i class="pi pi-exclamation-circle"></i>
<span>Library is required</span>
</div>
} @else if (!title.trim() && !isbn.trim()) {
<div class="validation-message error">
<i class="pi pi-exclamation-circle"></i>
<span>Title or ISBN is required</span>
</div>
} @else {
<div class="validation-message success">
<i class="pi pi-check-circle"></i>
<span>Ready to create</span>
</div>
}
</div>
<div class="footer-actions">
<p-button
label="Cancel"
severity="secondary"
[outlined]="true"
(onClick)="cancel()"/>
<p-button
label="Add Physical Book"
icon="pi pi-plus"
severity="success"
(onClick)="createBook()"
[disabled]="!canCreate() || isLoading"
[loading]="isLoading"/>
</div>
</div>
</div>
@@ -0,0 +1,154 @@
@use '../../../../shared/styles/panel-shared' as panel;
.add-physical-book {
display: flex;
flex-direction: column;
min-width: 700px;
max-height: 90vh;
@media (max-width: 768px) {
min-width: auto;
width: 100%;
}
}
.panel-header {
@include panel.panel-header;
}
.form-container {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 1.25rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
overflow-y: auto;
max-height: calc(90vh - 200px);
@media (max-width: 480px) {
padding: 0.75rem;
gap: 0.375rem;
}
}
.form-row {
display: flex;
gap: 0.75rem;
@media (max-width: 640px) {
flex-direction: column;
gap: 0.5rem;
}
}
.flex-1 {
flex: 1;
}
.flex-2 {
flex: 2;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
&.highlight-group {
padding: 0.5rem;
}
@media (max-width: 480px) {
gap: 0.25rem;
&.highlight-group {
padding: 0.375rem;
}
}
}
.form-label {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.9rem;
font-weight: 600;
color: var(--text-color);
.label-icon {
color: var(--primary-color);
}
.required-indicator {
color: var(--p-red-500);
margin-left: 0.125rem;
}
@media (max-width: 480px) {
font-size: 0.85rem;
}
}
.input-wrapper {
position: relative;
.input-full {
width: 100%;
box-sizing: border-box;
}
}
.input-full {
width: 100%;
box-sizing: border-box;
}
.autocomplete-wrapper {
width: 100%;
p-autocomplete {
width: 100%;
}
}
.dialog-footer {
@include panel.dialog-footer;
border-top: none;
}
.validation-message {
@include panel.validation-message;
}
::ng-deep {
.p-inputnumber {
width: 100%;
}
.p-inputnumber-input {
width: 100%;
}
.p-autocomplete .p-chip .p-chip-label {
font-size: 12px;
}
.p-autocomplete-input-chip {
width: 2rem;
}
.p-autocomplete-clearable ul {
padding-inline-end: 2rem !important;
}
.p-autocomplete-clearable .p-autocomplete-clear-icon {
right: 0px;
margin-top: -1rem;
width: 2rem;
height: 2rem;
padding: 0.5rem;
}
}
@@ -0,0 +1,168 @@
import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {Tooltip} from 'primeng/tooltip';
import {Select} from 'primeng/select';
import {Textarea} from 'primeng/textarea';
import {InputNumber} from 'primeng/inputnumber';
import {AutoComplete, AutoCompleteCompleteEvent} from 'primeng/autocomplete';
import {BookService} from '../../service/book.service';
import {LibraryService} from '../../service/library.service';
import {Library} from '../../model/library.model';
import {CreatePhysicalBookRequest} from '../../model/book.model';
import {filter, take} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
@Component({
selector: 'app-add-physical-book-dialog',
standalone: true,
templateUrl: './add-physical-book-dialog.component.html',
imports: [
FormsModule,
Button,
InputText,
Tooltip,
Select,
Textarea,
InputNumber,
AutoComplete
],
styleUrl: './add-physical-book-dialog.component.scss',
})
export class AddPhysicalBookDialogComponent implements OnInit {
private dynamicDialogRef = inject(DynamicDialogRef);
private dialogConfig = inject(DynamicDialogConfig);
private bookService = inject(BookService);
private libraryService = inject(LibraryService);
private destroyRef = inject(DestroyRef);
libraries: Library[] = [];
selectedLibraryId: number | null = null;
title: string = '';
isbn: string = '';
authors: string[] = [];
description: string = '';
publisher: string = '';
publishedDate: string = '';
language: string = '';
pageCount: number | null = null;
categories: string[] = [];
allAuthors: string[] = [];
allCategories: string[] = [];
filteredAuthors: string[] = [];
filteredCategories: string[] = [];
isLoading: boolean = false;
ngOnInit(): void {
this.libraryService.libraryState$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(state => {
if (state.loaded && state.libraries) {
this.libraries = state.libraries;
if (this.dialogConfig.data?.libraryId) {
this.selectedLibraryId = this.dialogConfig.data.libraryId;
} else if (this.libraries.length > 0 && this.libraries[0].id !== undefined) {
this.selectedLibraryId = this.libraries[0].id;
}
}
});
this.prepareAutoComplete();
}
private prepareAutoComplete(): void {
this.bookService.bookState$
.pipe(
filter((bookState) => bookState.loaded),
take(1)
)
.subscribe((bookState) => {
const authors = new Set<string>();
const categories = new Set<string>();
(bookState.books ?? []).forEach((book) => {
book.metadata?.authors?.forEach((author) => authors.add(author));
book.metadata?.categories?.forEach((category) => categories.add(category));
});
this.allAuthors = Array.from(authors);
this.allCategories = Array.from(categories);
});
}
filterAuthors(event: AutoCompleteCompleteEvent): void {
const query = event.query.toLowerCase();
this.filteredAuthors = this.allAuthors.filter((author) =>
author.toLowerCase().includes(query)
);
}
filterCategories(event: AutoCompleteCompleteEvent): void {
const query = event.query.toLowerCase();
this.filteredCategories = this.allCategories.filter((category) =>
category.toLowerCase().includes(query)
);
}
onAutoCompleteKeyUp(fieldName: 'authors' | 'categories', event: KeyboardEvent): void {
if (event.key === 'Enter') {
const input = event.target as HTMLInputElement;
const value = input.value?.trim();
if (value) {
const values = this[fieldName];
if (!values.includes(value)) {
this[fieldName] = [...values, value];
}
input.value = '';
}
}
}
onAutoCompleteSelect(fieldName: 'authors' | 'categories', event: { value: string, originalEvent: Event }): void {
const values = this[fieldName];
if (!values.includes(event.value)) {
this[fieldName] = [...values, event.value];
}
(event.originalEvent.target as HTMLInputElement).value = '';
}
cancel(): void {
this.dynamicDialogRef.close();
}
canCreate(): boolean {
return !!this.selectedLibraryId && (!!this.title.trim() || !!this.isbn.trim());
}
createBook(): void {
if (!this.canCreate() || this.isLoading) return;
this.isLoading = true;
const request: CreatePhysicalBookRequest = {
libraryId: this.selectedLibraryId!,
title: this.title.trim() || undefined,
isbn: this.isbn.trim() || undefined,
authors: this.authors.length > 0 ? this.authors : undefined,
description: this.description.trim() || undefined,
publisher: this.publisher.trim() || undefined,
publishedDate: this.publishedDate.trim() || undefined,
language: this.language.trim() || undefined,
pageCount: this.pageCount ?? undefined,
categories: this.categories.length > 0 ? this.categories : undefined
};
this.bookService.createPhysicalBook(request).subscribe({
next: (book) => {
this.isLoading = false;
this.dynamicDialogRef.close(book);
},
error: () => {
this.isLoading = false;
}
});
}
}
@@ -370,7 +370,7 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user!.permissions.canMoveOrganizeFiles) {
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
<p-button
outlined="true"
icon="pi pi-arrows-h"
@@ -380,6 +380,17 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user!.permissions.canManageLibrary || userState.user!.permissions.admin) {
<p-button
outlined="true"
icon="pi pi-link"
severity="info"
(click)="attachFilesToBook()"
[disabled]="!canAttachFiles()"
pTooltip="Attach to Another Book"
tooltipPosition="top">
</p-button>
}
@if (hasBulkReadActionsItems) {
<div class="more-actions-wrapper">
<p-button
@@ -53,6 +53,7 @@ import {BookBrowserQueryParamsService, VIEW_MODES} from './book-browser-query-pa
import {BookBrowserEntityService} from './book-browser-entity.service';
import {BookFilterOrchestrationService} from './book-filter-orchestration.service';
import {BookBrowserScrollService} from './book-browser-scroll.service';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -97,6 +98,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
protected taskHelperService = inject(TaskHelperService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected bookSelectionService = inject(BookSelectionService);
protected appSettingsService = inject(AppSettingsService);
private activatedRoute = inject(ActivatedRoute);
private router = inject(Router);
@@ -730,6 +732,60 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.dialogHelperService.openFileMoverDialog(this.selectedBooks);
}
attachFilesToBook(): void {
// Get selected books that are single-file books (no alternative formats)
const currentState = this.bookService.getCurrentBookState();
const selectedBookIds = Array.from(this.selectedBooks);
const sourceBooks = (currentState.books || []).filter(book =>
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
);
if (sourceBooks.length === 0) {
this.messageService.add({
severity: 'warn',
summary: 'No Eligible Books',
detail: 'Selected books must be single-file books (no alternative formats).'
});
return;
}
// Check if all books are from the same library
const libraryIds = new Set(sourceBooks.map(b => b.libraryId));
if (libraryIds.size > 1) {
this.messageService.add({
severity: 'warn',
summary: 'Multiple Libraries',
detail: 'All selected books must be from the same library.'
});
return;
}
this.dynamicDialogRef = this.dialogHelperService.openBulkBookFileAttacherDialog(sourceBooks);
if (this.dynamicDialogRef) {
this.dynamicDialogRef.onClose.subscribe(result => {
if (result?.success) {
this.bookSelectionService.deselectAll();
}
});
}
}
canAttachFiles(): boolean {
if (this.selectedBooks.size === 0) return false;
const currentState = this.bookService.getCurrentBookState();
const selectedBookIds = Array.from(this.selectedBooks);
const eligibleBooks = (currentState.books || []).filter(book =>
selectedBookIds.includes(book.id) && !book.alternativeFormats?.length
);
if (eligibleBooks.length === 0) return false;
// Check if all eligible books are from the same library
const libraryIds = new Set(eligibleBooks.map(b => b.libraryId));
return libraryIds.size === 1;
}
user() {
return this.userService.getCurrentUser();
}
@@ -2,20 +2,21 @@
[class.selected]="isSelected"
(click)="onCardClick($event)">
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive, 'loaded': isImageLoaded }">
<div class="cover-container" [ngClass]="{ 'center-info-btn': _isSeriesViewActive, 'loaded': isImageLoaded, 'audiobook-cover': _isAudiobook }">
<img
[src]="coverImageUrl"
class="book-cover"
[class.loaded]="isImageLoaded"
[class.square-cover]="_isAudiobook"
[alt]="'Cover of ' + displayTitle"
loading="lazy"
decoding="async"
(load)="onImageLoad()"/>
<div class="top-left-overlay-stack">
@if (showBookTypePill && book.bookType) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + book.bookType.toLowerCase()">
{{ book.bookType }}
@if (showBookTypePill && getDisplayFormat(); as displayFormat) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + displayFormat.toLowerCase()">
{{ displayFormat }}
</div>
}
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
@@ -36,7 +37,7 @@
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
}
@if (!_isSeriesViewActive) {
@if (!_isSeriesViewActive && hasDigitalFile()) {
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
}
@@ -24,7 +24,6 @@
.book-cover {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px 8px 0 0;
opacity: 0;
transition: opacity 0.2s ease-in;
@@ -34,6 +33,14 @@
opacity: 1;
}
.book-cover.square-cover {
object-fit: contain;
}
.cover-container.audiobook-cover {
background-color: var(--surface-ground);
}
.cover-container::after {
content: "";
position: absolute;
@@ -288,6 +295,46 @@
color: #fff;
}
.book-type-audiobook {
background: var(--book-type-audiobook-color);
color: #fff;
}
.book-type-m4b {
background: var(--book-type-m4b-color);
color: #fff;
}
.book-type-mp3 {
background: var(--book-type-mp3-color);
color: #fff;
}
.book-type-m4a {
background: var(--book-type-m4a-color);
color: #fff;
}
.book-type-cbz {
background: var(--book-type-cbz-color);
color: #fff;
}
.book-type-cbr {
background: var(--book-type-cbr-color);
color: #fff;
}
.book-type-cb7 {
background: var(--book-type-cb7-color);
color: #fff;
}
.book-type-physical {
background: var(--book-type-physical-color);
color: #fff;
}
.read-status-indicator {
display: flex;
align-items: center;
@@ -24,6 +24,7 @@ import {BookDialogHelperService} from '../book-dialog-helper.service';
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
import {BookNavigationService} from '../../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
@Component({
selector: 'app-book-card',
@@ -66,6 +67,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
private bookDialogHelperService = inject(BookDialogHelperService);
private bookNavigationService = inject(BookNavigationService);
private cdr = inject(ChangeDetectorRef);
private appSettingsService = inject(AppSettingsService);
protected _progressPercentage: number | null = null;
protected _koProgressPercentage: number | null = null;
@@ -80,11 +82,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
protected _seriesCountTooltip: string = '';
protected _titleTooltip: string = '';
protected _hasProgress: boolean = false;
protected _isAudiobook: boolean = false;
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
private destroy$ = new Subject<void>();
protected readStatusHelper = inject(ReadStatusHelper);
private user: User | null = null;
private diskType: string = 'LOCAL';
private menuInitialized = false;
showBookTypePill = true;
@@ -104,6 +108,16 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route';
});
this.appSettingsService.appSettings$
.pipe(
filter(settings => !!settings),
take(1),
takeUntil(this.destroy$)
)
.subscribe(settings => {
this.diskType = settings?.diskType ?? 'LOCAL';
});
if (this.overlayPreferenceService) {
this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => {
this.showBookTypePill = val;
@@ -152,6 +166,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books';
this._titleTooltip = 'Title: ' + this._displayTitle;
this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK';
}
get hasProgress(): boolean {
@@ -446,7 +461,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
const items: MenuItem[] = [];
const moreActions: MenuItem[] = [];
if (this.user?.permissions.canMoveOrganizeFiles) {
if (this.user?.permissions.canMoveOrganizeFiles && this.diskType === 'LOCAL') {
moreActions.push({
label: 'Organize File',
icon: 'pi pi-arrows-h',
@@ -713,13 +728,28 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
});
}
private getFileExtension(filePath?: string): string | null {
getFileExtension(filePath?: string): string | null {
if (!filePath) return null;
const parts = filePath.split('.');
if (parts.length < 2) return null;
return parts.pop()?.toUpperCase() || null;
}
getDisplayFormat(): string | null {
if (!this.book?.primaryFile) {
return 'PHYSICAL';
}
const ext = this.book?.primaryFile?.extension;
if (ext) {
return ext.toUpperCase();
}
return this.getFileExtension(this.book?.primaryFile?.filePath);
}
hasDigitalFile(): boolean {
return !!this.book?.primaryFile;
}
private getFileIcon(fileType: string | null): string {
if (!fileType) return 'pi pi-file';
switch (fileType.toLowerCase()) {
@@ -734,6 +764,11 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
case 'cbr':
case 'cbx':
return 'pi pi-image';
case 'audiobook':
case 'm4b':
case 'm4a':
case 'mp3':
return 'pi pi-headphones';
default:
return 'pi pi-file';
}
@@ -15,6 +15,8 @@ import {BookMetadataCenterComponent} from '../../../metadata/component/book-meta
import {CoverSearchComponent} from '../../../metadata/component/cover-search/cover-search.component';
import {Book} from '../../model/book.model';
import {AdditionalFileUploaderComponent} from '../additional-file-uploader/additional-file-uploader.component';
import {BookFileAttacherComponent} from '../book-file-attacher/book-file-attacher.component';
import {AddPhysicalBookDialogComponent} from '../add-physical-book-dialog/add-physical-book-dialog.component';
@Injectable({providedIn: 'root'})
export class BookDialogHelperService {
@@ -152,4 +154,34 @@ export class BookDialogHelperService {
},
});
}
openBookFileAttacherDialog(sourceBook: Book): DynamicDialogRef | null {
return this.openDialog(BookFileAttacherComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
data: {
sourceBook: sourceBook,
},
});
}
openBulkBookFileAttacherDialog(sourceBooks: Book[]): DynamicDialogRef | null {
return this.openDialog(BookFileAttacherComponent, {
showHeader: false,
styleClass: `${DialogSize.MD} ${DialogStyle.MINIMAL}`,
data: {
sourceBooks: sourceBooks,
},
});
}
openAddPhysicalBookDialog(libraryId?: number): DynamicDialogRef | null {
return this.openDialog(AddPhysicalBookDialogComponent, {
showHeader: false,
styleClass: `${DialogSize.LG} ${DialogStyle.MINIMAL}`,
data: {
libraryId: libraryId,
},
});
}
}
@@ -48,7 +48,7 @@
</cdk-virtual-scroll-viewport>
@if (truncatedFilters[filterType]) {
<div class="truncation-notice">
Showing first 500 items
Showing first 100 items
</div>
}
}
@@ -60,7 +60,7 @@
</p-accordion>
<div class="footer-notice">
Note: Top 500 items are displayed per filter category
Note: Top 100 items are displayed per filter category
</div>
</div>
</div>
@@ -142,7 +142,7 @@ function getMatchScoreRangeFilters(score?: number | null): { id: string; name: s
}
function getBookTypeFilter(book: Book): { id: string; name: string }[] {
return book.bookType ? [{id: book.bookType, name: book.bookType}] : [];
return book.primaryFile?.bookType ? [{id: book.primaryFile.bookType, name: book.primaryFile.bookType}] : [];
}
export const readStatusLabels: Record<ReadStatus, string> = {
@@ -230,14 +230,14 @@ export class BookFilterComponent implements OnInit, OnDestroy {
userService = inject(UserService);
bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
userData$: Observable<UserState> = this.userService.userState$;
filterSortingMode: FilterSortingMode = 'alphabetical';
filterSortingMode: FilterSortingMode = 'count';
ngOnInit(): void {
this.userData$.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
).subscribe(userState => {
this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'alphabetical';
this.filterSortingMode = userState.user!.userSettings.filterSortingMode ?? 'count';
});
combineLatest([
@@ -344,8 +344,8 @@ export class BookFilterComponent implements OnInit, OnDestroy {
return aKey.localeCompare(bKey);
});
const isTruncated = sorted.length > 500;
const truncated = sorted.slice(0, 500);
const isTruncated = sorted.length > 100;
const truncated = sorted.slice(0, 100);
return {items: truncated, isTruncated};
}),
@@ -1,143 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {CoverScalePreferenceService} from './cover-scale-preference.service';
import {MessageService} from 'primeng/api';
import {LocalStorageService} from '../../../../shared/service/local-storage.service';
import {take} from 'rxjs/operators';
describe('CoverScalePreferenceService', () => {
let messageServiceMock: any;
let localStorageServiceMock: any;
beforeEach(() => {
messageServiceMock = {add: vi.fn()};
localStorageServiceMock = {
set: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
CoverScalePreferenceService,
{provide: MessageService, useValue: messageServiceMock},
{provide: LocalStorageService, useValue: localStorageServiceMock}
]
});
vi.useFakeTimers();
});
afterEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
});
it('should initialize with default scale if nothing in storage', () => {
localStorageServiceMock.get.mockReturnValueOnce(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
expect(service.scaleFactor).toBe(1.0);
});
it('should initialize with saved scale from storage', () => {
localStorageServiceMock.get.mockReturnValueOnce(1.5);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
expect(service.scaleFactor).toBe(1.5);
});
it('should ignore NaN value from storage', () => {
localStorageServiceMock.get.mockReturnValueOnce(NaN);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
expect(service.scaleFactor).toBe(1.0);
});
it('initScaleValue sets scaleFactor', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service.initScaleValue(2.2);
expect(service.scaleFactor).toBe(2.2);
service.initScaleValue(undefined);
expect(service.scaleFactor).toBe(1.0);
});
it('setScale updates scaleFactor and emits on scaleChange$', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
const spy = vi.fn();
service.scaleChange$.pipe(take(1)).subscribe(spy);
service.setScale(1.8);
expect(service.scaleFactor).toBe(1.8);
expect(spy).toHaveBeenCalledWith(1.8);
});
it('currentCardSize returns correct dimensions', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service.scaleFactor = 2;
expect(service.currentCardSize).toEqual({width: 270, height: 440});
service.scaleFactor = 0.5;
expect(service.currentCardSize).toEqual({width: 68, height: 110});
});
it('gridColumnMinWidth returns correct string', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service.scaleFactor = 1.23;
expect(service.gridColumnMinWidth).toBe(`${Math.round(135 * 1.23)}px`);
});
it('saveScalePreference saves to localStorage and shows success message', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service['saveScalePreference'](1.25);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.25);
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
severity: 'success',
summary: 'Cover Size Saved',
detail: expect.stringContaining('1.25')
}));
});
it('saveScalePreference handles errors and shows error message', () => {
localStorageServiceMock.get.mockReturnValue(null);
localStorageServiceMock.set.mockImplementation(() => {
throw new Error('fail');
});
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service['saveScalePreference'](1.1);
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
severity: 'error',
summary: 'Save Failed'
}));
});
it('setScale triggers debounced saveScalePreference', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service.setScale(1.7);
vi.advanceTimersByTime(1000);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.7);
});
it('debounced save only triggers once for rapid setScale calls', () => {
localStorageServiceMock.get.mockReturnValue(null);
const injector = TestBed.inject(EnvironmentInjector);
const service = runInInjectionContext(injector, () => TestBed.inject(CoverScalePreferenceService));
service.setScale(1.1);
service.setScale(1.2);
service.setScale(1.3);
vi.advanceTimersByTime(1000);
expect(localStorageServiceMock.set).toHaveBeenCalledTimes(1);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('coverScalePreference', 1.3);
});
});
@@ -1,167 +0,0 @@
import {beforeEach, describe, expect, it} from 'vitest';
import {Subject} from 'rxjs';
import {HeaderFilter} from './HeaderFilter';
import {BookState} from '../../../model/state/book-state.model';
const makeBook = (overrides: any = {}) => ({
id: 1,
metadata: {
bookId: 1,
title: 'Test Title',
authors: ['John Doe'],
seriesName: 'Test Series',
categories: ['Fiction'],
isbn10: '1234567890',
isbn13: '9781234567897',
...overrides.metadata
},
...overrides
});
const baseState: BookState = {
books: [
makeBook(),
makeBook({id: 2, metadata: {bookId: 2, title: 'Another Book', authors: ['Jane Smith'], seriesName: 'Another Series', categories: ['Nonfiction'], isbn10: '0987654321', isbn13: '9780987654321'}}),
makeBook({id: 3, metadata: {bookId: 3, title: 'Éxample Łatin', authors: ['Åuthor Æther'], seriesName: 'Série', categories: ['Categøry'], isbn10: 'ø123', isbn13: 'æ456'}}),
makeBook({id: 4, metadata: {bookId: 4, title: 'Special!@#$', authors: ['O\'Connor'], seriesName: '', categories: [], isbn10: '', isbn13: ''}})
],
loaded: true,
error: null
};
describe('HeaderFilter', () => {
let search$: Subject<string>;
let filter: HeaderFilter;
beforeEach(() => {
search$ = new Subject<string>();
filter = new HeaderFilter(search$.asObservable());
});
it('returns original state if search term is less than 2 chars', () => {
filter.filter(baseState).subscribe(result => {
expect(result).toBe(baseState);
});
search$.next('a');
});
it('filters by title (case-insensitive, normalized)', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.title).toBe('Test Title');
});
search$.next('test');
});
it('filters by author', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.authors?.[0]).toBe('Jane Smith');
});
search$.next('smith');
});
const expectBooksWithTitles = (searchTerm: string, expectedCount: number, expectedTitles: string[]) => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(expectedCount);
const titles = result.books?.map(b => b.metadata?.title);
expectedTitles.forEach(title => expect(titles).toContain(title));
});
search$.next(searchTerm);
};
it('filters by series', () => {
expectBooksWithTitles('series', 2, ['Test Title', 'Another Book']);
});
it('filters by category', () => {
expectBooksWithTitles('fiction', 2, ['Test Title', 'Another Book']);
});
it('filters by isbn10', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.isbn10).toBe('1234567890');
});
search$.next('1234567890');
});
it('filters by isbn13', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.isbn13).toBe('9780987654321');
});
search$.next('9780987654321');
});
it('normalizes diacritics and special chars', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.title).toBe('Éxample Łatin');
});
search$.next('example latin');
});
it('normalizes special Unicode chars in categories (ø -> o)', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.categories?.[0]).toBe('Categøry');
});
search$.next('category');
});
it('removes punctuation and matches', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books?.length).toBe(1);
expect(result.books?.[0]?.metadata?.title).toBe('Special!@#$');
});
search$.next('special');
});
it('returns empty books if no match', () => {
filter.filter(baseState).subscribe(result => {
expect(result.books).toEqual([]);
});
search$.next('notfound');
});
it('handles undefined fields gracefully', () => {
const state: BookState = {
books: [
{
id: 5,
bookType: 'EPUB',
libraryId: 1,
libraryName: 'Test Library',
metadata: {
bookId: 5,
title: undefined,
authors: undefined,
seriesName: undefined,
categories: undefined,
isbn10: undefined,
isbn13: undefined
}
}
],
loaded: true,
error: null
};
filter.filter(state).subscribe(result => {
expect(result.books).toEqual([]);
});
search$.next('anything');
});
it('distinctUntilChanged prevents duplicate emissions for same search term', async () => {
const emissions: any[] = [];
const subscription = filter.filter(baseState).subscribe(result => {
emissions.push(result);
});
search$.next('test');
search$.next('test');
await new Promise(resolve => setTimeout(resolve, 600));
expect(emissions.length).toBe(1);
subscription.unsubscribe();
});
});
@@ -1,244 +0,0 @@
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {BehaviorSubject, firstValueFrom, of, Subject} from 'rxjs';
import {SeriesCollapseFilter} from './SeriesCollapseFilter';
import {MessageService} from 'primeng/api';
import {UserService} from '../../../../settings/user-management/user.service';
import {BookState} from '../../../model/state/book-state.model';
import {Book} from '../../../model/book.model';
describe('SeriesCollapseFilter', () => {
let userServiceMock: any;
let messageServiceMock: any;
let userStateSubject: BehaviorSubject<any>;
let currentUser: any;
beforeEach(() => {
userStateSubject = new BehaviorSubject({
user: null,
loaded: false,
error: null
});
currentUser = {
id: 1,
userSettings: {
entityViewPreferences: {
global: {seriesCollapsed: false},
overrides: []
}
}
};
userServiceMock = {
userState$: userStateSubject.asObservable(),
getCurrentUser: vi.fn(() => currentUser),
updateUserSetting: vi.fn()
};
messageServiceMock = {add: vi.fn()};
TestBed.configureTestingModule({
providers: [
SeriesCollapseFilter,
{provide: UserService, useValue: userServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
vi.useFakeTimers();
});
afterEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
});
function createService(): SeriesCollapseFilter {
const injector = TestBed.inject(EnvironmentInjector);
return runInInjectionContext(injector, () => TestBed.inject(SeriesCollapseFilter));
}
it('should initialize with default collapsed=false', () => {
const service = createService();
expect(service.isSeriesCollapsed).toBe(false);
});
it('should apply global preference on userState$ emit', () => {
currentUser.userSettings.entityViewPreferences.global.seriesCollapsed = true;
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
const service = createService();
userStateSubject.next({user: currentUser, loaded: true, error: null});
expect(service.isSeriesCollapsed).toBe(true);
});
it('should apply override preference for context', () => {
currentUser.userSettings.entityViewPreferences.overrides = [
{entityType: 'LIBRARY', entityId: 42, preferences: {seriesCollapsed: true}}
];
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
const service = createService();
service.setContext('LIBRARY', 42);
userStateSubject.next({user: currentUser, loaded: true, error: null});
expect(service.isSeriesCollapsed).toBe(true);
});
it('should fallback to old seriesCollapse field for global', () => {
currentUser.userSettings.entityViewPreferences.global = {seriesCollapse: true};
delete currentUser.userSettings.entityViewPreferences.global.seriesCollapsed;
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
const service = createService();
userStateSubject.next({user: currentUser, loaded: true, error: null});
expect(service.isSeriesCollapsed).toBe(true);
});
it('should fallback to old seriesCollapse field for override', () => {
currentUser.userSettings.entityViewPreferences.overrides = [
{entityType: 'SHELF', entityId: 99, preferences: {seriesCollapse: true}}
];
userServiceMock.getCurrentUser.mockReturnValue(currentUser);
const service = createService();
service.setContext('SHELF', 99);
userStateSubject.next({user: currentUser, loaded: true, error: null});
expect(service.isSeriesCollapsed).toBe(true);
});
it('setCollapsed should update value and trigger persistence after debounce', () => {
const service = createService();
service.setCollapsed(true);
expect(service.isSeriesCollapsed).toBe(true);
vi.advanceTimersByTime(500);
expect(userServiceMock.updateUserSetting).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
severity: 'success',
summary: 'Preference Saved',
detail: expect.stringContaining('enabled')
}));
});
it('setCollapsed should persist override if context set', () => {
const service = createService();
service.setContext('MAGIC_SHELF', 123);
service.setCollapsed(true);
vi.advanceTimersByTime(500);
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
1,
'entityViewPreferences',
expect.objectContaining({
overrides: expect.arrayContaining([
expect.objectContaining({
entityType: 'MAGIC_SHELF',
entityId: 123,
preferences: expect.objectContaining({seriesCollapsed: true})
})
])
})
);
});
it('setCollapsed should persist global if no context', () => {
const service = createService();
service.setCollapsed(true);
vi.advanceTimersByTime(500);
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(
1,
'entityViewPreferences',
expect.objectContaining({
global: expect.objectContaining({seriesCollapsed: true})
})
);
});
it('should not persist if no user', () => {
userServiceMock.getCurrentUser.mockReturnValue(null);
const service = createService();
service.setCollapsed(true);
vi.advanceTimersByTime(500);
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
});
it('should filter books and collapse series', async () => {
const service = createService();
service.setCollapsed(true);
const books: Book[] = [
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any,
{id: 3, metadata: {seriesName: 'B', seriesNumber: 1}, title: 'B3'} as any,
{id: 4, metadata: {}, title: 'B4'} as any
];
const state: BookState = {books, loaded: true, error: null};
const result = await firstValueFrom(service.filter(state));
expect(result && result.books).toBeTruthy();
if (!result || !result.books) throw new Error('No books in result');
expect(result.books.length).toBe(3);
// Series A collapsed to one book with seriesBooks of length 2
const a = result.books.find(b => b.metadata?.seriesName === 'A');
expect(a).toBeDefined();
expect(a?.seriesBooks?.length).toBe(2);
expect(a?.seriesCount).toBe(2);
// Series B collapsed to one book with seriesBooks of length 1
const b = result.books.find(b => b.metadata?.seriesName === 'B');
expect(b).toBeDefined();
expect(b?.seriesBooks?.length).toBe(1);
expect(b?.seriesCount).toBe(1);
// Non-series book remains
expect(result.books.some(b => b['title'] === 'B4')).toBe(true);
});
it('should not collapse series if forceExpandSeries=true', async () => {
const service = createService();
service.setCollapsed(true);
const books: Book[] = [
{id: 1, metadata: {seriesName: 'A', seriesNumber: 2}, title: 'B1'} as any,
{id: 2, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B2'} as any
];
const state: BookState = {books, loaded: true, error: null};
const result = await firstValueFrom(service.filter(state, true));
expect(result && result.books).toBeTruthy();
if (!result || !result.books) throw new Error('No books in result');
expect(result.books.length).toBe(2);
});
it('should return original state if books is null', async () => {
const service = createService();
service.setCollapsed(true);
const state: BookState = {books: null, loaded: true, error: null};
const result = await firstValueFrom(service.filter(state));
expect(result).toBe(state);
});
it('should not collapse if isSeriesCollapsed is false', async () => {
const service = createService();
service.setCollapsed(false);
const books: Book[] = [
{id: 1, metadata: {seriesName: 'A', seriesNumber: 1}, title: 'B1'} as any
];
const state: BookState = {books, loaded: true, error: null};
const result = await firstValueFrom(service.filter(state));
expect(result && result.books).toBeTruthy();
if (!result || !result.books) throw new Error('No books in result');
expect(result.books.length).toBe(1);
expect(result.books[0]?.seriesBooks).toBeUndefined();
});
it('should clean up destroy$ on ngOnDestroy', () => {
const service = createService();
const spy = vi.spyOn(service['destroy$'], 'next');
service.ngOnDestroy();
expect(spy).toHaveBeenCalled();
});
it('setContext(null, null) resets context and applies preference', () => {
const service = createService();
const applyPrefSpy = vi.spyOn(service as any, 'applyPreference');
service.setContext(null, null);
expect((service as any).currentContext).toBeNull();
expect(applyPrefSpy).toHaveBeenCalled();
});
});
@@ -1,629 +0,0 @@
import {beforeEach, describe, expect, it} from 'vitest';
import {BehaviorSubject, firstValueFrom} from 'rxjs';
import {doesBookMatchReadStatus, isFileSizeInRange, isMatchScoreInRange, isPageCountInRange, isRatingInRange, isRatingInRange10, SideBarFilter} from './SidebarFilter';
import {BookState} from '../../../model/state/book-state.model';
import {Book, ReadStatus} from '../../../model/book.model';
import {Shelf} from '../../../model/shelf.model';
describe('SidebarFilter helpers', () => {
it('isRatingInRange returns true for value in range', () => {
expect(isRatingInRange(3.0, '3to4')).toBe(true);
expect(isRatingInRange(3.99, '3to4')).toBe(true);
expect(isRatingInRange(4.0, '3to4')).toBe(false);
});
it('isRatingInRange returns false for value out of range', () => {
expect(isRatingInRange(4.5, '3to4')).toBe(false);
expect(isRatingInRange(2.9, '3to4')).toBe(false);
});
it('isRatingInRange10 matches rounded rating', () => {
expect(isRatingInRange10(7.2, '7')).toBe(true);
expect(isRatingInRange10(7.7, '8')).toBe(true);
expect(isRatingInRange10(7.2, '8')).toBe(false);
});
it('isFileSizeInRange returns true for value in range', () => {
expect(isFileSizeInRange(0, '<1mb')).toBe(true);
expect(isFileSizeInRange(1023, '<1mb')).toBe(true);
expect(isFileSizeInRange(1024, '<1mb')).toBe(false);
});
it('isFileSizeInRange returns false for value out of range', () => {
expect(isFileSizeInRange(2000, '<1mb')).toBe(false);
expect(isFileSizeInRange(-1, '<1mb')).toBe(false);
});
it('isPageCountInRange returns true for value in range', () => {
expect(isPageCountInRange(100, '100to200')).toBe(true);
expect(isPageCountInRange(199, '100to200')).toBe(true);
expect(isPageCountInRange(200, '100to200')).toBe(false);
});
it('isPageCountInRange returns false for value out of range', () => {
expect(isPageCountInRange(50, '100to200')).toBe(false);
expect(isPageCountInRange(200, '100to200')).toBe(false);
});
it('isMatchScoreInRange returns true for value in range', () => {
expect(isMatchScoreInRange(0.80, '0.80-0.89')).toBe(true);
expect(isMatchScoreInRange(0.89, '0.80-0.89')).toBe(true);
expect(isMatchScoreInRange(0.90, '0.80-0.89')).toBe(false);
expect(isMatchScoreInRange(85, '0.80-0.89')).toBe(true);
});
it('isMatchScoreInRange returns false for value out of range', () => {
expect(isMatchScoreInRange(0.5, '0.80-0.89')).toBe(false);
expect(isMatchScoreInRange(0.95, '0.80-0.89')).toBe(false);
});
it('doesBookMatchReadStatus returns true if status matches', () => {
const book = {readStatus: ReadStatus.READ} as Book;
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(true);
});
it('doesBookMatchReadStatus returns false if status does not match', () => {
const book = {readStatus: ReadStatus.UNREAD} as Book;
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
});
it('doesBookMatchReadStatus returns true for unset if included', () => {
const book = {} as Book;
expect(doesBookMatchReadStatus(book, [ReadStatus.UNSET])).toBe(true);
});
it('isRatingInRange returns false for unknown rangeId', () => {
expect(isRatingInRange(3.5, 'not-a-range')).toBe(false);
});
it('isRatingInRange returns false for null/undefined rating', () => {
expect(isRatingInRange(undefined, '3to4')).toBe(false);
expect(isRatingInRange(null, '3to4')).toBe(false);
});
it('isRatingInRange10 returns false for null/undefined rating', () => {
expect(isRatingInRange10(undefined, '7')).toBe(false);
expect(isRatingInRange10(null, '7')).toBe(false);
});
it('isFileSizeInRange returns false for unknown rangeId', () => {
expect(isFileSizeInRange(500, 'not-a-range')).toBe(false);
});
it('isFileSizeInRange returns false for null/undefined fileSize', () => {
expect(isFileSizeInRange(undefined, '<1mb')).toBe(false);
});
it('isPageCountInRange returns false for unknown rangeId', () => {
expect(isPageCountInRange(150, 'not-a-range')).toBe(false);
});
it('isPageCountInRange returns false for null/undefined pageCount', () => {
expect(isPageCountInRange(undefined, '100to200')).toBe(false);
});
it('isMatchScoreInRange returns false for unknown rangeId', () => {
expect(isMatchScoreInRange(0.85, 'not-a-range')).toBe(false);
});
it('isMatchScoreInRange returns false for null/undefined score', () => {
expect(isMatchScoreInRange(undefined, '0.80-0.89')).toBe(false);
expect(isMatchScoreInRange(null, '0.80-0.89')).toBe(false);
});
it('doesBookMatchReadStatus returns false if selected is empty', () => {
const book = {readStatus: ReadStatus.READ} as Book;
expect(doesBookMatchReadStatus(book, [])).toBe(false);
});
it('doesBookMatchReadStatus returns false if status is not in selected', () => {
const book = {readStatus: ReadStatus.READING} as Book;
expect(doesBookMatchReadStatus(book, [ReadStatus.READ])).toBe(false);
});
});
describe('SideBarFilter', () => {
let books: Book[];
let bookState: BookState;
beforeEach(() => {
// Create fresh book objects for each test to prevent mutation pollution
books = [
{
id: 1,
libraryId: 1,
libraryName: 'Lib1',
metadata: {
bookId: 1,
authors: ['A1'],
categories: ['C1'],
moods: ['M1'],
tags: ['T1'],
publisher: 'P1',
seriesName: 'S1',
amazonRating: 4.2,
goodreadsRating: 3.8,
hardcoverRating: 4.0,
ranobedbRating: 3.5,
publishedDate: '2020-01-01',
pageCount: 150,
language: 'en'
},
personalRating: 7,
fileSizeKb: 500,
shelves: [{name: 'shelf1', icon: 'icon1'}] as Shelf[],
metadataMatchScore: 0.8,
bookType: 'EPUB',
readStatus: ReadStatus.READ
} as Book,
{
id: 2,
libraryId: 1,
libraryName: 'Lib1',
metadata: {
bookId: 2,
authors: ['A2'],
categories: ['C2'],
moods: ['M2'],
tags: ['T2'],
publisher: 'P2',
seriesName: 'S2',
amazonRating: 2.5,
goodreadsRating: 2.8,
hardcoverRating: 2.0,
ranobedbRating: 2.4,
publishedDate: '2019-01-01',
pageCount: 50,
language: 'fr'
},
personalRating: 3,
fileSizeKb: 2000,
shelves: [] as Shelf[],
metadataMatchScore: 0.5,
bookType: 'PDF',
readStatus: ReadStatus.UNREAD
} as Book
];
bookState = {books, loaded: true, error: null};
});
function filterWith(activeFilters: any, mode: 'and' | 'or' = 'and') {
const filter$ = new BehaviorSubject(activeFilters);
const mode$ = new BehaviorSubject(mode);
const filter = new SideBarFilter(filter$, mode$);
return filter.filter(bookState);
}
it('filters by author (and mode)', async () => {
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.authors).toContain('A1');
});
it('filters by author (or mode)', async () => {
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by category', async () => {
const result = await firstValueFrom(filterWith({category: ['C2']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.categories).toContain('C2');
});
it('filters by mood', async () => {
const result = await firstValueFrom(filterWith({mood: ['M1']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.moods).toContain('M1');
});
it('filters by tag', async () => {
const result = await firstValueFrom(filterWith({tag: ['T2']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.tags).toContain('T2');
});
it('filters by publisher', async () => {
const result = await firstValueFrom(filterWith({publisher: ['P1']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.publisher).toBe('P1');
});
it('filters by series', async () => {
const result = await firstValueFrom(filterWith({series: ['S2']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.seriesName).toBe('S2');
});
it('filters by readStatus', async () => {
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ]}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.readStatus).toBe(ReadStatus.READ);
});
it('filters by amazonRating', async () => {
const result = await firstValueFrom(filterWith({amazonRating: ['4to4.5']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.amazonRating).toBeGreaterThanOrEqual(4);
});
it('filters by goodreadsRating', async () => {
const result = await firstValueFrom(filterWith({goodreadsRating: ['3to4']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.goodreadsRating).toBeGreaterThanOrEqual(3);
});
it('filters by hardcoverRating', async () => {
const result = await firstValueFrom(filterWith({hardcoverRating: ['2to3']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.hardcoverRating).toBeGreaterThanOrEqual(2);
});
it('filters by ranobedbRating', async () => {
const result = await firstValueFrom(filterWith({ranobedbRating: ['3to4']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.ranobedbRating).toBeGreaterThanOrEqual(3);
});
it('filters by personalRating', async () => {
const result = await firstValueFrom(filterWith({personalRating: ['7']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.personalRating).toBe(7);
});
it('filters by shelfStatus unshelved', async () => {
const result = await firstValueFrom(filterWith({shelfStatus: ['unshelved']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.shelves?.length).toBe(0);
});
it('filters by fileSize', async () => {
const result = await firstValueFrom(filterWith({fileSize: ['<1mb']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.fileSizeKb).toBeLessThan(1024);
});
it('filters by language', async () => {
const result = await firstValueFrom(filterWith({language: ['fr']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.language).toBe('fr');
});
it('filters by pageCount', async () => {
const result = await firstValueFrom(filterWith({pageCount: ['100to200']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadata?.pageCount).toBeGreaterThanOrEqual(100);
});
it('filters by matchScore', async () => {
const result = await firstValueFrom(filterWith({matchScore: ['0.80-0.89']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.metadataMatchScore).toBeGreaterThanOrEqual(0.8);
});
it('filters by bookType', async () => {
const result = await firstValueFrom(filterWith({bookType: ['PDF']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.bookType).toBe('PDF');
});
it('returns all books if no filters', async () => {
const result = await firstValueFrom(filterWith({}, 'and'));
expect(result?.books?.length).toBe(2);
});
it('returns all books if filters is null', async () => {
const filter$ = new BehaviorSubject(null);
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(bookState));
expect(result?.books?.length).toBe(2);
});
it('returns original state if books is null', async () => {
bookState.books = null as any;
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
expect(result).toBe(bookState);
expect(result.books).toBeNull();
});
it('returns original state if books is undefined', async () => {
bookState.books = undefined as any;
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
expect(result).toBe(bookState);
expect(result.books).toBeUndefined();
});
it('returns empty books array for empty bookState', async () => {
bookState.books = [];
const result = await firstValueFrom(filterWith({author: ['A1']}, 'and'));
expect(result?.books?.length).toBe(0);
});
it('filters by multiple authors in OR mode', async () => {
const result = await firstValueFrom(filterWith({author: ['A1', 'A2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by multiple categories in OR mode', async () => {
const result = await firstValueFrom(filterWith({category: ['C1', 'C2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by multiple moods in OR mode', async () => {
const result = await firstValueFrom(filterWith({mood: ['M1', 'M2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by multiple tags in OR mode', async () => {
const result = await firstValueFrom(filterWith({tag: ['T1', 'T2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by multiple publishers in OR mode', async () => {
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('filters by multiple series in OR mode', async () => {
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('returns true for empty filter values in OR mode', async () => {
const result = await firstValueFrom(filterWith({author: []}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('returns false for empty filter values in AND mode', async () => {
const result = await firstValueFrom(filterWith({author: []}, 'and'));
expect(result?.books?.length).toBe(0);
});
it('filters with multiple filter types in AND mode', async () => {
const result = await firstValueFrom(filterWith({
author: ['A1'],
category: ['C1'],
readStatus: [ReadStatus.READ]
}, 'and'));
expect(result?.books?.length).toBe(1);
});
it('filters with multiple filter types in OR mode', async () => {
const result = await firstValueFrom(filterWith({
author: ['A1'],
category: ['C2']
}, 'or'));
expect(result?.books?.length).toBe(2);
});
it('returns false for unknown filter type', async () => {
const result = await firstValueFrom(filterWith({unknownFilter: ['value']}, 'and'));
expect(result?.books?.length).toBe(0);
});
it('filters by shelfStatus shelved', async () => {
const result = await firstValueFrom(filterWith({shelfStatus: ['shelved']}, 'and'));
expect(result?.books?.length).toBe(1);
expect(result?.books?.[0]?.shelves?.length).toBeGreaterThan(0);
});
it('returns false for book without publishedDate', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, publishedDate: undefined}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({publishedDate: [2020]});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
expect(result?.books?.length).toBe(0);
});
it('filters by multiple authors in AND mode - all must match', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, authors: ['A1', 'A3']}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({author: ['A1', 'A3']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
expect(result?.books?.length).toBe(1);
});
it('filters by multiple categories in AND mode - all must match', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, categories: ['C1', 'C3']}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({category: ['C1', 'C3']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
expect(result?.books?.length).toBe(1);
});
it('filters by multiple moods in AND mode - all must match', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, moods: ['M1', 'M3']}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({mood: ['M1', 'M3']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
expect(result?.books?.length).toBe(1);
});
it('filters by multiple tags in AND mode - all must match', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, tags: ['T1', 'T3']}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({tag: ['T1', 'T3']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
expect(result?.books?.length).toBe(1);
});
it('filters by multiple publishers in AND mode - returns books matching all', async () => {
// Publisher can only have one value, so AND with multiple should return nothing
const result = await firstValueFrom(filterWith({publisher: ['P1', 'P2']}, 'and'));
expect(result?.books?.length).toBe(0);
});
it('filters by multiple series in AND mode - returns books matching all', async () => {
// Series can only have one value, so AND with multiple should return nothing
const result = await firstValueFrom(filterWith({series: ['S1', 'S2']}, 'and'));
expect(result?.books?.length).toBe(0);
});
it('handles book with null metadata', async () => {
const testBooks: Book[] = [
{...books[0], metadata: null as any},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({author: ['A1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
expect(result?.books?.length).toBe(0);
});
it('handles book with undefined metadata', async () => {
const testBooks: Book[] = [
{...books[0], metadata: undefined as any},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({author: ['A1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has undefined metadata, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null authors array', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, authors: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({author: ['A1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
expect(result?.books?.length).toBe(0);
});
it('handles book with undefined authors array', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, authors: undefined as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({author: ['A1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has undefined authors, so it doesn't match. Book 2 has author 'A2', doesn't match 'A1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null categories array', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, categories: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({category: ['C1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null categories, so it doesn't match. Book 2 has category 'C2', doesn't match 'C1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null moods array', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, moods: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({mood: ['M1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null moods, so it doesn't match. Book 2 has mood 'M2', doesn't match 'M1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null tags array', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, tags: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({tag: ['T1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null tags, so it doesn't match. Book 2 has tag 'T2', doesn't match 'T1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null publisher', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, publisher: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({publisher: ['P1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null publisher, so it doesn't match. Book 2 has publisher 'P2', doesn't match 'P1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null series', async () => {
const testBooks: Book[] = [
{...books[0], metadata: {...books[0].metadata!, seriesName: null as any}},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({series: ['S1']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null series, so it doesn't match. Book 2 has series 'S2', doesn't match 'S1'
expect(result?.books?.length).toBe(0);
});
it('handles book with null shelves', async () => {
const testBooks: Book[] = [
{...books[0], shelves: null as any},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has null shelves (unshelved), book 2 has empty shelves array (also unshelved)
expect(result?.books?.length).toBe(2);
});
it('handles book with undefined shelves', async () => {
const testBooks: Book[] = [
{...books[0], shelves: undefined as any},
{...books[1]}
];
const testState = {...bookState, books: testBooks};
const filter$ = new BehaviorSubject({shelfStatus: ['unshelved']});
const mode$ = new BehaviorSubject<'and' | 'or'>('and');
const filter = new SideBarFilter(filter$, mode$);
const result = await firstValueFrom(filter.filter(testState));
// Book 1 has undefined shelves (unshelved), book 2 has empty shelves array (also unshelved)
expect(result?.books?.length).toBe(2);
});
it('filters by multiple readStatus values', async () => {
const result = await firstValueFrom(filterWith({readStatus: [ReadStatus.READ, ReadStatus.UNREAD]}, 'and'));
expect(result?.books?.length).toBe(2);
});
it('handles non-array filter values', async () => {
const result = await firstValueFrom(filterWith({author: 'A1' as any}, 'and'));
expect(result?.books?.length).toBe(0);
});
});
@@ -123,7 +123,7 @@ export class SideBarFilter implements BookFilter {
case 'matchScore':
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range));
case 'bookType':
return filterValues.includes(book.bookType);
return filterValues.includes(book.primaryFile?.bookType);
default:
return false;
}
@@ -1,119 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {SidebarFilterTogglePrefService} from './sidebar-filter-toggle-pref.service';
import {MessageService} from 'primeng/api';
import {LocalStorageService} from '../../../../../shared/service/local-storage.service';
import {take} from 'rxjs/operators';
describe('SidebarFilterTogglePrefService', () => {
let messageServiceMock: any;
let localStorageServiceMock: any;
let originalInnerWidth: number;
beforeEach(() => {
messageServiceMock = {add: vi.fn()};
localStorageServiceMock = {
set: vi.fn(),
get: vi.fn()
};
originalInnerWidth = window.innerWidth;
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 1024});
TestBed.configureTestingModule({
providers: [
SidebarFilterTogglePrefService,
{provide: MessageService, useValue: messageServiceMock},
{provide: LocalStorageService, useValue: localStorageServiceMock}
]
});
});
afterEach(() => {
vi.clearAllMocks();
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: originalInnerWidth});
});
function createService(): SidebarFilterTogglePrefService {
const injector = TestBed.inject(EnvironmentInjector);
return runInInjectionContext(injector, () => TestBed.inject(SidebarFilterTogglePrefService));
}
it('should initialize with true if no saved value and not narrow', () => {
localStorageServiceMock.get.mockReturnValueOnce(null);
const service = createService();
expect(service.selectedShowFilter).toBe(true);
});
it('should initialize with saved value if present and not narrow', () => {
localStorageServiceMock.get.mockReturnValueOnce(false);
const service = createService();
expect(service.selectedShowFilter).toBe(false);
});
it('should initialize with false if window is narrow', () => {
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 600});
const service = createService();
expect(service.selectedShowFilter).toBe(false);
});
it('should emit value on showFilter$', async () => {
localStorageServiceMock.get.mockReturnValueOnce(null);
const service = createService();
const val = await service.showFilter$.pipe(take(1)).toPromise();
expect(val).toBe(true);
});
it('should update selectedShowFilter and persist preference', () => {
localStorageServiceMock.get.mockReturnValueOnce(null);
const service = createService();
service.selectedShowFilter = false;
expect(service.selectedShowFilter).toBe(false);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
});
it('should not persist if value is unchanged', () => {
localStorageServiceMock.get.mockReturnValueOnce(true);
const service = createService();
localStorageServiceMock.set.mockClear();
service.selectedShowFilter = true;
expect(localStorageServiceMock.set).not.toHaveBeenCalled();
});
it('should toggle selectedShowFilter', () => {
localStorageServiceMock.get.mockReturnValueOnce(true);
const service = createService();
service.toggle();
expect(service.selectedShowFilter).toBe(false);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', false);
service.toggle();
expect(service.selectedShowFilter).toBe(true);
expect(localStorageServiceMock.set).toHaveBeenCalledWith('showSidebarFilter', true);
});
it('should handle error in savePreference and show error message', () => {
localStorageServiceMock.get.mockReturnValueOnce(null);
localStorageServiceMock.set.mockImplementation(() => {
throw new Error('fail');
});
const service = createService();
service.selectedShowFilter = false;
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
severity: 'error',
summary: 'Save Failed'
}));
});
it('should call loadFromStorage and set correct value for wide screen', () => {
localStorageServiceMock.get.mockReturnValueOnce(true);
const service = createService();
expect(service.selectedShowFilter).toBe(true);
});
it('should call loadFromStorage and set correct value for narrow screen', () => {
Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 500});
const service = createService();
expect(service.selectedShowFilter).toBe(false);
});
});
@@ -1,99 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {BookSorter} from './BookSorter';
import {SortDirection, SortOption} from '../../../model/sort.model';
describe('BookSorter', () => {
let applySortOption: (sort: SortOption) => void;
let sorter: BookSorter;
beforeEach(() => {
applySortOption = vi.fn();
sorter = new BookSorter(applySortOption);
});
it('should initialize with undefined selectedSort', () => {
expect(sorter.selectedSort).toBeUndefined();
});
it('should have all default sort options', () => {
expect(sorter.sortOptions).toBeInstanceOf(Array);
expect(sorter.sortOptions.length).toBeGreaterThan(0);
expect(sorter.sortOptions.some(opt => opt.field === 'title')).toBe(true);
});
it('should set selectedSort and call applySortOption on sortBooks (first time)', () => {
sorter.sortBooks('author');
expect(sorter.selectedSort).toMatchObject({
field: 'author',
direction: SortDirection.ASCENDING
});
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
});
it('should toggle direction when sorting the same field again', () => {
sorter.sortBooks('title');
const firstSort = {...sorter.selectedSort!};
sorter.sortBooks('title');
expect(sorter.selectedSort?.field).toBe('title');
expect(sorter.selectedSort?.direction).not.toBe(firstSort.direction);
expect(applySortOption).toHaveBeenCalledTimes(2);
});
it('should reset direction to ASCENDING when sorting a new field', () => {
sorter.sortBooks('title');
sorter.sortBooks('author');
expect(sorter.selectedSort?.field).toBe('author');
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
});
it('should not change selectedSort or call applySortOption for unknown field', () => {
sorter.sortBooks('notAField');
expect(sorter.selectedSort).toBeUndefined();
expect(applySortOption).not.toHaveBeenCalled();
});
it('should update sortOptions with correct icon for selected field and direction', () => {
sorter.sortBooks('title');
const upIcon = 'pi pi-arrow-up';
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(upIcon);
expect(sorter.sortOptions.filter(opt => opt.field !== 'title').every(opt => !(opt as any).icon)).toBe(true);
sorter.sortBooks('title'); // toggle direction
const downIcon = 'pi pi-arrow-down';
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe(downIcon);
});
it('should only set icon for the selected field', () => {
sorter.sortBooks('author');
sorter.sortBooks('title');
expect((sorter.sortOptions.find(opt => opt.field === 'title') as any)?.icon).toBe('pi pi-arrow-up');
expect((sorter.sortOptions.find(opt => opt.field === 'author') as any)?.icon).toBe('');
});
it('should preserve label and field when toggling direction', () => {
sorter.sortBooks('fileName');
const {label, field} = sorter.selectedSort!;
sorter.sortBooks('fileName');
expect(sorter.selectedSort?.label).toBe(label);
expect(sorter.selectedSort?.field).toBe(field);
});
it('should not throw if updateSortOptions is called with no selectedSort', () => {
// @ts-ignore
sorter.selectedSort = undefined;
expect(() => sorter.updateSortOptions()).toThrow();
});
it('should not mutate original sortOptions array reference on updateSortOptions', () => {
const original = sorter.sortOptions;
sorter.sortBooks('title');
expect(sorter.sortOptions).not.toBe(original);
});
it('should handle sorting "random" field', () => {
sorter.sortBooks('random');
expect(sorter.selectedSort?.field).toBe('random');
expect(sorter.selectedSort?.direction).toBe(SortDirection.ASCENDING);
expect(applySortOption).toHaveBeenCalledWith(sorter.selectedSort);
});
});
@@ -1,140 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {MessageService} from 'primeng/api';
import {TableColumnPreferenceService} from './table-column-preference.service';
import {TableColumnPreference, UserService} from '../../../settings/user-management/user.service';
describe('TableColumnPreferenceService', () => {
let service: TableColumnPreferenceService;
let userServiceMock: any;
let messageServiceMock: any;
const allColumns = [
{field: 'readStatus', header: 'Read'},
{field: 'title', header: 'Title'},
{field: 'authors', header: 'Authors'},
{field: 'publisher', header: 'Publisher'},
{field: 'seriesName', header: 'Series'},
{field: 'seriesNumber', header: 'Series #'},
{field: 'categories', header: 'Genres'},
{field: 'publishedDate', header: 'Published'},
{field: 'lastReadTime', header: 'Last Read'},
{field: 'addedOn', header: 'Added'},
{field: 'fileSizeKb', header: 'File Size'},
{field: 'language', header: 'Language'},
{field: 'isbn', header: 'ISBN'},
{field: 'pageCount', header: 'Pages'},
{field: 'amazonRating', header: 'Amazon'},
{field: 'amazonReviewCount', header: 'AZ #'},
{field: 'goodreadsRating', header: 'Goodreads'},
{field: 'goodreadsReviewCount', header: 'GR #'},
{field: 'hardcoverRating', header: 'Hardcover'},
{field: 'hardcoverReviewCount', header: 'HC #'},
{field: 'ranobedbRating', header: 'Ranobedb'},
];
const fallbackPreferences: TableColumnPreference[] = allColumns.map((col, index) => ({
field: col.field,
visible: true,
order: index
}));
beforeEach(() => {
userServiceMock = {
getCurrentUser: vi.fn(),
updateUserSetting: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
TableColumnPreferenceService,
{provide: UserService, useValue: userServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(TableColumnPreferenceService));
});
it('should initialize with fallback preferences if none provided', () => {
service.initPreferences(undefined);
expect(service.preferences).toEqual(fallbackPreferences);
});
it('should initialize with provided preferences', () => {
const savedPrefs: TableColumnPreference[] = [
{field: 'title', visible: true, order: 0},
{field: 'authors', visible: false, order: 1}
];
service.initPreferences(savedPrefs);
expect(service.preferences.find(p => p.field === 'title')?.visible).toBe(true);
expect(service.preferences.find(p => p.field === 'authors')?.visible).toBe(false);
expect(service.preferences.length).toBe(allColumns.length);
});
it('should return all columns', () => {
expect(service.allColumns).toEqual(allColumns);
});
it('should return visible columns sorted by order', () => {
const prefs: TableColumnPreference[] = [
{field: 'title', visible: true, order: 1},
{field: 'authors', visible: true, order: 0},
{field: 'publisher', visible: false, order: 2}
];
service['preferencesSubject'].next([
...prefs,
...fallbackPreferences.filter(p => !prefs.some(fp => fp.field === p.field))
]);
const visible = service.visibleColumns;
const fields = visible.map(col => col.field);
expect(fields.indexOf('authors')).toBeLessThan(fields.indexOf('title'));
expect(fields).not.toContain('publisher');
});
it('should save visible columns and update preferences', () => {
const selectedColumns = [
{field: 'title'},
{field: 'authors'}
];
userServiceMock.getCurrentUser.mockReturnValue({id: 42});
service.saveVisibleColumns(selectedColumns);
const prefs = service.preferences;
expect(prefs.find(p => p.field === 'title')?.visible).toBe(true);
expect(prefs.find(p => p.field === 'authors')?.visible).toBe(true);
expect(prefs.find(p => p.field === 'publisher')?.visible).toBe(false);
expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith(42, 'tableColumnPreference', prefs);
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({
severity: 'success',
summary: 'Preferences Saved'
}));
});
it('should not call updateUserSetting if no current user', () => {
userServiceMock.getCurrentUser.mockReturnValue(undefined);
service.saveVisibleColumns([{field: 'title'}]);
expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled();
expect(messageServiceMock.add).not.toHaveBeenCalled();
});
it('should get column header for known and unknown fields', () => {
expect(service['getColumnHeader']('title')).toBe('Title');
expect(service['getColumnHeader']('unknown')).toBe('unknown');
});
it('should merge saved preferences with all columns', () => {
const savedPrefs: TableColumnPreference[] = [
{field: 'title', visible: false, order: 5}
];
const merged = service['mergeWithAllColumns'](savedPrefs);
expect(merged.find(p => p.field === 'title')?.visible).toBe(false);
expect(merged.length).toBe(allColumns.length);
expect(merged.find(p => p.field === 'authors')?.visible).toBe(true);
});
});
@@ -0,0 +1,116 @@
<div class="book-file-attacher-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-link header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Attach {{ isBulkMode ? 'Files' : 'File' }} to Another Book</h2>
<p class="panel-description">Move {{ isBulkMode ? 'these books\' files' : 'this book\'s file' }} to another book as alternative format{{ isBulkMode ? 's' : '' }}</p>
</div>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(click)="closeDialog()"
styleClass="close-button">
</p-button>
</div>
<div class="dialog-content">
<!-- Source Book(s) Info -->
<div class="source-info">
<h3 class="section-title">Source Book{{ isBulkMode ? 's' : '' }} ({{ sourceBooks.length }})</h3>
<div class="source-books-list">
@for (book of sourceBooks; track book.id) {
<div class="book-info-card">
<div class="book-title">{{ book.metadata?.title || 'Unknown Title' }}</div>
@if (book.metadata?.authors?.length) {
<div class="book-authors">{{ book.metadata?.authors?.join(', ') }}</div>
}
<div class="file-info">
<i class="pi pi-file"></i>
<span>{{ getSourceFileInfo(book) }}</span>
</div>
</div>
}
</div>
</div>
<!-- Target Book Selection -->
<div class="target-selection">
<h3 class="section-title">Select Target Book</h3>
<p-autocomplete
[(ngModel)]="targetBook"
[suggestions]="filteredBooks"
(completeMethod)="filterBooks($event)"
(onSelect)="onBookSelect($event)"
(onClear)="onBookClear()"
optionLabel="metadata.title"
[dropdown]="true"
[showClear]="true"
placeholder="Search for a book in the same library..."
styleClass="full-width"
[disabled]="isAttaching">
<ng-template let-book pTemplate="item">
<div class="book-suggestion">
<div class="suggestion-title">{{ book.metadata?.title || 'Unknown Title' }}</div>
@if (book.metadata?.authors?.length) {
<div class="suggestion-authors">{{ book.metadata.authors.join(', ') }}</div>
}
@if (book.primaryFile) {
<div class="suggestion-format">{{ book.primaryFile.extension?.toUpperCase() || book.primaryFile.bookType }}</div>
}
</div>
</ng-template>
<ng-template let-book pTemplate="selectedItem">
<span>{{ getBookDisplayName(book) }}</span>
</ng-template>
</p-autocomplete>
</div>
<!-- Delete Source Book(s) Option -->
<div class="delete-option">
<p-checkbox
[(ngModel)]="deleteSourceBooks"
[binary]="true"
inputId="deleteSourceBooks"
[disabled]="isAttaching">
</p-checkbox>
<label for="deleteSourceBooks" class="delete-label">
Delete source book{{ isBulkMode ? 's' : '' }} after attachment
</label>
</div>
<!-- Warning Message -->
<div class="warning-message">
<i class="pi pi-info-circle"></i>
<div class="warning-text">
<p>This will move {{ isBulkMode ? 'the files from the selected books' : 'the file from the source book' }} to the target book as alternative format{{ isBulkMode ? 's' : '' }}.</p>
@if (deleteSourceBooks) {
<p>The source book{{ isBulkMode ? ' records' : ' record' }} will be deleted (file{{ isBulkMode ? 's' : '' }} will be preserved in target book).</p>
} @else {
<p>The source book{{ isBulkMode ? ' records' : ' record' }} will remain but will have no readable files.</p>
}
</div>
</div>
<!-- Action Buttons -->
<div class="action-buttons">
<p-button
label="Cancel"
[outlined]="true"
severity="secondary"
(click)="closeDialog()"
[disabled]="isAttaching">
</p-button>
<p-button
label="Attach {{ isBulkMode ? 'Files' : 'File' }}"
icon="pi pi-link"
(click)="attach()"
[disabled]="!canAttach()"
[loading]="isAttaching">
</p-button>
</div>
</div>
</div>
@@ -0,0 +1,180 @@
@use '../../../../shared/styles/panel-shared' as panel;
.book-file-attacher-container {
display: flex;
flex-direction: column;
height: 100%;
}
.panel-header {
@include panel.panel-header;
flex-shrink: 0;
}
.dialog-content {
flex: 1;
overflow-y: auto;
min-height: 0;
padding: 1.5rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-top: none;
border-radius: 0 0 10px 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.section-title {
font-size: 0.875rem;
font-weight: 600;
color: var(--p-text-muted-color);
margin-bottom: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.source-info {
.source-books-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
max-height: 200px;
overflow-y: auto;
}
.book-info-card {
background: var(--p-surface-100);
border-radius: 8px;
padding: 0.75rem 1rem;
border: 1px solid var(--border-color);
}
.book-title {
font-weight: 600;
font-size: 0.9375rem;
margin-bottom: 0.125rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.book-authors {
color: var(--p-text-muted-color);
font-size: 0.8125rem;
margin-bottom: 0.375rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.file-info {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--p-primary-color);
font-size: 0.8125rem;
font-weight: 500;
i {
font-size: 0.8125rem;
}
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.target-selection {
:host ::ng-deep {
.full-width {
width: 100%;
}
}
}
.book-suggestion {
padding: 0.25rem 0;
.suggestion-title {
font-weight: 500;
margin-bottom: 0.125rem;
}
.suggestion-authors {
font-size: 0.8125rem;
color: var(--p-text-muted-color);
}
.suggestion-format {
font-size: 0.75rem;
color: var(--p-primary-color);
font-weight: 600;
margin-top: 0.25rem;
}
}
.delete-option {
display: flex;
align-items: center;
gap: 0.75rem;
.delete-label {
font-size: 0.9375rem;
cursor: pointer;
user-select: none;
}
}
.warning-message {
display: flex;
gap: 0.75rem;
padding: 1rem;
background: var(--p-yellow-50);
border: 1px solid var(--p-yellow-200);
border-radius: 8px;
color: var(--p-yellow-800);
i {
flex-shrink: 0;
font-size: 1.25rem;
margin-top: 0.125rem;
}
.warning-text {
font-size: 0.875rem;
line-height: 1.5;
p {
margin: 0;
&:not(:last-child) {
margin-bottom: 0.5rem;
}
}
}
}
:host-context(.p-dark) {
.warning-message {
background: rgba(234, 179, 8, 0.1);
border-color: rgba(234, 179, 8, 0.3);
color: var(--p-yellow-400);
}
.source-info .book-info-card {
background: var(--p-surface-800);
}
}
.action-buttons {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
margin-top: auto;
padding-top: 0.5rem;
}
@@ -0,0 +1,148 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { DynamicDialogRef, DynamicDialogConfig } from 'primeng/dynamicdialog';
import { AutoComplete, AutoCompleteSelectEvent } from 'primeng/autocomplete';
import { Button } from 'primeng/button';
import { Checkbox } from 'primeng/checkbox';
import { Subject, takeUntil } from 'rxjs';
import { filter, take } from 'rxjs/operators';
import { BookService } from '../../service/book.service';
import { Book } from '../../model/book.model';
import { MessageService } from 'primeng/api';
@Component({
selector: 'app-book-file-attacher',
standalone: true,
imports: [
FormsModule,
AutoComplete,
Button,
Checkbox
],
templateUrl: './book-file-attacher.component.html',
styleUrls: ['./book-file-attacher.component.scss']
})
export class BookFileAttacherComponent implements OnInit, OnDestroy {
sourceBooks: Book[] = [];
targetBook: Book | null = null;
deleteSourceBooks = true;
isAttaching = false;
searchQuery = '';
filteredBooks: Book[] = [];
private destroy$ = new Subject<void>();
private allBooks: Book[] = [];
constructor(
private dialogRef: DynamicDialogRef,
private config: DynamicDialogConfig,
private bookService: BookService,
private messageService: MessageService
) {}
ngOnInit(): void {
// Support both single book and multiple books
if (this.config.data.sourceBook) {
this.sourceBooks = [this.config.data.sourceBook];
} else if (this.config.data.sourceBooks) {
this.sourceBooks = this.config.data.sourceBooks;
}
if (this.sourceBooks.length === 0) {
this.closeDialog();
return;
}
// Get the library ID from first source book (all should be same library)
const libraryId = this.sourceBooks[0].libraryId;
const sourceBookIds = new Set(this.sourceBooks.map(b => b.id));
// Load all books from state and filter for same library, excluding source books
this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
take(1),
takeUntil(this.destroy$)
).subscribe(state => {
this.allBooks = (state.books || []).filter(book =>
book.libraryId === libraryId && !sourceBookIds.has(book.id)
);
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
get isBulkMode(): boolean {
return this.sourceBooks.length > 1;
}
filterBooks(event: { query: string }): void {
const query = event.query.toLowerCase().trim();
if (!query) {
this.filteredBooks = this.allBooks.slice(0, 20);
return;
}
this.filteredBooks = this.allBooks
.filter(book => {
const title = book.metadata?.title?.toLowerCase() || '';
const authors = book.metadata?.authors?.join(' ').toLowerCase() || '';
return title.includes(query) || authors.includes(query);
})
.slice(0, 20);
}
onBookSelect(event: AutoCompleteSelectEvent): void {
this.targetBook = event.value as Book;
}
onBookClear(): void {
this.targetBook = null;
}
getBookDisplayName(book: Book): string {
const title = book.metadata?.title || `Book #${book.id}`;
const authors = book.metadata?.authors?.join(', ');
return authors ? `${title} - ${authors}` : title;
}
getSourceFileInfo(book: Book): string {
const file = book.primaryFile;
if (!file) return 'Unknown file';
const format = file.extension?.toUpperCase() || file.bookType || 'Unknown';
return `${format} - ${file.fileName || 'Unknown filename'}`;
}
canAttach(): boolean {
return !!this.targetBook && !this.isAttaching;
}
attach(): void {
if (!this.targetBook) return;
this.isAttaching = true;
const sourceBookIds = this.sourceBooks.map(b => b.id);
this.bookService.attachBookFiles(
this.targetBook.id,
sourceBookIds,
this.deleteSourceBooks
).pipe(
takeUntil(this.destroy$)
).subscribe({
next: () => {
this.dialogRef.close({ success: true, deletedSourceBooks: this.deleteSourceBooks });
},
error: () => {
this.isAttaching = false;
}
});
}
closeDialog(): void {
this.dialogRef.close();
}
}
@@ -162,7 +162,7 @@
tooltipPosition="top">
</p-button>
}
@if (userState.user!.permissions.canMoveOrganizeFiles) {
@if (userState.user!.permissions.canMoveOrganizeFiles && (appSettingsService.appSettings$ | async)?.diskType === 'LOCAL') {
<p-button
outlined="true"
icon="pi pi-arrows-h"
@@ -21,6 +21,7 @@ import {BookDialogHelperService} from "../book-browser/book-dialog-helper.servic
import {TaskHelperService} from "../../../settings/task-management/task-helper.service";
import {MetadataRefreshType} from "../../../metadata/model/request/metadata-refresh-type.enum";
import {TieredMenu} from "primeng/tieredmenu";
import {AppSettingsService} from "../../../../shared/service/app-settings.service";
import {Tooltip} from "primeng/tooltip";
import {Divider} from "primeng/divider";
import {animate, style, transition, trigger} from "@angular/animations";
@@ -78,6 +79,7 @@ export class SeriesPageComponent implements OnDestroy {
private dialogHelperService = inject(BookDialogHelperService);
protected taskHelperService = inject(TaskHelperService);
private messageService = inject(MessageService);
protected appSettingsService = inject(AppSettingsService);
tab: string = "view";
isExpanded = false;
@@ -3,7 +3,7 @@ import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrol
import {BookReview} from '../components/book-reviews/book-review-service';
import {ZoomType} from 'ngx-extended-pdf-viewer';
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3";
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3" | "AUDIOBOOK";
export enum AdditionalFileType {
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
@@ -17,17 +17,23 @@ export interface FileInfo {
fileSizeKb?: number;
}
export interface AdditionalFile extends FileInfo {
export interface BookFile extends FileInfo {
id: number;
bookId: number;
additionalFileType: AdditionalFileType;
description?: string;
bookType?: BookType;
folderBased?: boolean;
extension?: string;
addedOn?: string;
}
export interface AdditionalFile extends BookFile {
additionalFileType?: AdditionalFileType;
description?: string;
}
export interface Book extends FileInfo {
id: number;
bookType: BookType;
primaryFile?: BookFile;
libraryId: number;
libraryName: string;
metadata?: BookMetadata;
@@ -37,6 +43,7 @@ export interface Book extends FileInfo {
epubProgress?: EpubProgress;
pdfProgress?: PdfProgress;
cbxProgress?: CbxProgress;
audiobookProgress?: AudiobookProgress;
koreaderProgress?: KoReaderProgress;
koboProgress?: KoboProgress;
seriesCount?: number | null;
@@ -48,6 +55,7 @@ export interface Book extends FileInfo {
libraryPath?: { id: number };
alternativeFormats?: AdditionalFile[];
supplementaryFiles?: AdditionalFile[];
isPhysical?: boolean;
[key: string]: unknown;
}
@@ -75,6 +83,20 @@ export interface KoboProgress {
percentage: number;
}
export interface AudiobookProgress {
positionMs: number;
trackIndex?: number;
trackPositionMs?: number;
percentage: number;
}
export interface BookFileProgress {
bookFileId: number;
positionData?: string;
positionHref?: string;
progressPercent: number;
}
export interface BookMetadata {
bookId: number;
title?: string;
@@ -291,3 +313,16 @@ export enum ReadStatus {
ABANDONED = 'ABANDONED',
UNSET = 'UNSET'
}
export interface CreatePhysicalBookRequest {
libraryId: number;
isbn?: string;
title?: string;
authors?: string[];
description?: string;
publisher?: string;
publishedDate?: string;
language?: string;
pageCount?: number;
categories?: string[];
}
@@ -1,7 +1,5 @@
import {SortOption} from './sort.model';
export type LibraryScanMode = 'FILE_AS_BOOK' | 'FOLDER_AS_BOOK';
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2' | 'MOBI' | 'AZW3';
import {BookType} from './book.model';
export interface Library {
id?: number;
@@ -12,8 +10,7 @@ export interface Library {
fileNamingPattern?: string;
sort?: SortOption;
paths: LibraryPath[];
scanMode?: LibraryScanMode;
defaultBookFormat?: BookFileType;
formatPriority?: BookType[];
}
export interface LibraryPath {
@@ -1,478 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {ConfirmationService, MessageService} from 'primeng/api';
import {BookService} from './book.service';
import {LoadingService} from '../../../core/services/loading.service';
import {User} from '../../settings/user-management/user.service';
import {ReadStatus} from '../model/book.model';
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {of, throwError} from 'rxjs';
import {HttpErrorResponse} from '@angular/common/http';
import {APIException} from '../../../shared/models/api-exception.model';
import {BookMenuService} from './book-menu.service';
describe('BookMenuService', () => {
let service: BookMenuService;
let confirmationService: any;
let messageService: any;
let bookService: any;
let loadingService: any;
const mockUser: User = {
id: 1,
username: 'testuser',
email: 'test@example.com',
permissions: {
canBulkAutoFetchMetadata: true,
canBulkCustomFetchMetadata: true,
canBulkEditMetadata: true,
canBulkRegenerateCover: true,
canBulkResetBookReadStatus: true,
canBulkResetBookloreReadProgress: true,
canBulkResetKoReaderReadProgress: true
}
} as User;
const mockUserNoPermissions: User = {
id: 2,
username: 'limiteduser',
email: 'limited@example.com',
permissions: {
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canBulkResetBookReadStatus: false,
canBulkResetBookloreReadProgress: false,
canBulkResetKoReaderReadProgress: false
}
} as User;
beforeEach(() => {
confirmationService = {
confirm: vi.fn()
};
messageService = {
add: vi.fn()
};
bookService = {
updateBookReadStatus: vi.fn(),
resetProgress: vi.fn()
};
loadingService = {
show: vi.fn().mockReturnValue('loader-id'),
hide: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMenuService,
{provide: ConfirmationService, useValue: confirmationService},
{provide: MessageService, useValue: messageService},
{provide: BookService, useValue: bookService},
{provide: LoadingService, useValue: loadingService}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(BookMenuService)
);
});
describe('getMetadataMenuItems', () => {
it('should return all metadata menu items when user has all permissions', () => {
const autoFetch = vi.fn();
const fetch = vi.fn();
const bulkEdit = vi.fn();
const multiEdit = vi.fn();
const regenerate = vi.fn();
const generateCustomCovers = vi.fn();
const items = service.getMetadataMenuItems(
autoFetch,
fetch,
bulkEdit,
multiEdit,
regenerate,
generateCustomCovers,
mockUser
);
expect(items).toHaveLength(6);
expect(items[0].label).toBe('Auto Fetch Metadata');
expect(items[0].icon).toBe('pi pi-bolt');
expect(items[1].label).toBe('Custom Fetch Metadata');
expect(items[1].icon).toBe('pi pi-sync');
expect(items[2].label).toBe('Bulk Metadata Editor');
expect(items[2].icon).toBe('pi pi-table');
expect(items[3].label).toBe('Multi-Book Metadata Editor');
expect(items[3].icon).toBe('pi pi-clone');
expect(items[4].label).toBe('Regenerate Covers');
expect(items[4].icon).toBe('pi pi-image');
expect(items[5].label).toBe('Generate Custom Covers');
expect(items[5].icon).toBe('pi pi-palette');
});
it('should return empty array when user has no permissions', () => {
const items = service.getMetadataMenuItems(
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
mockUserNoPermissions
);
expect(items).toHaveLength(0);
});
it('should return empty array when user is null', () => {
const items = service.getMetadataMenuItems(
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
null
);
expect(items).toHaveLength(0);
});
it('should call command functions when menu items are clicked', () => {
const autoFetch = vi.fn();
const fetch = vi.fn();
const bulkEdit = vi.fn();
const multiEdit = vi.fn();
const regenerate = vi.fn();
const generateCustomCovers = vi.fn();
const items = service.getMetadataMenuItems(
autoFetch,
fetch,
bulkEdit,
multiEdit,
regenerate,
generateCustomCovers,
mockUser
);
items[0].command!({} as any);
expect(autoFetch).toHaveBeenCalledOnce();
items[1].command!({} as any);
expect(fetch).toHaveBeenCalledOnce();
items[2].command!({} as any);
expect(bulkEdit).toHaveBeenCalledOnce();
items[3].command!({} as any);
expect(multiEdit).toHaveBeenCalledOnce();
items[4].command!({} as any);
expect(regenerate).toHaveBeenCalledOnce();
items[5].command!({} as any);
expect(generateCustomCovers).toHaveBeenCalledOnce();
});
it('should return only items for granted permissions', () => {
const partialUser: User = {
...mockUser,
permissions: {
...mockUser.permissions,
canBulkAutoFetchMetadata: true,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: true,
canBulkRegenerateCover: false
}
} as User;
const items = service.getMetadataMenuItems(
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
vi.fn(),
partialUser
);
expect(items).toHaveLength(3);
expect(items[0].label).toBe('Auto Fetch Metadata');
expect(items[1].label).toBe('Bulk Metadata Editor');
expect(items[2].label).toBe('Multi-Book Metadata Editor');
});
});
describe('getBulkReadActionsMenu', () => {
it('should return all read action items when user has all permissions', () => {
const selectedBooks = new Set([1, 2, 3]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
expect(items).toHaveLength(3);
expect(items[0].label).toBe('Update Read Status');
expect(items[0].icon).toBe('pi pi-book');
expect(items[0].items).toBeDefined();
expect(items[0].items!.length).toBeGreaterThan(0);
expect(items[1].label).toBe('Reset Booklore Progress');
expect(items[1].icon).toBe('pi pi-undo');
expect(items[2].label).toBe('Reset KOReader Progress');
expect(items[2].icon).toBe('pi pi-undo');
});
it('should return empty array when user has no permissions', () => {
const selectedBooks = new Set([1, 2, 3]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUserNoPermissions);
expect(items).toHaveLength(0);
});
it('should return empty array when user is null', () => {
const selectedBooks = new Set([1, 2, 3]);
const items = service.getBulkReadActionsMenu(selectedBooks, null);
expect(items).toHaveLength(0);
});
it('should show confirmation dialog when updating read status', () => {
const selectedBooks = new Set([1, 2, 3]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
const readStatusItems = items[0].items!;
readStatusItems[0].command!({} as any);
expect(confirmationService.confirm).toHaveBeenCalledOnce();
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
expect(confirmCall.message).toContain('3 book(s)');
expect(confirmCall.header).toBe('Confirm Read Status Update');
});
it('should update read status on confirmation accept', () => {
const selectedBooks = new Set([1, 2, 3]);
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(of([]));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
const readStatusItems = items[0].items!;
const readItem = readStatusItems.find(item => item.label === 'Read');
expect(readItem).toBeDefined();
readItem!.command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(loadingService.show).toHaveBeenCalledWith('Updating read status for 3 book(s)...');
expect(bookService.updateBookReadStatus).toHaveBeenCalledWith([1, 2, 3], ReadStatus.READ);
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
expect(messageService.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Read Status Updated',
detail: 'Marked as "Read"',
life: 2000
});
});
it('should show error message when read status update fails', () => {
const selectedBooks = new Set([1, 2]);
const errorResponse = new HttpErrorResponse({
error: {message: 'Update failed'} as APIException,
status: 500
});
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
const readStatusItems = items[0].items!;
readStatusItems[0].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Update Failed',
detail: 'Update failed',
life: 3000
});
});
it('should show confirmation dialog when resetting Booklore progress', () => {
const selectedBooks = new Set([1, 2, 3]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[1].command!({} as any);
expect(confirmationService.confirm).toHaveBeenCalledOnce();
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
expect(confirmCall.message).toContain('3 book(s)');
expect(confirmCall.header).toBe('Confirm Reset');
});
it('should reset Booklore progress on confirmation accept', () => {
const selectedBooks = new Set([5, 6]);
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[1].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(loadingService.show).toHaveBeenCalledWith('Resetting Booklore progress for 2 book(s)...');
expect(bookService.resetProgress).toHaveBeenCalledWith([5, 6], ResetProgressTypes.BOOKLORE);
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
expect(messageService.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Progress Reset',
detail: 'Booklore reading progress has been reset.',
life: 1500
});
});
it('should show error message when Booklore progress reset fails', () => {
const selectedBooks = new Set([1]);
const errorResponse = new HttpErrorResponse({
error: {message: 'Reset failed'} as APIException,
status: 500
});
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[1].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'Reset failed',
life: 3000
});
});
it('should show confirmation dialog when resetting KOReader progress', () => {
const selectedBooks = new Set([7, 8]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[2].command!({} as any);
expect(confirmationService.confirm).toHaveBeenCalledOnce();
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
expect(confirmCall.message).toContain('2 book(s)');
expect(confirmCall.message).toContain('KOReader');
expect(confirmCall.header).toBe('Confirm Reset');
});
it('should reset KOReader progress on confirmation accept', () => {
const selectedBooks = new Set([9]);
vi.mocked(bookService.resetProgress).mockReturnValue(of([]));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[2].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(loadingService.show).toHaveBeenCalledWith('Resetting KOReader progress for 1 book(s)...');
expect(bookService.resetProgress).toHaveBeenCalledWith([9], ResetProgressTypes.KOREADER);
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
expect(messageService.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Progress Reset',
detail: 'KOReader reading progress has been reset.',
life: 1500
});
});
it('should show error message when KOReader progress reset fails', () => {
const selectedBooks = new Set([10]);
const errorResponse = new HttpErrorResponse({
error: {message: 'KOReader reset failed'} as APIException,
status: 500
});
vi.mocked(bookService.resetProgress).mockReturnValue(throwError(() => errorResponse));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[2].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'KOReader reset failed',
life: 3000
});
});
it('should handle API error without message gracefully', () => {
const selectedBooks = new Set([1]);
const errorResponse = new HttpErrorResponse({
error: {} as APIException,
status: 500
});
vi.mocked(bookService.updateBookReadStatus).mockReturnValue(throwError(() => errorResponse));
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
const readStatusItems = items[0].items!;
readStatusItems[0].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.accept!();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update read status.',
life: 3000
});
});
it('should return only items for granted read permissions', () => {
const partialUser: User = {
...mockUser,
permissions: {
...mockUser.permissions,
canBulkResetBookReadStatus: true,
canBulkResetBookloreReadProgress: false,
canBulkResetKoReaderReadProgress: true
}
} as User;
const selectedBooks = new Set([1, 2]);
const items = service.getBulkReadActionsMenu(selectedBooks, partialUser);
expect(items).toHaveLength(2);
expect(items[0].label).toBe('Update Read Status');
expect(items[1].label).toBe('Reset KOReader Progress');
});
it('should not call bookService when confirmation is rejected', () => {
const selectedBooks = new Set([1, 2]);
const items = service.getBulkReadActionsMenu(selectedBooks, mockUser);
items[1].command!({} as any);
const confirmCall = vi.mocked(confirmationService.confirm).mock.calls[0][0];
confirmCall.reject?.();
expect(bookService.resetProgress).not.toHaveBeenCalled();
expect(loadingService.show).not.toHaveBeenCalled();
});
});
});
@@ -1,106 +0,0 @@
import {beforeEach, describe, expect, it} from 'vitest';
import {firstValueFrom} from 'rxjs';
import {BookNavigationService} from './book-navigation.service';
describe('BookNavigationService', () => {
let service: BookNavigationService;
const bookIds = [10, 20, 30, 40];
beforeEach(() => {
service = new BookNavigationService();
});
it('should set and get available book ids', () => {
service.setAvailableBookIds(bookIds);
expect(service.getAvailableBookIds()).toEqual(bookIds);
});
it('should set navigation context and emit state', async () => {
service.setNavigationContext(bookIds, 30);
const state = await firstValueFrom(service.getNavigationState());
expect(state).not.toBeNull();
expect(state!.bookIds).toEqual(bookIds);
expect(state!.currentIndex).toBe(2);
});
it('should emit null if currentBookId not in bookIds', async () => {
service.setNavigationContext(bookIds, 99);
const state = await firstValueFrom(service.getNavigationState());
expect(state).toBeNull();
});
it('should determine canNavigatePrevious correctly', () => {
service.setNavigationContext(bookIds, 10);
expect(service.canNavigatePrevious()).toBe(false);
service.setNavigationContext(bookIds, 30);
expect(service.canNavigatePrevious()).toBe(true);
});
it('should determine canNavigateNext correctly', () => {
service.setNavigationContext(bookIds, 40);
expect(service.canNavigateNext()).toBe(false);
service.setNavigationContext(bookIds, 20);
expect(service.canNavigateNext()).toBe(true);
});
it('should get previous book id', () => {
service.setNavigationContext(bookIds, 30);
expect(service.getPreviousBookId()).toBe(20);
service.setNavigationContext(bookIds, 10);
expect(service.getPreviousBookId()).toBeNull();
});
it('should get next book id', () => {
service.setNavigationContext(bookIds, 20);
expect(service.getNextBookId()).toBe(30);
service.setNavigationContext(bookIds, 40);
expect(service.getNextBookId()).toBeNull();
});
it('should update current book and emit new index', async () => {
service.setNavigationContext(bookIds, 10);
service.updateCurrentBook(30);
const state = await firstValueFrom(service.getNavigationState());
expect(state!.currentIndex).toBe(2);
expect(state!.bookIds[state!.currentIndex]).toBe(30);
});
it('should not update current book if id not in list', async () => {
service.setNavigationContext(bookIds, 10);
service.updateCurrentBook(99);
const state = await firstValueFrom(service.getNavigationState());
expect(state!.currentIndex).toBe(0);
expect(state!.bookIds[state!.currentIndex]).toBe(10);
});
it('should return current position', () => {
service.setNavigationContext(bookIds, 30);
expect(service.getCurrentPosition()).toEqual({current: 3, total: 4});
});
it('should return null for current position if no state', () => {
expect(service.getCurrentPosition()).toBeNull();
});
it('should handle navigation methods gracefully if state is null', () => {
expect(service.canNavigatePrevious()).toBe(false);
expect(service.canNavigateNext()).toBe(false);
expect(service.getPreviousBookId()).toBeNull();
expect(service.getNextBookId()).toBeNull();
service.updateCurrentBook(10);
expect(service.getCurrentPosition()).toBeNull();
});
});
@@ -1,171 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {BookPatchService} from './book-patch.service';
import {BookStateService} from './book-state.service';
import {Book, ReadStatus} from '../model/book.model';
describe('BookPatchService', () => {
let service: BookPatchService;
let httpMock: any;
let bookStateServiceMock: any;
const mockBooks: Book[] = [
{id: 1, bookType: 'PDF', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
{id: 2, bookType: 'EPUB', libraryId: 1, libraryName: 'Lib', dateFinished: undefined} as Book,
];
beforeEach(() => {
httpMock = {
post: vi.fn(),
put: vi.fn(),
};
bookStateServiceMock = {
getCurrentBookState: vi.fn(),
updateBookState: vi.fn(),
};
TestBed.configureTestingModule({
providers: [
BookPatchService,
{provide: HttpClient, useValue: httpMock},
{provide: BookStateService, useValue: bookStateServiceMock},
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(BookPatchService)
);
});
it('should update book shelves and update state', () => {
const updatedBooks = [{...mockBooks[0], id: 1, libraryName: 'Updated'}];
httpMock.post.mockReturnValue(of(updatedBooks));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])).subscribe(result => {
expect(result).toEqual(updatedBooks);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
books: expect.arrayContaining([expect.objectContaining({id: 1, libraryName: 'Updated'})])
}));
});
});
it('should save PDF progress', () => {
httpMock.post.mockReturnValue(of(void 0));
service.savePdfProgress(1, 10, 0.5).subscribe(result => {
expect(result).toBeUndefined();
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
bookId: 1,
pdfProgress: {page: 10, percentage: 0.5}
});
});
});
it('should save EPUB progress', () => {
httpMock.post.mockReturnValue(of(void 0));
service.saveEpubProgress(2, 'cfi123', 'href123', 0.8);
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
bookId: 2,
epubProgress: {cfi: 'cfi123', href: 'href123', percentage: 0.8}
});
});
it('should save CBX progress', () => {
httpMock.post.mockReturnValue(of(void 0));
service.saveCbxProgress(3, 5, 0.2).subscribe(result => {
expect(result).toBeUndefined();
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
bookId: 3,
cbxProgress: {page: 5, percentage: 0.2}
});
});
});
it('should update date finished and update state', () => {
httpMock.post.mockReturnValue(of(void 0));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.updateDateFinished(1, '2023-01-01').subscribe(() => {
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
books: expect.arrayContaining([expect.objectContaining({id: 1, dateFinished: '2023-01-01'})])
}));
});
});
it('should reset progress and update state', () => {
const responses = [{bookId: 1, readStatus: ReadStatus.UNREAD, readStatusModifiedTime: 'now', dateFinished: undefined}];
httpMock.post.mockReturnValue(of(responses));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.resetProgress([1], 'BOOKLORE').subscribe(result => {
expect(result).toEqual(responses);
expect(httpMock.post).toHaveBeenCalledWith(
expect.stringContaining('/reset-progress'),
[1],
{params: expect.any(HttpParams)}
);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
it('should update book read status and update state', () => {
const responses = [{bookId: 2, readStatus: ReadStatus.READING, readStatusModifiedTime: 'now', dateFinished: '2023-01-01'}];
httpMock.post.mockReturnValue(of(responses));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.updateBookReadStatus([2], ReadStatus.READING).subscribe(result => {
expect(result).toEqual(responses);
expect(httpMock.post).toHaveBeenCalledWith(
expect.stringContaining('/status'),
{bookIds: [2], status: ReadStatus.READING}
);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
it('should reset personal rating and update state', () => {
const responses = [{bookId: 1, personalRating: null}];
httpMock.post.mockReturnValue(of(responses));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.resetPersonalRating([1]).subscribe(result => {
expect(result).toEqual(responses);
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/reset-personal-rating'), [1]);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
it('should update personal rating and update state', () => {
const responses = [{bookId: 2, personalRating: 5}];
httpMock.put.mockReturnValue(of(responses));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.updatePersonalRating([2], 5).subscribe(result => {
expect(result).toEqual(responses);
expect(httpMock.put).toHaveBeenCalledWith(expect.stringContaining('/personal-rating'), {ids: [2], rating: 5});
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
it('should update last read time in state', () => {
const now = new Date().toISOString();
vi.useFakeTimers().setSystemTime(new Date(now));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [...mockBooks]});
service.updateLastReadTime(1);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith(expect.objectContaining({
books: expect.arrayContaining([expect.objectContaining({id: 1, lastReadTime: now})])
}));
vi.useRealTimers();
});
it('should handle errors from http.post gracefully', () => {
httpMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.savePdfProgress(1, 1, 1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
import {Book, ReadStatus} from '../model/book.model';
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
import {BookStateService} from './book-state.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
@@ -17,17 +17,18 @@ export class BookPatchService {
private http = inject(HttpClient);
private bookStateService = inject(BookStateService);
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number }>();
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>();
private epubProgress$ = this.epubProgressSubject.pipe(
distinctUntilChanged((prev, curr) =>
prev.bookId === curr.bookId &&
prev.cfi === curr.cfi &&
prev.href === curr.href &&
prev.percentage === curr.percentage
prev.percentage === curr.percentage &&
prev.bookFileId === curr.bookFileId
),
exhaustMap(payload => {
const body = {
const body: any = {
bookId: payload.bookId,
epubProgress: {
cfi: payload.cfi,
@@ -35,6 +36,15 @@ export class BookPatchService {
percentage: payload.percentage
}
};
// Add file-level progress if bookFileId is provided
if (payload.bookFileId) {
body.fileProgress = {
bookFileId: payload.bookFileId,
positionData: payload.cfi,
positionHref: payload.href,
progressPercent: payload.percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}),
share()
@@ -65,29 +75,57 @@ export class BookPatchService {
);
}
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
positionData: String(page),
progressPercent: percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): void {
this.epubProgressSubject.next({bookId, cfi, href, percentage});
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void {
this.epubProgressSubject.next({bookId, cfi, href, percentage, bookFileId});
}
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
cbxProgress: {
page: page,
percentage: percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
positionData: String(page),
progressPercent: percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}
/**
* Save file-level progress directly using the new API.
* This is the preferred method for per-file progress tracking.
*/
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
const body = {
bookId: bookId,
fileProgress: fileProgress
};
return this.http.post<void>(`${this.url}/progress`, body);
}
@@ -1,511 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {firstValueFrom, of, throwError} from 'rxjs';
import {BookService} from './book.service';
import {BookStateService} from './book-state.service';
import {BookSocketService} from './book-socket.service';
import {BookPatchService} from './book-patch.service';
import {MessageService} from 'primeng/api';
import {AuthService} from '../../../shared/service/auth.service';
import {FileDownloadService} from '../../../shared/service/file-download.service';
import {Router} from '@angular/router';
import {AdditionalFileType, Book, BookMetadata, ReadStatus} from '../model/book.model';
describe('BookService', () => {
let service: BookService;
let httpMock: any;
let messageServiceMock: any;
let authServiceMock: any;
let fileDownloadServiceMock: any;
let routerMock: any;
let bookStateServiceMock: any;
let bookSocketServiceMock: any;
let bookPatchServiceMock: any;
beforeEach(() => {
httpMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
messageServiceMock = {add: vi.fn()};
authServiceMock = {token$: of('token')};
fileDownloadServiceMock = {downloadFile: vi.fn()};
routerMock = {navigate: vi.fn()};
bookStateServiceMock = {
bookState$: of({books: [{id: 1, bookType: 'PDF', shelves: [], metadata: {seriesName: 'S'}}], loaded: true, error: null}),
getCurrentBookState: vi.fn(),
updateBookState: vi.fn(),
resetBookState: vi.fn()
};
bookSocketServiceMock = {
handleNewlyCreatedBook: vi.fn(),
handleRemovedBookIds: vi.fn(),
handleBookUpdate: vi.fn(),
handleMultipleBookUpdates: vi.fn(),
handleBookMetadataUpdate: vi.fn(),
handleMultipleBookCoverPatches: vi.fn()
};
bookPatchServiceMock = {
updateBookShelves: vi.fn(),
updateLastReadTime: vi.fn(),
savePdfProgress: vi.fn(),
saveEpubProgress: vi.fn(),
saveCbxProgress: vi.fn(),
updateDateFinished: vi.fn(),
resetProgress: vi.fn(),
updateBookReadStatus: vi.fn(),
resetPersonalRating: vi.fn(),
updatePersonalRating: vi.fn()
};
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [
{id: 1, bookType: 'PDF', shelves: [{id: 10}], metadata: {seriesName: 'S'}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file.pdf'},
{id: 2, bookType: 'EPUB', shelves: [], metadata: {}, alternativeFormats: [], supplementaryFiles: [], fileName: 'file2.epub'}
],
loaded: true,
error: null
});
TestBed.configureTestingModule({
providers: [
BookService,
{provide: HttpClient, useValue: httpMock},
{provide: MessageService, useValue: messageServiceMock},
{provide: AuthService, useValue: authServiceMock},
{provide: FileDownloadService, useValue: fileDownloadServiceMock},
{provide: Router, useValue: routerMock},
{provide: BookStateService, useValue: bookStateServiceMock},
{provide: BookSocketService, useValue: bookSocketServiceMock},
{provide: BookPatchService, useValue: bookPatchServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(BookService));
});
describe('State Management', () => {
it('should get current book state', () => {
expect(service.getCurrentBookState()).toEqual(bookStateServiceMock.getCurrentBookState());
});
it('should fetch books and update state', async () => {
const books = [{id: 1}];
httpMock.get.mockReturnValue(of(books));
await firstValueFrom(service['fetchBooks']());
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
books,
loaded: true,
error: null
});
});
it('should handle fetchBooks error', async () => {
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: false, error: null});
await expect(firstValueFrom(service['fetchBooks']())).rejects.toBeTruthy();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
books: [],
loaded: true,
error: 'fail'
});
});
it('should refreshBooks and update state', () => {
httpMock.get.mockReturnValue(of([{id: 1}]));
service.refreshBooks();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
books: [{id: 1}],
loaded: true,
error: null
});
});
it('should handle refreshBooks error', () => {
httpMock.get.mockReturnValue(throwError(() => ({message: 'fail'})));
service.refreshBooks();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
books: null,
loaded: true,
error: 'fail'
});
});
it('should remove books by library id', () => {
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, libraryId: 2}, {id: 2, libraryId: 3}],
loaded: true,
error: null
});
service.removeBooksByLibraryId(2);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalledWith({
books: [{id: 2, libraryId: 3}],
loaded: true,
error: null
});
});
it('should remove books from shelf', () => {
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, shelves: [{id: 10}, {id: 20}]}, {id: 2, shelves: [{id: 20}]}],
loaded: true,
error: null
});
service.removeBooksFromShelf(20);
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
describe('Book Retrieval', () => {
it('should get book by id from state', () => {
expect(service.getBookByIdFromState(1)).toEqual(expect.objectContaining({id: 1}));
expect(service.getBookByIdFromState(999)).toBeUndefined();
});
it('should get books by ids from state', () => {
expect(service.getBooksByIdsFromState([1, 2])).toHaveLength(2);
expect(service.getBooksByIdsFromState([])).toEqual([]);
});
it('should get book by id from API', async () => {
httpMock.get.mockReturnValue(of({id: 1}));
const result = await firstValueFrom(service.getBookByIdFromAPI(1, true));
expect(result).toEqual({id: 1});
});
it('should get books in series', async () => {
const result = await firstValueFrom(service.getBooksInSeries(1));
expect(result).toEqual([expect.objectContaining({id: 1})]);
});
it('should get book recommendations', async () => {
httpMock.get.mockReturnValue(of([{id: 1}]));
const result = await firstValueFrom(service.getBookRecommendations(1));
expect(result).toEqual([{id: 1}]);
});
});
describe('Book Operations', () => {
it('should delete books and update state', async () => {
httpMock.delete.mockReturnValue(of({failedFileDeletions: []}));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1}, {id: 2}],
loaded: true,
error: null
});
await firstValueFrom(service.deleteBooks(new Set([1])));
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should show warning if some files could not be deleted', async () => {
httpMock.delete.mockReturnValue(of({failedFileDeletions: ['file.pdf']}));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, fileName: 'file.pdf'}],
loaded: true,
error: null
});
await firstValueFrom(service.deleteBooks(new Set([1])));
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'warn'}));
});
it('should handle deleteBooks error', async () => {
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
await expect(firstValueFrom(service.deleteBooks(new Set([1])))).rejects.toBeTruthy();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
});
it('should update book shelves', async () => {
bookPatchServiceMock.updateBookShelves.mockReturnValue(of([{id: 1}]));
const result = await firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])));
expect(result).toEqual([{id: 1}]);
});
it('should handle updateBookShelves error', async () => {
bookPatchServiceMock.updateBookShelves.mockReturnValue(throwError(() => ({message: 'fail'})));
await expect(firstValueFrom(service.updateBookShelves(new Set([1]), new Set([2]), new Set([3])))).rejects.toBeTruthy();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
});
describe('Reading & Viewer Settings', () => {
it('should navigate to correct reader and update last read time', () => {
service.readBook(1);
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1'], undefined);
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
});
it('should not navigate if book not found', () => {
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null});
service.readBook(999);
expect(routerMock.navigate).not.toHaveBeenCalled();
});
it('should get book setting', async () => {
httpMock.get.mockReturnValue(of({fontSize: 12}));
const result = await firstValueFrom(service.getBookSetting(1));
expect(result).toEqual({fontSize: 12});
});
it('should update viewer setting', async () => {
httpMock.put.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.updateViewerSetting({fontSize: 12}, 1));
expect(result).toBeUndefined();
});
});
describe('File Operations', () => {
it('should get file content', async () => {
httpMock.get.mockReturnValue(of(new Blob(['abc'])));
const result = await firstValueFrom(service.getFileContent(1));
expect(result).toBeInstanceOf(Blob);
});
it('should download file', () => {
const book = {id: 1, fileName: 'file.pdf'};
service.downloadFile(book as Book);
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
});
it('should delete additional file and update state', async () => {
httpMock.delete.mockReturnValue(of(void 0));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, alternativeFormats: [{id: 2}], supplementaryFiles: [{id: 3}]}],
loaded: true,
error: null
});
await firstValueFrom(service.deleteAdditionalFile(1, 2));
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should handle deleteAdditionalFile error', async () => {
httpMock.delete.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
await expect(firstValueFrom(service.deleteAdditionalFile(1, 2))).rejects.toBeTruthy();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
});
it('should upload additional file and update state', async () => {
httpMock.post.mockReturnValue(of({id: 2}));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, alternativeFormats: [], supplementaryFiles: []}],
loaded: true,
error: null
});
const file = new File(['abc'], 'file.txt');
await firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT));
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should handle uploadAdditionalFile error', async () => {
httpMock.post.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
const file = new File(['abc'], 'file.txt');
await expect(firstValueFrom(service.uploadAdditionalFile(1, file, AdditionalFileType.ALTERNATIVE_FORMAT))).rejects.toBeTruthy();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
});
it('should download additional file', () => {
const book = {id: 1, alternativeFormats: [{id: 2, fileName: 'f.txt'}]};
service.downloadAdditionalFile(book as Book, 2);
expect(fileDownloadServiceMock.downloadFile).toHaveBeenCalled();
});
});
describe('Progress & Status Tracking', () => {
it('should update last read time', () => {
service.updateLastReadTime(1);
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
});
it('should save pdf progress', async () => {
bookPatchServiceMock.savePdfProgress.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.savePdfProgress(1, 2, 0.5));
expect(result).toBeUndefined();
});
it('should save cbx progress', async () => {
bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5));
expect(result).toBeUndefined();
});
it('should update date finished', async () => {
bookPatchServiceMock.updateDateFinished.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.updateDateFinished(1, '2020-01-01'));
expect(result).toBeUndefined();
});
it('should reset progress', async () => {
bookPatchServiceMock.resetProgress.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
const result = await firstValueFrom(service.resetProgress([1], 'BOOKLORE'));
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
});
it('should update book read status', async () => {
bookPatchServiceMock.updateBookReadStatus.mockReturnValue(of([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]));
const result = await firstValueFrom(service.updateBookReadStatus([1], ReadStatus.READ));
expect(result).toEqual([{bookId: 1, readStatus: ReadStatus.READ, readStatusModifiedTime: ''}]);
});
});
describe('Personal Rating', () => {
it('should reset personal rating', async () => {
bookPatchServiceMock.resetPersonalRating.mockReturnValue(of([{bookId: 1}]));
const result = await firstValueFrom(service.resetPersonalRating([1]));
expect(result).toEqual([{bookId: 1}]);
});
it('should update personal rating', async () => {
bookPatchServiceMock.updatePersonalRating.mockReturnValue(of([{bookId: 1, personalRating: 5}]));
const result = await firstValueFrom(service.updatePersonalRating([1], 5));
expect(result).toEqual([{bookId: 1, personalRating: 5}]);
});
});
describe('Metadata Operations', () => {
it('should update book metadata', async () => {
httpMock.put.mockReturnValue(of({bookId: 1}));
const spy = vi.spyOn(BookService.prototype, 'handleBookMetadataUpdate');
const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true));
expect(result).toEqual({bookId: 1});
expect(spy).toHaveBeenCalledWith(1, {bookId: 1});
spy.mockRestore();
});
it('should update books metadata', async () => {
httpMock.put.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.updateBooksMetadata({} as any));
expect(result).toBeUndefined();
});
it('should toggle all lock', async () => {
httpMock.put.mockReturnValue(of([{bookId: 1}]));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, metadata: {bookId: 1}}],
loaded: true,
error: null
});
const result = await firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'));
expect(result).toBeUndefined();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
it('should handle toggle all lock error', async () => {
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
await expect(firstValueFrom(service.toggleAllLock(new Set([1]), 'lock'))).rejects.toBeTruthy();
});
it('should toggle field locks', async () => {
httpMock.put.mockReturnValue(of(void 0));
bookStateServiceMock.getCurrentBookState.mockReturnValue({
books: [{id: 1, metadata: {}}],
loaded: true,
error: null
});
const result = await firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}));
expect(result).toBeUndefined();
expect(bookStateServiceMock.updateBookState).toHaveBeenCalled();
});
it('should handle toggle field locks error', async () => {
httpMock.put.mockReturnValue(throwError(() => ({message: 'fail'})));
await expect(firstValueFrom(service.toggleFieldLocks([1], {title: 'LOCK'}))).rejects.toBeTruthy();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'}));
});
it('should consolidate metadata', async () => {
httpMock.post.mockReturnValue(of({}));
service.refreshBooks = vi.fn();
await firstValueFrom(service.consolidateMetadata('authors', ['a'], ['b']));
expect(service.refreshBooks).toHaveBeenCalled();
});
it('should delete metadata', async () => {
httpMock.post.mockReturnValue(of({}));
service.refreshBooks = vi.fn();
await firstValueFrom(service.deleteMetadata('authors', ['a']));
expect(service.refreshBooks).toHaveBeenCalled();
});
});
describe('Cover Operations', () => {
it('should get upload cover url', () => {
expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload');
});
it('should regenerate covers', async () => {
httpMock.post.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.regenerateCovers());
expect(result).toBeUndefined();
});
it('should regenerate cover', async () => {
httpMock.post.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.regenerateCover(1));
expect(result).toBeUndefined();
});
it('should generate custom cover', async () => {
httpMock.post.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.generateCustomCover(1));
expect(result).toBeUndefined();
});
it('should regenerate covers for books', async () => {
httpMock.post.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.regenerateCoversForBooks([1, 2]));
expect(result).toBeUndefined();
});
it('should bulk upload cover', async () => {
httpMock.post.mockReturnValue(of(void 0));
const file = new File(['abc'], 'cover.jpg');
const result = await firstValueFrom(service.bulkUploadCover([1, 2], file));
expect(result).toBeUndefined();
});
});
describe('Websocket Handlers', () => {
it('should handle newly created book', () => {
const book = {id: 1};
service.handleNewlyCreatedBook(book as Book);
expect(bookSocketServiceMock.handleNewlyCreatedBook).toHaveBeenCalledWith(book);
});
it('should handle removed book ids', () => {
service.handleRemovedBookIds([1, 2]);
expect(bookSocketServiceMock.handleRemovedBookIds).toHaveBeenCalledWith([1, 2]);
});
it('should handle book update', () => {
const book = {id: 1};
service.handleBookUpdate(book as Book);
expect(bookSocketServiceMock.handleBookUpdate).toHaveBeenCalledWith(book);
});
it('should handle multiple book updates', () => {
const books = [{id: 1}, {id: 2}];
service.handleMultipleBookUpdates(books as Book[]);
expect(bookSocketServiceMock.handleMultipleBookUpdates).toHaveBeenCalledWith(books);
});
it('should handle book metadata update', () => {
service.handleBookMetadataUpdate(1, {bookId: 1} as BookMetadata);
expect(bookSocketServiceMock.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1});
});
it('should handle multiple book cover patches', () => {
const patches = [{id: 1, coverUpdatedOn: 'now'}];
service.handleMultipleBookCoverPatches(patches);
expect(bookSocketServiceMock.handleMultipleBookCoverPatches).toHaveBeenCalledWith(patches);
});
});
});
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
import {first, Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BookType, BulkMetadataUpdateRequest, CreatePhysicalBookRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {MessageService} from 'primeng/api';
@@ -242,9 +242,35 @@ export class BookService {
);
}
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
tap(newBook => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = [...(currentState.books || []), newBook];
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: 'Physical Book Created',
detail: `"${newBook.metadata?.title || 'Book'}" has been added to your library.`
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Creation Failed',
detail: error?.error?.message || error?.message || 'An error occurred while creating the physical book.'
});
return throwError(() => error);
})
);
}
/*------------------ Reading & Viewer Settings ------------------*/
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming'): void {
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming', explicitBookType?: BookType): void {
const book = this.bookStateService
.getCurrentBookState()
.books?.find(b => b.id === bookId);
@@ -254,10 +280,14 @@ export class BookService {
return;
}
let baseUrl: string | null = null;
let queryParams: Record<string, any> | undefined;
// Determine the book type - use explicit type if provided, otherwise use primary
const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType;
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
switch (book.bookType) {
let baseUrl: string | null = null;
let queryParams: Record<string, any> = {};
switch (bookType) {
case 'PDF':
baseUrl = reader === 'pdf-streaming' ? 'cbx-reader' : 'pdf-reader';
break;
@@ -265,7 +295,7 @@ export class BookService {
case 'EPUB':
baseUrl = 'ebook-reader';
if (reader === 'epub-streaming') {
queryParams = { streaming: true };
queryParams['streaming'] = true;
}
break;
@@ -278,20 +308,30 @@ export class BookService {
case 'CBX':
baseUrl = 'cbx-reader';
break;
case 'AUDIOBOOK':
baseUrl = 'audiobook-reader';
break;
}
if (!baseUrl) {
console.error('Unsupported book type:', book.bookType);
console.error('Unsupported book type:', bookType);
return;
}
this.router.navigate([`/${baseUrl}/book/${book.id}`], queryParams ? { queryParams } : undefined);
// Add bookType to query params if reading an alternative format
if (isAlternativeFormat) {
queryParams['bookType'] = bookType;
}
const hasQueryParams = Object.keys(queryParams).length > 0;
this.router.navigate([`/${baseUrl}/book/${book.id}`], hasQueryParams ? { queryParams } : undefined);
this.updateLastReadTime(book.id);
}
getBookSetting(bookId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
getBookSetting(bookId: number, bookFileId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting?bookFileId=${bookFileId}`);
}
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
@@ -300,13 +340,25 @@ export class BookService {
/*------------------ File Operations ------------------*/
getFileContent(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
let url = `${this.url}/${bookId}/content`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.http.get<Blob>(url, {responseType: 'blob' as 'json'});
}
downloadFile(book: Book): void {
const downloadUrl = `${this.url}/${book.id}/download`;
this.fileDownloadService.downloadFile(downloadUrl, book.fileName!);
this.fileDownloadService.downloadFile(downloadUrl, book.primaryFile?.fileName ?? 'book');
}
downloadAllFiles(book: Book): void {
const downloadUrl = `${this.url}/${book.id}/download-all`;
const fileName = book.metadata?.title
? `${book.metadata.title.replace(/[^a-zA-Z0-9\-_]/g, '_')}.zip`
: `book-${book.id}.zip`;
this.fileDownloadService.downloadFile(downloadUrl, fileName);
}
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
@@ -347,6 +399,63 @@ export class BookService {
);
}
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
return this.http.delete<void>(deleteUrl).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
if (isPrimary) {
// Primary file was deleted - promote first alternative to primary, or set null
const remainingAlternatives = book.alternativeFormats?.filter(file => file.id !== fileId) || [];
if (remainingAlternatives.length > 0) {
const [newPrimary, ...restAlternatives] = remainingAlternatives;
return {
...book,
primaryFile: newPrimary,
alternativeFormats: restAlternatives
};
} else {
return {
...book,
primaryFile: undefined,
alternativeFormats: []
};
}
} else {
// Alternative file was deleted
return {
...book,
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId)
};
}
}
return book;
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: 'File Deleted',
detail: 'Book file deleted successfully.'
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error?.error?.message || error?.message || 'An error occurred while deleting the file.'
});
return throwError(() => error);
})
);
}
uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType, description?: string): Observable<AdditionalFile> {
const formData = new FormData();
formData.append('file', file);
@@ -363,7 +472,9 @@ export class BookService {
? 'EPUB'
: (ext === 'cbz' || ext === 'cbr' || ext === 'cb7' || ext === 'cbt')
? 'CBX'
: null;
: (ext === 'm4b' || ext === 'm4a' || ext === 'mp3')
? 'AUDIOBOOK'
: null;
if (bookType) {
formData.append('bookType', bookType);
@@ -426,16 +537,16 @@ export class BookService {
this.bookPatchService.updateLastReadTime(bookId);
}
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
return this.bookPatchService.savePdfProgress(bookId, page, percentage);
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
return this.bookPatchService.savePdfProgress(bookId, page, percentage, bookFileId);
}
/*saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): Observable<void> {
return this.bookPatchService.saveEpubProgress(bookId, cfi, href, percentage);
}*/
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
return this.bookPatchService.saveCbxProgress(bookId, page, percentage);
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
return this.bookPatchService.saveCbxProgress(bookId, page, percentage, bookFileId);
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
@@ -621,4 +732,46 @@ export class BookService {
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
this.bookSocketService.handleMultipleBookCoverPatches(patches);
}
/*------------------ Book File Attachment ------------------*/
attachBookFiles(targetBookId: number, sourceBookIds: number[], deleteSourceBooks: boolean): Observable<Book> {
return this.http.post<Book>(`${this.url}/${targetBookId}/attach-file`, {
sourceBookIds,
deleteSourceBooks
}).pipe(
tap(updatedBook => {
const currentState = this.bookStateService.getCurrentBookState();
let updatedBooks = (currentState.books || []).map(book =>
book.id === targetBookId ? updatedBook : book
);
// If deleteSourceBooks, remove source books from state
if (deleteSourceBooks) {
const sourceIdSet = new Set(sourceBookIds);
updatedBooks = updatedBooks.filter(book => !sourceIdSet.has(book.id));
}
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
const fileCount = sourceBookIds.length;
this.messageService.add({
severity: 'success',
summary: 'Files Attached',
detail: `${fileCount} book file${fileCount > 1 ? 's have' : ' has'} been attached successfully.`
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Attachment Failed',
detail: error?.error?.message || error?.message || 'An error occurred while attaching the files.'
});
return throwError(() => error);
})
);
}
}
@@ -1,96 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {CbxReaderService} from './cbx-reader.service';
import {AuthService} from '../../../shared/service/auth.service';
describe('CbxReaderService', () => {
let service: CbxReaderService;
let httpClientMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
TestBed.configureTestingModule({
providers: [
CbxReaderService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(CbxReaderService)
);
});
it('should get available pages with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('abc123');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
httpClientMock.get.mockReturnValue(of([1, 2, 3]));
service.getAvailablePages(42).subscribe(pages => {
expect(pages).toEqual([1, 2, 3]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('token=abc123'));
});
});
it('should get available pages without token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
httpClientMock.get.mockReturnValue(of([4, 5]));
service.getAvailablePages(99).subscribe(pages => {
expect(pages).toEqual([4, 5]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.not.stringContaining('token='));
});
});
it('should handle error when getting available pages', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getAvailablePages(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should return correct page image url with oidc token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getPageImageUrl(5, 7);
expect(url).toContain('/api/v1/media/book/5/cbx/pages/7');
expect(url).toContain('token=tok');
});
it('should return correct page image url with internal token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue('inttok');
const url = service.getPageImageUrl(8, 2);
expect(url).toContain('/api/v1/media/book/8/cbx/pages/2');
expect(url).toContain('token=inttok');
});
it('should return correct page image url without token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getPageImageUrl(3, 1);
expect(url).toContain('/api/v1/media/book/3/cbx/pages/1');
expect(url).not.toContain('token=');
});
});
@@ -25,15 +25,27 @@ export class CbxReaderService {
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getAvailablePages(bookId: number) {
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
getAvailablePages(bookId: number, bookType?: string) {
let url = `${this.pagesUrl}/${bookId}/pages`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.http.get<number[]>(this.appendToken(url));
}
getPageInfo(bookId: number) {
return this.http.get<CbxPageInfo[]>(this.appendToken(`${this.pagesUrl}/${bookId}/page-info`));
getPageInfo(bookId: number, bookType?: string) {
let url = `${this.pagesUrl}/${bookId}/page-info`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.http.get<CbxPageInfo[]>(this.appendToken(url));
}
getPageImageUrl(bookId: number, page: number): string {
return this.appendToken(`${this.imageUrl}/${bookId}/cbx/pages/${page}`);
getPageImageUrl(bookId: number, page: number, bookType?: string): string {
let url = `${this.imageUrl}/${bookId}/cbx/pages/${page}`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.appendToken(url);
}
}
@@ -1,350 +0,0 @@
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {ConfirmationService, MessageService} from 'primeng/api';
import {Router} from '@angular/router';
import {LibraryService} from './library.service';
import {ShelfService} from './shelf.service';
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {UserService} from "../../settings/user-management/user.service";
import {LoadingService} from '../../../core/services/loading.service';
import {LibraryShelfMenuService} from './library-shelf-menu.service';
import {Library} from '../model/library.model';
import {Shelf} from '../model/shelf.model';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {of, throwError} from 'rxjs';
import {beforeEach, describe, expect, it, vi} from 'vitest';
describe('LibraryShelfMenuService', () => {
let service: LibraryShelfMenuService;
let confirmationService: any;
let messageService: any;
let libraryService: any;
let shelfService: any;
let taskHelperService: any;
let router: any;
let dialogLauncherService: any;
let magicShelfService: any;
let userService: any;
let loadingService: any;
const mockLibrary: Library = {id: 1, name: 'Lib1'} as Library;
const mockShelf: Shelf = {id: 2, name: 'Shelf1'} as Shelf;
const mockMagicShelf: MagicShelf = {id: 3, name: 'Magic1', isPublic: false} as MagicShelf;
beforeEach(() => {
confirmationService = {confirm: vi.fn()};
messageService = {add: vi.fn()};
libraryService = {
refreshLibrary: vi.fn(),
deleteLibrary: vi.fn()
};
shelfService = {
deleteShelf: vi.fn()
};
taskHelperService = {
refreshMetadataTask: vi.fn()
};
router = {navigate: vi.fn()};
dialogLauncherService = {
openLibraryEditDialog: vi.fn(),
openLibraryMetadataFetchDialog: vi.fn(),
openShelfEditDialog: vi.fn(),
openMagicShelfEditDialog: vi.fn()
};
magicShelfService = {
deleteShelf: vi.fn()
};
userService = {
getCurrentUser: vi.fn()
};
loadingService = {
show: vi.fn().mockReturnValue('loader-id'),
hide: vi.fn()
};
TestBed.configureTestingModule({
providers: [
LibraryShelfMenuService,
{provide: ConfirmationService, useValue: confirmationService},
{provide: MessageService, useValue: messageService},
{provide: LibraryService, useValue: libraryService},
{provide: ShelfService, useValue: shelfService},
{provide: TaskHelperService, useValue: taskHelperService},
{provide: Router, useValue: router},
{provide: DialogLauncherService, useValue: dialogLauncherService},
{provide: MagicShelfService, useValue: magicShelfService},
{provide: UserService, useValue: userService},
{provide: LoadingService, useValue: loadingService}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(LibraryShelfMenuService));
});
describe('initializeLibraryMenuItems', () => {
it('should provide all menu items for a library', () => {
const items = service.initializeLibraryMenuItems(mockLibrary);
expect(items.length).toBe(1);
const options = items[0].items!;
expect(options.some(i => i.label === 'Edit Library')).toBe(true);
expect(options.some(i => i.label === 'Re-scan Library')).toBe(true);
expect(options.some(i => i.label === 'Custom Fetch Metadata')).toBe(true);
expect(options.some(i => i.label === 'Auto Fetch Metadata')).toBe(true);
expect(options.some(i => i.label === 'Delete Library')).toBe(true);
});
it('should call openLibraryEditDialog when Edit Library is clicked', () => {
const items = service.initializeLibraryMenuItems(mockLibrary);
const edit = items[0].items!.find(i => i.label === 'Edit Library');
edit!.command!({});
expect(dialogLauncherService.openLibraryEditDialog).toHaveBeenCalledWith(mockLibrary.id);
});
it('should call openLibraryMetadataFetchDialog when Custom Fetch Metadata is clicked', () => {
const items = service.initializeLibraryMenuItems(mockLibrary);
const fetch = items[0].items!.find(i => i.label === 'Custom Fetch Metadata');
fetch!.command!({});
expect(dialogLauncherService.openLibraryMetadataFetchDialog).toHaveBeenCalledWith(mockLibrary.id);
});
it('should call refreshMetadataTask when Auto Fetch Metadata is clicked', () => {
taskHelperService.refreshMetadataTask.mockReturnValue(of({}));
const items = service.initializeLibraryMenuItems(mockLibrary);
const auto = items[0].items!.find(i => i.label === 'Auto Fetch Metadata');
auto!.command!({});
expect(taskHelperService.refreshMetadataTask).toHaveBeenCalledWith({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: mockLibrary.id
});
});
it('should show confirmation dialog for Re-scan Library', () => {
libraryService.refreshLibrary.mockReturnValue(of({}));
const items = service.initializeLibraryMenuItems(mockLibrary);
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
rescan!.command!({});
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
const confirmCall = confirmationService.confirm.mock.calls[0][0];
expect(confirmCall.message).toContain(mockLibrary.name);
expect(confirmCall.header).toBe('Confirmation');
});
it('should refresh library and show success message on accept', () => {
libraryService.refreshLibrary.mockReturnValue(of({}));
const items = service.initializeLibraryMenuItems(mockLibrary);
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
rescan!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(libraryService.refreshLibrary).toHaveBeenCalledWith(mockLibrary.id);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'info',
summary: 'Success',
detail: 'Library refresh scheduled'
});
});
it('should show error message if refreshLibrary fails', () => {
libraryService.refreshLibrary.mockReturnValue(throwError(() => ({})));
const items = service.initializeLibraryMenuItems(mockLibrary);
const rescan = items[0].items!.find(i => i.label === 'Re-scan Library');
rescan!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'Failed to refresh library'
});
});
it('should show confirmation dialog for Delete Library', () => {
libraryService.deleteLibrary.mockReturnValue(of({}));
const items = service.initializeLibraryMenuItems(mockLibrary);
const del = items[0].items!.find(i => i.label === 'Delete Library');
del!.command!({});
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
const confirmCall = confirmationService.confirm.mock.calls[0][0];
expect(confirmCall.message).toContain(mockLibrary.name);
expect(confirmCall.header).toBe('Confirmation');
});
it('should delete library, navigate, and show success message on accept', () => {
libraryService.deleteLibrary.mockReturnValue(of({}));
const items = service.initializeLibraryMenuItems(mockLibrary);
const del = items[0].items!.find(i => i.label === 'Delete Library');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(loadingService.show).toHaveBeenCalledWith(expect.stringContaining(mockLibrary.name));
expect(libraryService.deleteLibrary).toHaveBeenCalledWith(mockLibrary.id);
expect(router.navigate).toHaveBeenCalledWith(['/']);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'info',
summary: 'Success',
detail: 'Library was deleted'
});
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
});
it('should show error message if deleteLibrary fails', () => {
libraryService.deleteLibrary.mockReturnValue(throwError(() => ({})));
const items = service.initializeLibraryMenuItems(mockLibrary);
const del = items[0].items!.find(i => i.label === 'Delete Library');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete library'
});
expect(loadingService.hide).toHaveBeenCalledWith('loader-id');
});
});
describe('initializeShelfMenuItems', () => {
it('should provide all menu items for a shelf', () => {
const items = service.initializeShelfMenuItems(mockShelf);
expect(items.length).toBe(1);
const options = items[0].items!;
expect(options.some(i => i.label === 'Edit Shelf')).toBe(true);
expect(options.some(i => i.label === 'Delete Shelf')).toBe(true);
});
it('should call openShelfEditDialog when Edit Shelf is clicked', () => {
const items = service.initializeShelfMenuItems(mockShelf);
const edit = items[0].items!.find(i => i.label === 'Edit Shelf');
edit!.command!({});
expect(dialogLauncherService.openShelfEditDialog).toHaveBeenCalledWith(mockShelf.id);
});
it('should show confirmation dialog for Delete Shelf', () => {
shelfService.deleteShelf.mockReturnValue(of({}));
const items = service.initializeShelfMenuItems(mockShelf);
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
del!.command!({});
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
const confirmCall = confirmationService.confirm.mock.calls[0][0];
expect(confirmCall.message).toContain(mockShelf.name);
expect(confirmCall.header).toBe('Confirmation');
});
it('should delete shelf, navigate, and show success message on accept', () => {
shelfService.deleteShelf.mockReturnValue(of({}));
const items = service.initializeShelfMenuItems(mockShelf);
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(shelfService.deleteShelf).toHaveBeenCalledWith(mockShelf.id);
expect(router.navigate).toHaveBeenCalledWith(['/']);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'info',
summary: 'Success',
detail: 'Shelf was deleted'
});
});
it('should show error message if deleteShelf fails', () => {
shelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
const items = service.initializeShelfMenuItems(mockShelf);
const del = items[0].items!.find(i => i.label === 'Delete Shelf');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete shelf'
});
});
});
describe('initializeMagicShelfMenuItems', () => {
it('should provide all menu items for a magic shelf', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
expect(items.length).toBe(1);
const options = items[0].items!;
expect(options.some(i => i.label === 'Edit Magic Shelf')).toBe(true);
expect(options.some(i => i.label === 'Delete Magic Shelf')).toBe(true);
});
it('should call openMagicShelfEditDialog when Edit Magic Shelf is clicked', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
edit!.command!({});
expect(dialogLauncherService.openMagicShelfEditDialog).toHaveBeenCalledWith(mockMagicShelf.id);
});
it('should show confirmation dialog for Delete Magic Shelf', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
magicShelfService.deleteShelf.mockReturnValue(of({}));
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
del!.command!({});
expect(confirmationService.confirm).toHaveBeenCalledTimes(1);
const confirmCall = confirmationService.confirm.mock.calls[0][0];
expect(confirmCall.message).toContain(mockMagicShelf.name);
expect(confirmCall.header).toBe('Confirmation');
});
it('should delete magic shelf, navigate, and show success message on accept', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
magicShelfService.deleteShelf.mockReturnValue(of({}));
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(magicShelfService.deleteShelf).toHaveBeenCalledWith(mockMagicShelf.id);
expect(router.navigate).toHaveBeenCalledWith(['/']);
expect(messageService.add).toHaveBeenCalledWith({
severity: 'info',
summary: 'Success',
detail: 'Magic shelf was deleted'
});
});
it('should show error message if deleteMagicShelf fails', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
magicShelfService.deleteShelf.mockReturnValue(throwError(() => ({})));
const items = service.initializeMagicShelfMenuItems(mockMagicShelf);
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
del!.command!({});
const confirmCall = confirmationService.confirm.mock.calls[0][0];
confirmCall.accept();
expect(messageService.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete shelf'
});
});
it('should disable options for public shelf if not admin', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: false}});
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
expect(edit!.disabled).toBe(true);
expect(del!.disabled).toBe(true);
});
it('should not disable options for public shelf if admin', () => {
userService.getCurrentUser.mockReturnValue({permissions: {admin: true}});
const publicMagicShelf = {...mockMagicShelf, isPublic: true};
const items = service.initializeMagicShelfMenuItems(publicMagicShelf);
const edit = items[0].items!.find(i => i.label === 'Edit Magic Shelf');
const del = items[0].items!.find(i => i.label === 'Delete Magic Shelf');
expect(edit!.disabled).toBe(false);
expect(del!.disabled).toBe(false);
});
});
});
@@ -12,6 +12,7 @@ import {UserService} from "../../settings/user-management/user.service";
import {LoadingService} from '../../../core/services/loading.service';
import {finalize} from 'rxjs';
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
@Injectable({
providedIn: 'root',
@@ -28,12 +29,23 @@ export class LibraryShelfMenuService {
private magicShelfService = inject(MagicShelfService);
private userService = inject(UserService);
private loadingService = inject(LoadingService);
private bookDialogHelperService = inject(BookDialogHelperService);
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
return [
{
label: 'Options',
items: [
{
label: 'Add Physical Book',
icon: 'pi pi-book',
command: () => {
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
}
},
{
separator: true
},
{
label: 'Edit Library',
icon: 'pi pi-pen-to-square',
@@ -1,167 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {firstValueFrom, of, throwError} from 'rxjs';
import {LibraryService} from './library.service';
import {BookService} from './book.service';
import {AuthService} from '../../../shared/service/auth.service';
import {Library} from '../model/library.model';
describe('LibraryService', () => {
let service: LibraryService;
let httpClientMock: any;
let bookServiceMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn()
};
bookServiceMock = {
removeBooksByLibraryId: vi.fn(),
bookState$: of({
books: [
{id: 1, libraryId: 10},
{id: 2, libraryId: 20},
{id: 3, libraryId: 10},
{id: 4}
]
})
};
authServiceMock = {
token$: of('token')
};
TestBed.configureTestingModule({
providers: [
LibraryService,
{provide: HttpClient, useValue: httpClientMock},
{provide: BookService, useValue: bookServiceMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(LibraryService)
);
});
it('should fetch libraries and update state', () => {
const libraries: Library[] = [{id: 1, name: 'LibA', icon: 'icon', watch: true, paths: []}];
httpClientMock.get.mockReturnValue(of(libraries));
service['fetchLibraries']().subscribe(result => {
expect(result).toEqual(libraries);
expect(service['libraryStateSubject'].value.libraries).toEqual(libraries);
expect(service['libraryStateSubject'].value.loaded).toBe(true);
});
});
it('should handle fetch libraries error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['libraryStateSubject'].next({libraries: null, loaded: false, error: null});
service['fetchLibraries']().subscribe({
error: (err: any) => {
expect(service['libraryStateSubject'].value.error).toBe('fail');
}
});
});
it('should create a library and update state', () => {
const library: Library = {id: 2, name: 'LibB', icon: 'icon', watch: true, paths: []};
httpClientMock.post.mockReturnValue(of(library));
service['libraryStateSubject'].next({libraries: [], loaded: true, error: null});
service.createLibrary(library).subscribe(result => {
expect(result).toEqual(library);
expect(service['libraryStateSubject'].value.libraries).toContain(library);
});
});
it('should update a library and update state', () => {
const library: Library = {id: 3, name: 'LibC', icon: 'icon', watch: true, paths: []};
httpClientMock.put.mockReturnValue(of({...library, name: 'LibC2'}));
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
service.updateLibrary({...library, name: 'LibC2'}, 3).subscribe(result => {
expect(result.name).toBe('LibC2');
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 3)?.name).toBe('LibC2');
});
});
it('should delete a library and update state', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
const library: Library = {id: 4, name: 'LibD', icon: 'icon', watch: true, paths: []};
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
service.deleteLibrary(4).subscribe(() => {
expect(service['libraryStateSubject'].value.libraries).toEqual([]);
expect(bookServiceMock.removeBooksByLibraryId).toHaveBeenCalledWith(4);
});
});
it('should handle delete library error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
service['libraryStateSubject'].next({libraries: [{id: 5, name: 'LibE', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
service.deleteLibrary(5).subscribe({
error: () => {
expect(service['libraryStateSubject'].value.error).toBe('delete error');
}
});
});
it('should refresh a library and handle error', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('refresh error')));
service['libraryStateSubject'].next({libraries: [{id: 6, name: 'LibF', icon: 'icon', watch: true, paths: []}], loaded: true, error: null});
service.refreshLibrary(6).subscribe({
error: () => {
expect(service['libraryStateSubject'].value.error).toBe('refresh error');
}
});
});
it('should update library file naming pattern', () => {
const library: Library = {id: 7, name: 'LibG', icon: 'icon', watch: true, paths: [], fileNamingPattern: 'old'};
const updatedLibrary = {...library, fileNamingPattern: 'new'};
httpClientMock.patch.mockReturnValue(of(updatedLibrary));
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
service.updateLibraryFileNamingPattern(7, 'new').subscribe(result => {
expect(result.fileNamingPattern).toBe('new');
expect(service['libraryStateSubject'].value.libraries?.find(l => l.id === 7)?.fileNamingPattern).toBe('new');
});
});
it('should check if library exists by name', () => {
const library: Library = {id: 8, name: 'LibH', icon: 'icon', watch: true, paths: []};
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
expect(service.doesLibraryExistByName('LibH')).toBe(true);
expect(service.doesLibraryExistByName('NonExistent')).toBe(false);
});
it('should find library by id', () => {
const library: Library = {id: 9, name: 'LibI', icon: 'icon', watch: true, paths: []};
service['libraryStateSubject'].next({libraries: [library], loaded: true, error: null});
expect(service.findLibraryById(9)).toEqual(library);
expect(service.findLibraryById(999)).toBeUndefined();
});
it('should get libraries from state', () => {
const libraries: Library[] = [
{id: 10, name: 'LibJ', icon: 'icon', watch: true, paths: []}
];
service['libraryStateSubject'].next({libraries, loaded: true, error: null});
expect(service.getLibrariesFromState()).toEqual(libraries);
});
it('should get book count for library', async () => {
const count = await firstValueFrom(service.getBookCount(10));
expect(count).toBe(2);
});
});
@@ -1,123 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {firstValueFrom, of, throwError} from 'rxjs';
import {MetadataFetchTask, MetadataTaskService} from './metadata-task';
import {API_CONFIG} from '../../../core/config/api-config';
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../../../shared/model/metadata-batch-progress.model';
describe('MetadataTaskService', () => {
let service: MetadataTaskService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
delete: vi.fn(),
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataTaskService,
{ provide: HttpClient, useValue: httpClientMock }
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataTaskService)
);
});
it('should get task with proposals', async () => {
const task: MetadataFetchTask = {
id: 'task1',
status: 'IN_PROGRESS',
completed: 1,
totalBooks: 2,
startedAt: '2024-01-01T00:00:00Z',
completedAt: null,
initiatedBy: 'user1',
errorMessage: null,
proposals: []
};
httpClientMock.get.mockReturnValue(of({ task }));
const result = await firstValueFrom(service.getTaskWithProposals('task1'));
expect(result).toEqual(task);
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task1`);
});
it('should handle error in getTaskWithProposals', async () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
try {
await firstValueFrom(service.getTaskWithProposals('task2'));
} catch (e: any) {
expect(e.message).toBe('fail');
}
});
it('should delete a task', async () => {
httpClientMock.delete.mockReturnValue(of(void 0));
await firstValueFrom(service.deleteTask('task3'));
expect(httpClientMock.delete).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/task3`);
});
it('should handle error in deleteTask', async () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
try {
await firstValueFrom(service.deleteTask('task4'));
} catch (e: any) {
expect(e.message).toBe('delete error');
}
});
it('should update proposal status', async () => {
httpClientMock.post.mockReturnValue(of(void 0));
await firstValueFrom(service.updateProposalStatus('task5', 123, 'ACCEPTED'));
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/metadata/tasks/task5/proposals/123/status`,
null,
{ params: { status: 'ACCEPTED' } }
);
});
it('should handle error in updateProposalStatus', async () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('status error')));
try {
await firstValueFrom(service.updateProposalStatus('task6', 456, 'REJECTED'));
} catch (e: any) {
expect(e.message).toBe('status error');
}
});
it('should get active tasks', async () => {
const notifications: MetadataBatchProgressNotification[] = [
{
taskId: 't1',
completed: 1,
total: 2,
message: 'Running',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
}
];
httpClientMock.get.mockReturnValue(of(notifications));
const result = await firstValueFrom(service.getActiveTasks());
expect(result).toEqual(notifications);
expect(httpClientMock.get).toHaveBeenCalledWith(`${API_CONFIG.BASE_URL}/api/metadata/tasks/active`);
});
it('should handle error in getActiveTasks', async () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('active error')));
try {
await firstValueFrom(service.getActiveTasks());
} catch (e: any) {
expect(e.message).toBe('active error');
}
});
});
@@ -1,70 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {NewPdfReaderService} from './new-pdf-reader.service';
import {AuthService} from '../../../shared/service/auth.service';
import {API_CONFIG} from '../../../core/config/api-config';
describe('NewPdfReaderService', () => {
let service: NewPdfReaderService;
let authServiceMock: any;
let httpClientMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
NewPdfReaderService,
{provide: AuthService, useValue: authServiceMock},
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(NewPdfReaderService)
);
});
it('should append token from OIDC access token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = 'http://test.com/resource';
const result = (service as any).appendToken(url);
expect(result).toContain('token=oidc-token');
});
it('should not append token if both tokens are null', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = 'http://test.com/resource';
const result = (service as any).appendToken(url);
expect(result).toBe(url);
});
it('should call http.get with correct URL', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('token123');
service.getAvailablePages(42);
expect(httpClientMock.get).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/pdf/42/pages?token=token123`
);
});
});
@@ -38,15 +38,27 @@ export class NewPdfReaderService {
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getAvailablePages(bookId: number) {
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
getAvailablePages(bookId: number, bookType?: string) {
let url = `${this.pagesUrl}/${bookId}/pages`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.http.get<number[]>(this.appendToken(url));
}
getPageInfo(bookId: number) {
return this.http.get<PdfInfo>(this.appendToken(`${this.pagesUrl}/${bookId}/info`));
getPageInfo(bookId: number, bookType?: string) {
let url = `${this.pagesUrl}/${bookId}/info`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.http.get<PdfInfo>(this.appendToken(url));
}
getPageImageUrl(bookId: number, page: number): string {
return this.appendToken(`${this.imageUrl}/${bookId}/pdf/pages/${page}`);
getPageImageUrl(bookId: number, page: number, bookType?: string): string {
let url = `${this.imageUrl}/${bookId}/pdf/pages/${page}`;
if (bookType) {
url += `?bookType=${bookType}`;
}
return this.appendToken(url);
}
}
@@ -1,131 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {firstValueFrom, of, throwError} from 'rxjs';
import {ShelfService} from './shelf.service';
import {BookService} from './book.service';
import {UserService} from '../../settings/user-management/user.service';
import {Shelf} from '../model/shelf.model';
describe('ShelfService', () => {
let service: ShelfService;
let httpClientMock: any;
let bookServiceMock: any;
let userServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
bookServiceMock = {
removeBooksFromShelf: vi.fn(),
bookState$: of({
books: [
{id: 1, shelves: [{id: 10}]},
{id: 2, shelves: [{id: 20}]},
{id: 3, shelves: []},
{id: 4}
]
})
};
userServiceMock = {
userState$: of({user: {id: 1}})
};
TestBed.configureTestingModule({
providers: [
ShelfService,
{provide: HttpClient, useValue: httpClientMock},
{provide: BookService, useValue: bookServiceMock},
{provide: UserService, useValue: userServiceMock},
{provide: 'OAuthService', useValue: {}}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(ShelfService)
);
});
it('should fetch shelves and update state', () => {
const shelves: Shelf[] = [{id: 1, name: 'A', icon: 'icon'}];
httpClientMock.get.mockReturnValue(of(shelves));
service['fetchShelves']().subscribe(result => {
expect(result).toEqual(shelves);
expect(service['shelfStateSubject'].value.shelves).toEqual(shelves);
expect(service['shelfStateSubject'].value.loaded).toBe(true);
});
});
it('should handle fetch shelves error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['shelfStateSubject'].next({shelves: null, loaded: false, error: null});
service['fetchShelves']().subscribe({
error: (err: any) => {
expect(service['shelfStateSubject'].value.error).toBe('fail');
}
});
});
it('should create a shelf and update state', () => {
const shelf: Shelf = {id: 2, name: 'B', icon: 'icon'};
httpClientMock.post.mockReturnValue(of(shelf));
service['shelfStateSubject'].next({shelves: [], loaded: true, error: null});
service.createShelf(shelf).subscribe(result => {
expect(result).toEqual(shelf);
expect(service['shelfStateSubject'].value.shelves).toContain(shelf);
});
});
it('should update a shelf and update state', () => {
const shelf: Shelf = {id: 3, name: 'C', icon: 'icon'};
httpClientMock.put.mockReturnValue(of({...shelf, name: 'C2'}));
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
service.updateShelf({...shelf, name: 'C2'}, 3).subscribe(result => {
expect(result.name).toBe('C2');
expect(service['shelfStateSubject'].value.shelves?.find(s => s.id === 3)?.name).toBe('C2');
});
});
it('should delete a shelf and update state', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
const shelf: Shelf = {id: 4, name: 'D', icon: 'icon'};
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
service.deleteShelf(4).subscribe(() => {
expect(service['shelfStateSubject'].value.shelves).toEqual([]);
expect(bookServiceMock.removeBooksFromShelf).toHaveBeenCalledWith(4);
});
});
it('should handle delete shelf error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('delete error')));
service['shelfStateSubject'].next({shelves: [{id: 5, name: 'E', icon: 'icon'}], loaded: true, error: null});
service.deleteShelf(5).subscribe({
error: () => {
expect(service['shelfStateSubject'].value.error).toBe('delete error');
}
});
});
it('should get shelf by id', () => {
const shelf: Shelf = {id: 6, name: 'F', icon: 'icon'};
service['shelfStateSubject'].next({shelves: [shelf], loaded: true, error: null});
expect(service.getShelfById(6)).toEqual(shelf);
expect(service.getShelfById(999)).toBeUndefined();
});
it('should get unshelved book count', async () => {
const count = await firstValueFrom(service.getUnshelvedBookCount());
expect(count).toBe(2);
});
});
@@ -1,153 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {SortService} from './sort.service';
import {Book} from '../model/book.model';
import {SortDirection} from '../model/sort.model';
function makeBook(partial: Partial<Book>): Book {
return {
id: 1,
bookType: "PDF",
libraryId: 1,
libraryName: "Lib",
...partial,
} as Book;
}
describe('SortService', () => {
let service: SortService;
let books: Book[];
beforeEach(() => {
service = new SortService();
books = [
makeBook({
id: 1,
fileName: 'Book10.pdf',
metadata: {
bookId: 1,
title: 'Book 10',
authors: ['Alice'],
publishedDate: '2020-01-01',
seriesName: 'Series A',
seriesNumber: 2,
rating: 4.5,
reviewCount: 10,
},
personalRating: 3,
addedOn: '2021-01-01T00:00:00Z',
lastReadTime: '2022-01-01T00:00:00Z',
fileSizeKb: 1000,
}),
makeBook({
id: 2,
fileName: 'Book2.pdf',
metadata: {
bookId: 2,
title: 'Book 2',
authors: ['Bob'],
publishedDate: '2019-01-01',
seriesName: 'Series A',
seriesNumber: 1,
rating: 4.8,
reviewCount: 20,
},
personalRating: 5,
addedOn: '2020-01-01T00:00:00Z',
lastReadTime: '2023-01-01T00:00:00Z',
fileSizeKb: 2000,
}),
makeBook({
id: 3,
fileName: 'Book1.pdf',
metadata: {
bookId: 3,
title: 'Book 1',
authors: ['Alice'],
publishedDate: '2021-01-01',
rating: 4.0,
reviewCount: 5,
},
personalRating: 4,
addedOn: '2022-01-01T00:00:00Z',
lastReadTime: '2021-01-01T00:00:00Z',
fileSizeKb: 500,
}),
];
});
it('should sort by title (natural order)', () => {
const sorted = service.applySort(books, {field: 'title', direction: SortDirection.ASCENDING, label: 'Title'});
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
});
it('should sort by author', () => {
const sorted = service.applySort(books, {field: 'author', direction: SortDirection.ASCENDING, label: 'Author'});
expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Alice', 'Alice', 'Bob']);
});
it('should sort by author surname', () => {
const testBooks = [
makeBook({ id: 1, metadata: { bookId: 1, title: 'T1', authors: ['Terry Pratchett'] } }),
makeBook({ id: 2, metadata: { bookId: 2, title: 'T2', authors: ['Neil Gaiman'] } }),
makeBook({ id: 3, metadata: { bookId: 3, title: 'T3', authors: ['Stephen King'] } }),
];
const sorted = service.applySort(testBooks, { field: 'authorSurnameVorname', direction: SortDirection.ASCENDING, label: 'Author (Surname)' });
expect(sorted.map(b => b.metadata?.authors?.[0])).toEqual(['Neil Gaiman', 'Stephen King', 'Terry Pratchett']);
});
it('should sort by publishedDate descending', () => {
const sorted = service.applySort(books, {field: 'publishedDate', direction: SortDirection.DESCENDING, label: 'Published Date'});
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 10', 'Book 2']);
});
it('should sort by series (titleSeries)', () => {
const sorted = service.applySort(books, {field: 'titleSeries', direction: SortDirection.ASCENDING, label: 'Series'});
expect(sorted.map(b => b.metadata?.title)).toEqual(['Book 1', 'Book 2', 'Book 10']);
});
it('should sort by personalRating descending', () => {
const sorted = service.applySort(books, {field: 'personalRating', direction: SortDirection.DESCENDING, label: 'Personal Rating'});
expect(sorted.map(b => b.personalRating)).toEqual([5, 4, 3]);
});
it('should sort by fileName (natural order)', () => {
const sorted = service.applySort(books, {field: 'fileName', direction: SortDirection.ASCENDING, label: 'File Name'});
expect(sorted.map(b => b.fileName)).toEqual(['Book1.pdf', 'Book2.pdf', 'Book10.pdf']);
});
it('should sort by fileSizeKb ascending', () => {
const sorted = service.applySort(books, {field: 'fileSizeKb', direction: SortDirection.ASCENDING, label: 'File Size'});
expect(sorted.map(b => b.fileSizeKb)).toEqual([500, 1000, 2000]);
});
it('should sort by addedOn descending', () => {
const sorted = service.applySort(books, {field: 'addedOn', direction: SortDirection.DESCENDING, label: 'Added On'});
expect(sorted.map(b => b.addedOn)).toEqual([
'2022-01-01T00:00:00Z',
'2021-01-01T00:00:00Z',
'2020-01-01T00:00:00Z',
]);
});
it('should handle missing extractor gracefully', () => {
const spy = vi.spyOn(console, 'warn').mockImplementation(() => {
});
const sorted = service.applySort(books, {field: 'nonexistent', direction: SortDirection.ASCENDING, label: 'Nonexistent'} as any);
expect(sorted).toBe(books);
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
it('should return original array if no sort option', () => {
const sorted = service.applySort(books, null);
expect(sorted).toBe(books);
});
it('should sort by random (order is not predictable)', () => {
const sorted = service.applySort(books, {field: 'random', direction: SortDirection.ASCENDING, label: 'Random'});
expect(sorted.length).toBe(3);
// Can't assert order, but should be a permutation of the input
expect(sorted.map(b => b.id).sort()).toEqual([1, 2, 3]);
});
});