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:
@@ -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]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user