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

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

* feat: add streaming reader support for alternative EPUB formats

* refactor: extract tabs section into MetadataTabsComponent

* feat: implement per-file reading progress tracking

* feat: add configurable format priority with cascading fallback

* refactor: redesign library creator with single-page layout

* refactor: unify reading progress into ReadingProgressService

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

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

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

* fix: display unique format types in metadata viewer

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

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

* refactor: consolidate book grouping with organization mode support

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

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

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

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

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

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

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

* style: improve library creator dialog spacing and layout

* fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility

* fix: FileMoveService now handles multi-file BookEntity properly

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

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

* style: relax spacing in library-creator component

* style: tighten directory-picker layout for consistency

* fix: PathPatternResolver now respects folderBased flag for audiobooks

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

* refactor: consolidate BookFileType into BookType and add audiobook styling

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

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

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

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

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

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

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

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

* fix: update FileMoveService tests to include AppProperties parameter

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

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

* feat: add audiobook streaming player with HTTP Range support

* feat: add M4B chapter extraction and chapter navigation

* feat: add audiobook bookmarks and sleep timer

* refactor: split AudiobookReaderService into focused services

* feat: add Media Session API for background audio playback

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

* feat: require bookFileId for viewer settings API

* fix: show split button for audiobooks with readable alternatives

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

* feat: add audiobook play button in files tab

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

* feat: add extension field to BookFile DTO

* feat: use extension field for book card format pill

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

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

* fix: increase drag handle size for format priority chips

* fix: add missing BookFileRepository mock to BookServiceDeleteTests

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

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

* refactor: redesign icon-picker component with improved styling

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

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

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

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

* fix: navigate to first page when opening unread ebooks

* fix: exclude API requests from service worker interception

* feat: support fileless books with automatic file attachment

* fix: bypass service worker for audiobook streaming requests

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

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-27 10:12:50 -07:00
committed by GitHub
co-authored by acx10
parent c23e38b5a5
commit 3f334202b6
340 changed files with 23225 additions and 20727 deletions
@@ -34,7 +34,7 @@ export class AppConfigService {
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
800: '#283548',
900: '#0f172a',
950: '#020617'
}
@@ -51,7 +51,7 @@ export class AppConfigService {
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
@@ -68,7 +68,7 @@ export class AppConfigService {
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
800: '#303030',
900: '#171717',
950: '#0a0a0a'
}
@@ -85,7 +85,7 @@ export class AppConfigService {
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
800: '#313136',
900: '#18181b',
950: '#09090b'
}
@@ -102,7 +102,7 @@ export class AppConfigService {
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#292524',
800: '#342f2b',
900: '#1c1917',
950: '#0c0a09'
}
@@ -204,7 +204,7 @@ export class AppConfigService {
500: '#5c6b7a',
600: '#4a5866',
700: '#3b4651',
800: '#2d353e',
800: '#38424d',
900: '#1f252c',
950: '#121518'
}
@@ -222,7 +222,7 @@ export class AppConfigService {
600: '#666666',
700: '#525252',
800: '#3d3d3d',
900: '#2a2a2a',
900: '#242424',
950: '#141414'
}
},
@@ -239,7 +239,7 @@ export class AppConfigService {
600: '#6a6b70',
700: '#55565b',
800: '#3f4046',
900: '#2c2c34',
900: '#252530',
950: '#16161d'
}
},
@@ -256,7 +256,7 @@ export class AppConfigService {
600: '#6e7173',
700: '#565a5b',
800: '#3e4244',
900: '#262b2c',
900: '#1e2324',
950: '#0e1315'
}
},
@@ -272,7 +272,7 @@ export class AppConfigService {
500: '#828787',
600: '#5F7274',
700: '#415B61',
800: '#29444E',
800: '#324f5a',
900: '#183240',
950: '#0c1920'
}
@@ -289,7 +289,7 @@ export class AppConfigService {
500: '#94a3b8',
600: '#64748b',
700: '#475569',
800: '#334155',
800: '#3d5068',
900: '#1e293b',
950: '#0f172a'
}
@@ -306,7 +306,7 @@ export class AppConfigService {
500: '#6a755e',
600: '#555d4c',
700: '#434a3d',
800: '#333930',
800: '#3d4438',
900: '#232824',
950: '#131614'
}
@@ -323,7 +323,7 @@ export class AppConfigService {
500: '#755e5e',
600: '#5d4c4c',
700: '#4a3d3d',
800: '#382f2f',
800: '#423838',
900: '#242020',
950: '#141212'
}
@@ -1,534 +0,0 @@
import {afterEach, 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 {AppSettingsService, PublicAppSettings} from './app-settings.service';
import {AppSettings} from '../model/app-settings.model';
import {AuthService} from './auth.service';
describe('AppSettingsService', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
const mockAppSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
komgaApiEnabled: false,
komgaGroupUnknown: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'TestProvider',
clientId: 'clientid',
issuerUri: 'https://issuer.example.com',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false},
ranobedb: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
ranobedbRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: {
epub: {enabled: false, maxFileSizeInMb: 0},
pdf: {enabled: false, maxFileSizeInMb: 0},
cbx: {enabled: false, maxFileSizeInMb: 0}
},
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false,
metadataProviderSpecificFields: {
asin: false,
amazonRating: false,
amazonReviewCount: false,
googleId: false,
goodreadsId: false,
goodreadsRating: false,
goodreadsReviewCount: false,
hardcoverId: false,
hardcoverBookId: false,
hardcoverRating: false,
hardcoverReviewCount: false,
comicvineId: false,
lubimyczytacId: false,
lubimyczytacRating: false,
ranobedbId: false,
ranobedbRating: false
}
};
const mockPublicSettings: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: mockAppSettings.oidcProviderDetails
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should fetch app settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toEqual(mockAppSettings);
expect(service['appSettingsSubject'].value).toEqual(mockAppSettings);
});
});
it('should handle error when fetching app settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchAppSettings']().subscribe({
error: (err: any) => {
expect(service['appSettingsSubject'].value).toBeNull();
expect(err).toBeInstanceOf(Error);
}
});
});
it('should fetch public settings and update subject', () => {
httpClientMock.get.mockReturnValue(of(mockPublicSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toEqual(mockPublicSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
});
it('should handle error when fetching public settings', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchPublicSettings']().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should sync public settings from app settings', () => {
service['publicAppSettingsSubject'].next(null);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should not update public settings if unchanged', () => {
service['publicAppSettingsSubject'].next(mockPublicSettings);
service['syncPublicSettings'](mockAppSettings);
expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings);
});
it('should save settings and update appSettingsSubject', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should fetch settings if current is null on save', () => {
httpClientMock.put.mockReturnValue(of(void 0));
httpClientMock.get.mockReturnValue(of(mockAppSettings));
service['appSettingsSubject'].next(null);
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe(() => {
expect(httpClientMock.get).toHaveBeenCalled();
});
});
it('should handle error on saveSettings', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(result => {
expect(result).toBeUndefined();
});
});
it('should toggle OIDC enabled and update state', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
service.toggleOidcEnabled(false).subscribe(() => {
expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false);
});
});
it('should call clearOIDCTokens when disabling OIDC', async () => {
httpClientMock.put.mockReturnValue(of(void 0));
service['appSettingsSubject'].next({...mockAppSettings});
await new Promise<void>(resolve => {
service.toggleOidcEnabled(false).subscribe(() => {
setTimeout(() => {
expect(authServiceMock.clearOIDCTokens).toHaveBeenCalled();
resolve();
}, 10);
});
});
});
it('should handle error on toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.toggleOidcEnabled(true).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
describe('AppSettingsService - API Contract Tests', () => {
let service: AppSettingsService;
let httpClientMock: any;
let authServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
put: vi.fn()
};
authServiceMock = {
clearOIDCTokens: vi.fn()
};
injectorMock = {
get: vi.fn().mockReturnValue(authServiceMock)
};
TestBed.configureTestingModule({
providers: [
AppSettingsService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock},
{provide: EnvironmentInjector, useValue: injectorMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService));
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('PublicAppSettings interface contract', () => {
it('should validate all required PublicAppSettings fields exist', () => {
const requiredFields: (keyof PublicAppSettings)[] = [
'oidcEnabled', 'remoteAuthEnabled', 'oidcProviderDetails'
];
const mockResponse: PublicAppSettings = {
oidcEnabled: true,
remoteAuthEnabled: false,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service['fetchPublicSettings']().subscribe(settings => {
requiredFields.forEach(field => {
expect(settings).toHaveProperty(field);
expect(settings[field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for fetchAppSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchAppSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/settings$/));
});
it('should call correct endpoint for fetchPublicSettings', () => {
httpClientMock.get.mockReturnValue(of({}));
service['fetchPublicSettings']().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/public-settings$/));
});
it('should call correct endpoint for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'oidcEnabled', value: true}]
);
});
it('should call correct endpoint for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(true).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/settings$/),
[{name: 'OIDC_ENABLED', value: true}]
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for saveSettings', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.saveSettings([{key: 'remoteAuthEnabled', newValue: false}]).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'remoteAuthEnabled', value: false}]
);
});
it('should send correct structure for toggleOidcEnabled', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.toggleOidcEnabled(false).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
[{name: 'OIDC_ENABLED', value: false}]
);
});
});
describe('Response type contract', () => {
it('should expect AppSettings from fetchAppSettings', () => {
const mockSettings: AppSettings = {
autoBookSearch: true,
similarBookRecommendation: false,
defaultMetadataRefreshOptions: {} as any,
libraryMetadataRefreshOptions: [],
uploadPattern: '',
opdsServerEnabled: false,
komgaApiEnabled: false,
komgaGroupUnknown: false,
remoteAuthEnabled: false,
oidcEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
},
oidcAutoProvisionDetails: {
enableAutoProvisioning: false,
defaultPermissions: [],
defaultLibraryIds: []
},
maxFileUploadSizeInMb: 0,
metadataProviderSettings: {
amazon: {enabled: false, cookie: '', domain: ''},
google: {enabled: false, language: ''},
goodReads: {enabled: false},
hardcover: {enabled: false, apiKey: ''},
comicvine: {enabled: false, apiKey: ''},
douban: {enabled: false},
lubimyczytac: {enabled: false},
ranobedb: {enabled: false}
},
metadataMatchWeights: {
title: 0,
subtitle: 0,
description: 0,
authors: 0,
publisher: 0,
publishedDate: 0,
seriesName: 0,
seriesNumber: 0,
seriesTotal: 0,
isbn13: 0,
isbn10: 0,
language: 0,
pageCount: 0,
categories: 0,
amazonRating: 0,
amazonReviewCount: 0,
goodreadsRating: 0,
goodreadsReviewCount: 0,
hardcoverRating: 0,
hardcoverReviewCount: 0,
doubanRating: 0,
doubanReviewCount: 0,
lubimyczytacRating: 0,
ranobedbRating: 0,
coverImage: 0
},
metadataPersistenceSettings: {
moveFilesToLibraryPattern: false,
saveToOriginalFile: {
epub: {enabled: false, maxFileSizeInMb: 0},
pdf: {enabled: false, maxFileSizeInMb: 0},
cbx: {enabled: false, maxFileSizeInMb: 0}
},
convertCbrCb7ToCbz: false
},
metadataPublicReviewsSettings: {
downloadEnabled: false,
autoDownloadEnabled: false,
providers: []
},
koboSettings: {
convertToKepub: false,
conversionLimitInMb: 0,
conversionImageCompressionPercentage: 0,
convertCbxToEpub: false,
conversionLimitInMbForCbx: 0,
forceEnableHyphenation: false
},
coverCroppingSettings: {
verticalCroppingEnabled: false,
horizontalCroppingEnabled: false,
aspectRatioThreshold: 0,
smartCroppingEnabled: false
},
metadataDownloadOnBookdrop: false,
telemetryEnabled: false,
metadataProviderSpecificFields: {
asin: false,
amazonRating: false,
amazonReviewCount: false,
googleId: false,
goodreadsId: false,
goodreadsRating: false,
goodreadsReviewCount: false,
hardcoverId: false,
hardcoverBookId: false,
hardcoverRating: false,
hardcoverReviewCount: false,
comicvineId: false,
lubimyczytacId: false,
lubimyczytacRating: false,
ranobedbId: false,
ranobedbRating: false
}
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchAppSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
it('should expect PublicAppSettings from fetchPublicSettings', () => {
const mockSettings: PublicAppSettings = {
oidcEnabled: false,
remoteAuthEnabled: true,
oidcProviderDetails: {
providerName: 'Provider',
clientId: 'id',
issuerUri: 'issuer',
claimMapping: {
username: 'username',
email: 'email',
name: 'name'
}
}
};
httpClientMock.get.mockReturnValue(of(mockSettings));
service['fetchPublicSettings']().subscribe(settings => {
expect(settings).toHaveProperty('oidcEnabled');
expect(settings).toHaveProperty('remoteAuthEnabled');
expect(settings).toHaveProperty('oidcProviderDetails');
});
});
});
});
@@ -0,0 +1,386 @@
import { inject, Injectable } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import {
ReadingSessionApiService,
CreateReadingSessionDto
} from './reading-session-api.service';
export interface AudiobookSession {
bookId: number;
bookFileId?: number;
sessionStartTime: Date;
totalListeningSeconds: number;
startPositionMs: number;
currentPositionMs: number;
trackIndex?: number;
playbackRate: number;
lastPlayStartTime?: Date;
}
@Injectable({
providedIn: 'root'
})
export class AudiobookSessionService {
private readonly apiService = inject(ReadingSessionApiService);
private currentSession: AudiobookSession | null = null;
private periodicSaveInterval: ReturnType<typeof setInterval> | null = null;
private readonly PERIODIC_SAVE_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
private readonly MIN_SESSION_DURATION_SECONDS = 30;
constructor() {
this.setupBrowserLifecycleListeners();
}
private setupBrowserLifecycleListeners(): void {
window.addEventListener('beforeunload', () => {
if (this.currentSession) {
this.endSessionSync();
}
});
// Note: We intentionally do NOT pause on visibility change
// Audiobooks play in the background
}
/**
* Start a new listening session when playback begins
*/
startSession(
bookId: number,
startPositionMs: number,
playbackRate: number = 1,
bookFileId?: number,
trackIndex?: number
): void {
// End any existing session first
if (this.currentSession) {
this.endSession();
}
this.currentSession = {
bookId,
bookFileId,
sessionStartTime: new Date(),
totalListeningSeconds: 0,
startPositionMs,
currentPositionMs: startPositionMs,
trackIndex,
playbackRate,
lastPlayStartTime: new Date()
};
this.log('Audiobook session started', {
bookId,
startPosition: this.formatMs(startPositionMs),
playbackRate
});
this.startPeriodicSave();
}
/**
* Called when playback is paused - accumulates listening time
*/
pauseSession(currentPositionMs: number): void {
if (!this.currentSession || !this.currentSession.lastPlayStartTime) {
return;
}
// Calculate listening time since last play
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
this.currentSession.currentPositionMs = currentPositionMs;
this.currentSession.lastPlayStartTime = undefined;
this.log('Audiobook session paused', {
addedSeconds: Math.round(adjustedDurationSeconds),
totalSeconds: Math.round(this.currentSession.totalListeningSeconds),
position: this.formatMs(currentPositionMs)
});
}
/**
* Called when playback resumes after pause
*/
resumeSession(currentPositionMs: number): void {
if (!this.currentSession) {
return;
}
this.currentSession.lastPlayStartTime = new Date();
this.currentSession.currentPositionMs = currentPositionMs;
this.log('Audiobook session resumed', {
position: this.formatMs(currentPositionMs)
});
}
/**
* Update current position (called during playback)
*/
updatePosition(currentPositionMs: number, trackIndex?: number): void {
if (!this.currentSession) {
return;
}
this.currentSession.currentPositionMs = currentPositionMs;
if (trackIndex !== undefined) {
this.currentSession.trackIndex = trackIndex;
}
}
/**
* Update playback rate
*/
updatePlaybackRate(rate: number): void {
if (!this.currentSession) {
return;
}
// If currently playing, accumulate time at old rate before changing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
this.currentSession.lastPlayStartTime = now;
}
this.currentSession.playbackRate = rate;
this.log('Playback rate changed', { rate });
}
/**
* End the session and send to backend
*/
endSession(currentPositionMs?: number): void {
if (!this.currentSession) {
return;
}
this.stopPeriodicSave();
// If still playing, accumulate final listening time
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
}
if (currentPositionMs !== undefined) {
this.currentSession.currentPositionMs = currentPositionMs;
}
const totalSeconds = Math.round(this.currentSession.totalListeningSeconds);
if (totalSeconds >= this.MIN_SESSION_DURATION_SECONDS) {
this.sendSessionToBackend(this.currentSession);
} else {
this.log('Session too short, discarding', { totalSeconds });
}
this.currentSession = null;
}
/**
* Check if a session is currently active
*/
isSessionActive(): boolean {
return this.currentSession !== null;
}
/**
* Check if currently in playing state (not paused)
*/
isPlaying(): boolean {
return this.currentSession?.lastPlayStartTime !== undefined;
}
/**
* Get current accumulated listening time in seconds
*/
getCurrentListeningTime(): number {
if (!this.currentSession) {
return 0;
}
let total = this.currentSession.totalListeningSeconds;
// Add time since last play start if currently playing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
total += (playDurationMs / 1000) * this.currentSession.playbackRate;
}
return Math.round(total);
}
private endSessionSync(): void {
if (!this.currentSession) {
return;
}
// Accumulate final listening time if playing
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
const adjustedDurationSeconds = (playDurationMs / 1000) * this.currentSession.playbackRate;
this.currentSession.totalListeningSeconds += adjustedDurationSeconds;
}
const totalSeconds = Math.round(this.currentSession.totalListeningSeconds);
if (totalSeconds < this.MIN_SESSION_DURATION_SECONDS) {
this.cleanup();
return;
}
const sessionData = this.buildSessionData(this.currentSession);
this.log('Audiobook session ended (sync)', sessionData);
const success = this.apiService.sendSessionBeacon(sessionData);
if (!success) {
this.logError('sendBeacon failed, request may not have been queued');
}
this.cleanup();
}
private startPeriodicSave(): void {
this.stopPeriodicSave();
this.periodicSaveInterval = setInterval(() => {
if (this.currentSession && this.currentSession.lastPlayStartTime) {
// Send intermediate session data
this.sendIntermediateSession();
}
}, this.PERIODIC_SAVE_INTERVAL_MS);
}
private stopPeriodicSave(): void {
if (this.periodicSaveInterval) {
clearInterval(this.periodicSaveInterval);
this.periodicSaveInterval = null;
}
}
private sendIntermediateSession(): void {
if (!this.currentSession) {
return;
}
// Calculate current total without modifying state
let totalSeconds = this.currentSession.totalListeningSeconds;
if (this.currentSession.lastPlayStartTime) {
const now = new Date();
const playDurationMs = now.getTime() - this.currentSession.lastPlayStartTime.getTime();
totalSeconds += (playDurationMs / 1000) * this.currentSession.playbackRate;
}
if (totalSeconds < this.MIN_SESSION_DURATION_SECONDS) {
return;
}
const sessionData = this.buildSessionData(this.currentSession, Math.round(totalSeconds));
this.log('Sending intermediate session', {
listeningSeconds: Math.round(totalSeconds)
});
this.apiService.createSession(sessionData).subscribe({
next: () => this.log('Intermediate session saved'),
error: (err: HttpErrorResponse) => this.logError('Failed to save intermediate session', err)
});
// Reset accumulated time after sending (to avoid double-counting)
// Keep lastPlayStartTime to continue tracking
this.currentSession.totalListeningSeconds = 0;
this.currentSession.lastPlayStartTime = new Date();
this.currentSession.startPositionMs = this.currentSession.currentPositionMs;
}
private sendSessionToBackend(session: AudiobookSession): void {
const sessionData = this.buildSessionData(session);
this.log('Audiobook session completed', sessionData);
this.apiService.createSession(sessionData).subscribe({
next: () => this.log('Session saved to backend'),
error: (err: HttpErrorResponse) => this.logError('Failed to save session', err)
});
}
private buildSessionData(session: AudiobookSession, overrideDuration?: number): CreateReadingSessionDto {
const durationSeconds = overrideDuration ?? Math.round(session.totalListeningSeconds);
const now = new Date();
// Calculate progress if we have position data
// Note: Progress calculation would need total duration from the component
// For now, we use position as location
return {
bookId: session.bookId,
bookType: 'AUDIOBOOK',
startTime: session.sessionStartTime.toISOString(),
endTime: now.toISOString(),
durationSeconds,
durationFormatted: this.formatDuration(durationSeconds),
startLocation: this.formatMs(session.startPositionMs),
endLocation: this.formatMs(session.currentPositionMs)
};
}
private formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`;
} else if (minutes > 0) {
return `${minutes}m ${secs}s`;
}
return `${secs}s`;
}
private formatMs(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
private cleanup(): void {
this.stopPeriodicSave();
this.currentSession = null;
}
private log(message: string, data?: unknown): void {
if (data) {
console.log(`[AudiobookSession] ${message}`, data);
} else {
console.log(`[AudiobookSession] ${message}`);
}
}
private logError(message: string, error?: unknown): void {
if (error) {
console.error(`[AudiobookSession] ${message}`, error);
} else {
console.error(`[AudiobookSession] ${message}`);
}
}
}
@@ -1,310 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of} from 'rxjs';
import {AuthService} from './auth.service';
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
import {Router} from '@angular/router';
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
import {RxStompService} from '../websocket/rx-stomp.service';
describe('AuthService', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {
getIdToken: vi.fn().mockReturnValue('oidc-token')
};
oAuthStorageMock = {
removeItem: vi.fn()
};
routerMock = {
navigate: vi.fn()
};
postLoginInitializerMock = {
initialize: vi.fn().mockReturnValue(of(void 0))
};
rxStompServiceMock = {
updateConfig: vi.fn(),
activate: vi.fn(),
deactivate: vi.fn()
};
injectorMock = {
get: vi.fn((token: any) => {
if (token === RxStompService) return rxStompServiceMock;
return undefined;
})
};
vi.stubGlobal('localStorage', {
getItem: vi.fn().mockReturnValue(null),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
// Patch inject() for Injector
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should save and get internal tokens', () => {
service.saveInternalTokens('access', 'refresh');
expect(localStorage.setItem).toHaveBeenCalledWith('accessToken_Internal', 'access');
expect(localStorage.setItem).toHaveBeenCalledWith('refreshToken_Internal', 'refresh');
expect(service.tokenSubject.value).toBe('access');
});
it('should get internal access and refresh tokens', () => {
(localStorage.getItem as any).mockImplementation((key: string) => key === 'accessToken_Internal' ? 'access' : 'refresh');
expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh');
});
it('should get OIDC access token', () => {
expect(service.getOidcAccessToken()).toBe('oidc-token');
});
it('should call internalLogin and save tokens', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call internalRefreshToken and save tokens', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.internalRefreshToken().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should call remoteLogin and save tokens', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const spy = vi.spyOn(service, 'saveInternalTokens');
service.remoteLogin().subscribe(res => {
expect(res.accessToken).toBe('a');
expect(spy).toHaveBeenCalledWith('a', 'r');
});
});
it('should clear OIDC tokens and navigate if no internal tokens', () => {
(localStorage.getItem as any).mockReturnValue(null);
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should not clear OIDC tokens if internal tokens exist', () => {
(localStorage.getItem as any).mockReturnValue('access');
service.clearOIDCTokens();
expect(oAuthStorageMock.removeItem).not.toHaveBeenCalled();
expect(routerMock.navigate).not.toHaveBeenCalled();
});
it('should logout and clear all tokens', () => {
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
routerMock.navigate.mockReturnValue(Promise.resolve(true));
service.logout();
expect(localStorage.removeItem).toHaveBeenCalledWith('accessToken_Internal');
expect(localStorage.removeItem).toHaveBeenCalledWith('refreshToken_Internal');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token');
expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token');
expect(rxStompServiceMock.deactivate).toHaveBeenCalled();
expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
});
it('should initialize websocket connection if token exists', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue('token');
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service['postLoginInitialized'] = false;
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).toHaveBeenCalled();
expect(rxStompServiceMock.activate).toHaveBeenCalled();
});
it('should not initialize websocket connection if no token', () => {
vi.spyOn(service, 'getOidcAccessToken').mockReturnValue(null);
vi.spyOn(service, 'getInternalAccessToken').mockReturnValue(null);
service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock);
service.initializeWebSocketConnection();
expect(rxStompServiceMock.updateConfig).not.toHaveBeenCalled();
expect(rxStompServiceMock.activate).not.toHaveBeenCalled();
});
it('should call postLoginInitializer only once', () => {
service['postLoginInitialized'] = false;
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalled();
service['handleSuccessfulAuth']();
expect(postLoginInitializerMock.initialize).toHaveBeenCalledTimes(1);
});
it('should get RxStompService from injector', () => {
service['rxStompService'] = undefined;
expect(service.getRxStompService()).toBe(rxStompServiceMock);
expect(service.getRxStompService()).toBe(rxStompServiceMock); // cached
});
});
describe('AuthService - API Contract Tests', () => {
let service: AuthService;
let httpClientMock: any;
let oAuthServiceMock: any;
let oAuthStorageMock: any;
let routerMock: any;
let postLoginInitializerMock: any;
let rxStompServiceMock: any;
let injectorMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
oAuthServiceMock = {getIdToken: vi.fn()};
oAuthStorageMock = {removeItem: vi.fn()};
routerMock = {navigate: vi.fn()};
postLoginInitializerMock = {initialize: vi.fn().mockReturnValue(of(void 0))};
rxStompServiceMock = {updateConfig: vi.fn(), activate: vi.fn(), deactivate: vi.fn()};
injectorMock = {get: vi.fn((token: any) => rxStompServiceMock)};
vi.stubGlobal('localStorage', {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn()
});
TestBed.configureTestingModule({
providers: [
AuthService,
{provide: HttpClient, useValue: httpClientMock},
{provide: OAuthService, useValue: oAuthServiceMock},
{provide: OAuthStorage, useValue: oAuthStorageMock},
{provide: Router, useValue: routerMock},
{provide: PostLoginInitializerService, useValue: postLoginInitializerMock},
{provide: RxStompService, useValue: rxStompServiceMock},
{provide: 'Injector', useValue: injectorMock}
]
});
(AuthService.prototype as any).injector = injectorMock;
service = TestBed.inject(AuthService);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/login$/),
{username: 'u', password: 'p'}
);
});
it('should call correct endpoint for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/refresh$/),
{refreshToken: 'refresh'}
);
});
it('should call correct endpoint for remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/remote$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
const payload = {username: 'user', password: 'pass'};
service.internalLogin(payload).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), payload);
});
it('should send correct structure for internalRefreshToken', () => {
(localStorage.getItem as any).mockReturnValue('refresh');
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), {refreshToken: 'refresh'});
});
});
describe('Response type contract', () => {
it('should expect token object from internalLogin', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.internalLogin({username: 'u', password: 'p'}).subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from remoteLogin', () => {
httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'}));
service.remoteLogin().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
expect(res).toHaveProperty('isDefaultPassword');
});
});
it('should expect token object from internalRefreshToken', () => {
httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'}));
service.internalRefreshToken().subscribe(res => {
expect(res).toHaveProperty('accessToken');
expect(res).toHaveProperty('refreshToken');
});
});
});
});
@@ -1,264 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {BookMarkService, BookMark, CreateBookMarkRequest, UpdateBookMarkRequest} from './book-mark.service';
describe('BookMarkService', () => {
let service: BookMarkService;
let httpClientMock: any;
const mockBookmark: BookMark = {
id: 1,
userId: 2,
bookId: 3,
cfi: 'epubcfi(/6/2[cover]!/6)',
title: 'Bookmark 1',
color: 'yellow',
notes: 'note',
priority: 1,
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
it('should get bookmarks for a book', () => {
httpClientMock.get.mockReturnValue(of([mockBookmark]));
service.getBookmarksForBook(3).subscribe(bookmarks => {
expect(bookmarks).toEqual([mockBookmark]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create a bookmark', () => {
httpClientMock.post.mockReturnValue(of(mockBookmark));
const req: CreateBookMarkRequest = {bookId: 3, cfi: 'epubcfi(/6/2[cover]!/6)', title: 'Bookmark 1'};
service.createBookmark(req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should update a bookmark', () => {
httpClientMock.put.mockReturnValue(of(mockBookmark));
const req: UpdateBookMarkRequest = {title: 'Updated', notes: 'Updated note'};
service.updateBookmark(1, req).subscribe(bm => {
expect(bm).toEqual(mockBookmark);
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), req);
});
});
it('should delete a bookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getBookmarksForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getBookmarksForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createBookmark error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createBookmark({bookId: 3, cfi: 'cfi'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle updateBookmark error', () => {
httpClientMock.put.mockReturnValue(throwError(() => new Error('fail')));
service.updateBookmark(1, {title: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteBookmark error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteBookmark(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookMarkService - API Contract Tests', () => {
let service: BookMarkService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookMarkService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookMarkService);
});
describe('BookMark interface contract', () => {
it('should validate all required BookMark fields exist', () => {
const requiredFields: (keyof BookMark)[] = [
'id', 'bookId', 'cfi', 'title', 'createdAt'
];
const mockResponse: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getBookmarksForBook(2).subscribe(bookmarks => {
requiredFields.forEach(field => {
expect(bookmarks[0]).toHaveProperty(field);
expect(bookmarks[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getBookmarksForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getBookmarksForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/bookmarks\/book\/5$/));
});
it('should call correct endpoint for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks$/),
req
);
});
it('should call correct endpoint for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't'};
service.updateBookmark(7, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/7$/),
req
);
});
it('should call correct endpoint for deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/bookmarks\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createBookmark', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'};
service.createBookmark(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
it('should send correct structure for updateBookmark', () => {
httpClientMock.put.mockReturnValue(of({}));
const req: UpdateBookMarkRequest = {title: 't', notes: 'n'};
service.updateBookmark(9, req).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookMark[] from getBookmarksForBook', () => {
const mockBookmarks: BookMark[] = [{
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockBookmarks));
service.getBookmarksForBook(2).subscribe(bookmarks => {
expect(Array.isArray(bookmarks)).toBe(true);
expect(bookmarks[0]).toHaveProperty('id');
expect(bookmarks[0]).toHaveProperty('bookId');
});
});
it('should expect BookMark from createBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockBookmark));
service.createBookmark({bookId: 2, cfi: 'cfi', title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect BookMark from updateBookmark', () => {
const mockBookmark: BookMark = {
id: 1,
bookId: 2,
cfi: 'cfi',
title: 't',
createdAt: '2024-01-01T00:00:00Z'
};
httpClientMock.put.mockReturnValue(of(mockBookmark));
service.updateBookmark(1, {title: 't'}).subscribe(bm => {
expect(bm).toHaveProperty('id');
expect(bm).toHaveProperty('bookId');
});
});
it('should expect void from deleteBookmark', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteBookmark(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -7,7 +7,9 @@ export interface BookMark {
id: number;
userId?: number;
bookId: number;
cfi: string;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title: string;
color?: string;
notes?: string;
@@ -18,7 +20,9 @@ export interface BookMark {
export interface CreateBookMarkRequest {
bookId: number;
cfi: string;
cfi?: string; // For EPUB bookmarks
positionMs?: number; // For audiobook bookmarks
trackIndex?: number; // For folder-based audiobooks
title?: string;
}
@@ -1,215 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {BookNote, BookNoteService, CreateBookNoteRequest} from './book-note.service';
describe('BookNoteService', () => {
let service: BookNoteService;
let httpClientMock: any;
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 'Note Title',
content: 'Note content',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
it('should get notes for a book', () => {
httpClientMock.get.mockReturnValue(of([mockNote]));
service.getNotesForBook(3).subscribe(notes => {
expect(notes).toEqual([mockNote]);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3'));
});
});
it('should create or update a note', () => {
httpClientMock.post.mockReturnValue(of(mockNote));
const req: CreateBookNoteRequest = {bookId: 3, title: 'Note Title', content: 'Note content'};
service.createOrUpdateNote(req).subscribe(note => {
expect(note).toEqual(mockNote);
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
it('should delete a note', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should handle getNotesForBook error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getNotesForBook(3).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle createOrUpdateNote error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createOrUpdateNote({bookId: 3, title: 'fail', content: 'fail'}).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
it('should handle deleteNote error', () => {
httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail')));
service.deleteNote(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
}
});
});
});
describe('BookNoteService - API Contract Tests', () => {
let service: BookNoteService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
delete: vi.fn()
};
TestBed.configureTestingModule({
providers: [
BookNoteService,
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(BookNoteService);
});
describe('BookNote interface contract', () => {
it('should validate all required BookNote fields exist', () => {
const requiredFields: (keyof BookNote)[] = [
'id', 'userId', 'bookId', 'title', 'content', 'createdAt', 'updatedAt'
];
const mockResponse: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getNotesForBook(3).subscribe(notes => {
requiredFields.forEach(field => {
expect(notes[0]).toHaveProperty(field);
expect(notes[0][field]).toBeDefined();
});
});
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getNotesForBook', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getNotesForBook(5).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/book-notes\/book\/5$/));
});
it('should call correct endpoint for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes$/),
req
);
});
it('should call correct endpoint for deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(8).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/book-notes\/8$/)
);
});
});
describe('Request payload contract', () => {
it('should send correct structure for createOrUpdateNote', () => {
httpClientMock.post.mockReturnValue(of({}));
const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'};
service.createOrUpdateNote(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req);
});
});
describe('Response type contract', () => {
it('should expect BookNote[] from getNotesForBook', () => {
const mockNotes: BookNote[] = [{
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockNotes));
service.getNotesForBook(3).subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('id');
expect(notes[0]).toHaveProperty('title');
});
});
it('should expect BookNote from createOrUpdateNote', () => {
const mockNote: BookNote = {
id: 1,
userId: 2,
bookId: 3,
title: 't',
content: 'c',
createdAt: '2024-01-01T00:00:00Z',
updatedAt: '2024-01-01T01:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockNote));
service.createOrUpdateNote({bookId: 2, title: 't', content: 'c'}).subscribe(note => {
expect(note).toHaveProperty('id');
expect(note).toHaveProperty('title');
});
});
it('should expect void from deleteNote', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteNote(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,317 +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} from 'rxjs';
import {CustomFontService} from './custom-font.service';
import {CustomFont, FontFormat} from '../model/custom-font.model';
import {AuthService} from './auth.service';
describe('CustomFontService', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
let fontsSet: any[];
let originalDocumentFonts: any;
const mockFont: CustomFont = {
id: 1,
fontName: 'TestFont',
originalFileName: 'testfont.ttf',
format: FontFormat.TTF,
fileSize: 1024,
uploadedAt: '2024-01-01T00:00:00Z'
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
(globalThis as any).FontFace = function (family: string, source: string, descriptors?: any) {
this.family = family;
this.source = source;
this.descriptors = descriptors;
this.load = vi.fn().mockResolvedValue(this);
};
// Store original and create mock fonts set
originalDocumentFonts = document.fonts;
fontsSet = [];
// Mock document.fonts
Object.defineProperty(document, 'fonts', {
value: {
add: vi.fn((font: any) => fontsSet.push(font)),
delete: vi.fn((font: any) => {
const idx = fontsSet.indexOf(font);
if (idx !== -1) fontsSet.splice(idx, 1);
}),
[Symbol.iterator]: function* () {
yield* fontsSet;
}
},
writable: true,
configurable: true
});
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
it('should initialize with empty fontsSubject', () => {
expect(service['fontsSubject'].value).toEqual([]);
});
it('should upload font and update cache', () => {
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'testfont.ttf');
service.uploadFont(file, 'TestFont').subscribe(font => {
expect(font).toEqual(mockFont);
expect(service['fontsSubject'].value).toContainEqual(mockFont);
});
});
it('should get user fonts and update cache', () => {
httpClientMock.get.mockReturnValue(of([mockFont]));
service.getUserFonts().subscribe(fonts => {
expect(fonts).toEqual([mockFont]);
expect(service['fontsSubject'].value).toEqual([mockFont]);
});
});
it('should delete font and update cache', () => {
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
expect(service['fontsSubject'].value).toEqual([]);
});
});
it('should get font URL', () => {
expect(service.getFontUrl(123)).toMatch(/\/api\/v1\/custom-fonts\/123\/file$/);
});
it('should append token to URL', () => {
const url = 'http://test.com/font.ttf';
expect(service.appendToken(url)).toContain('token=');
});
it('should mark font as loaded after loadFontFace', async () => {
await service.loadFontFace(mockFont);
expect(service.isFontLoaded(mockFont.fontName)).toBe(true);
const fontsArr = Array.from(document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(true);
});
it('should call removeFontFace on delete', () => {
const fontObj = new (globalThis as any).FontFace(mockFont.fontName, 'url(test.ttf)');
document.fonts.add(fontObj);
service['fontsSubject'].next([mockFont]);
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(mockFont.id).subscribe(() => {
const fontsArr = Array.from(document.fonts);
expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(false);
});
});
it('should handle loadAllFonts', async () => {
vi.spyOn(service, 'loadFontFace').mockResolvedValue(undefined);
await service.loadAllFonts([mockFont]);
expect(service.loadFontFace).toHaveBeenCalledWith(mockFont);
});
it('should return false for isFontLoaded if not loaded', () => {
expect(service.isFontLoaded('NotLoaded')).toBe(false);
});
});
describe('CustomFontService - API Contract Tests', () => {
let service: CustomFontService;
let httpClientMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
getOidcAccessToken: vi.fn().mockReturnValue('token'),
getInternalAccessToken: vi.fn().mockReturnValue(null)
};
TestBed.configureTestingModule({
providers: [
CustomFontService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService));
});
describe('CustomFont interface contract', () => {
it('should validate all required CustomFont fields exist', () => {
const requiredFields: (keyof CustomFont)[] = [
'id', 'fontName', 'originalFileName', 'format', 'fileSize', 'uploadedAt'
];
const mockResponse: CustomFont = {
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
};
httpClientMock.get.mockReturnValue(of([mockResponse]));
service.getUserFonts().subscribe(fonts => {
requiredFields.forEach(field => {
expect(fonts[0]).toHaveProperty(field);
expect(fonts[0][field]).toBeDefined();
});
});
});
it('should fail if API returns CustomFont without required id field', () => {
const invalidResponse = [{
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getUserFonts().subscribe(fonts => {
expect(fonts[0]).not.toHaveProperty('id');
});
});
});
describe('Enum value contract', () => {
it('should validate FontFormat enum values from API', () => {
const validValues = [FontFormat.TTF, FontFormat.OTF, FontFormat.WOFF, FontFormat.WOFF2];
validValues.forEach(value => {
expect(Object.values(FontFormat)).toContain(value);
});
expect(Object.keys(FontFormat)).toHaveLength(4);
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getUserFonts', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getUserFonts().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts$/));
});
it('should call correct endpoint for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/custom-fonts\/upload$/),
expect.any(FormData)
);
});
it('should call correct endpoint for deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(123).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts\/123$/));
});
it('should call getFontUrl with correct format', () => {
expect(service.getFontUrl(42)).toMatch(/\/api\/v1\/custom-fonts\/42\/file$/);
});
});
describe('Request payload contract', () => {
it('should send FormData with file and fontName for uploadFont', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file, 'Font').subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(true);
});
it('should send FormData with only file if fontName not provided', () => {
httpClientMock.post.mockReturnValue(of({}));
const file = new File(['dummy'], 'font.ttf');
service.uploadFont(file).subscribe();
const formData = httpClientMock.post.mock.calls[0][1];
expect(formData instanceof FormData).toBe(true);
expect(formData.has('file')).toBe(true);
expect(formData.has('fontName')).toBe(false);
});
});
describe('Response type contract', () => {
it('should expect CustomFont array from getUserFonts', () => {
const mockFonts: CustomFont[] = [{
id: 1,
fontName: 'Font',
originalFileName: 'font.ttf',
format: FontFormat.TTF,
fileSize: 1234,
uploadedAt: '2024-01-01T00:00:00Z'
}];
httpClientMock.get.mockReturnValue(of(mockFonts));
service.getUserFonts().subscribe(fonts => {
expect(Array.isArray(fonts)).toBe(true);
expect(fonts[0]).toHaveProperty('id');
expect(fonts[0]).toHaveProperty('fontName');
});
});
it('should expect CustomFont from uploadFont', () => {
const mockFont: CustomFont = {
id: 2,
fontName: 'Font2',
originalFileName: 'font2.ttf',
format: FontFormat.OTF,
fileSize: 2048,
uploadedAt: '2024-01-02T00:00:00Z'
};
httpClientMock.post.mockReturnValue(of(mockFont));
const file = new File(['dummy'], 'font2.ttf');
service.uploadFont(file, 'Font2').subscribe(font => {
expect(font).toHaveProperty('id');
expect(font).toHaveProperty('fontName');
expect(font).toHaveProperty('format');
});
});
it('should expect void from deleteFont', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteFont(1).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,174 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {DownloadProgressService} from './download-progress.service';
import {Subject, take} from 'rxjs';
describe('DownloadProgressService', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
it('should initialize with default state', () => {
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toEqual({
visible: false,
filename: '',
progress: 0,
loaded: 0,
total: 0
});
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should start a download and set state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(true);
expect(progress.filename).toBe('file.pdf');
expect(progress.progress).toBe(0);
expect(progress.cancelSubject).toBe(cancelSubject);
});
expect(service.isDownloadInProgress()).toBe(true);
});
it('should update progress and throttle updates', async () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
// First update should be immediate
service.updateProgress(50, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(50);
expect(progress.loaded).toBe(50);
expect(progress.total).toBe(100);
});
// Throttled update (simulate time)
vi.useFakeTimers();
service.updateProgress(60, 100);
// Should not emit immediately
let emitted = false;
service.downloadProgress$.subscribe(progress => {
if (progress.loaded === 60) emitted = true;
});
vi.advanceTimersByTime(100);
expect(emitted).toBe(true);
vi.useRealTimers();
});
it('should immediately update when progress is 100', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(100, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
expect(progress.loaded).toBe(100);
expect(progress.total).toBe(100);
});
});
it('should complete download and reset state', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.visible).toBe(false);
expect(progress.filename).toBe('');
expect(progress.progress).toBe(0);
});
expect(service.isDownloadInProgress()).toBe(false);
});
it('should cancel download and call cancelSubject', () => {
const cancelSubject = new Subject<void>();
const nextSpy = vi.fn();
const completeSpy = vi.fn();
cancelSubject.subscribe({next: nextSpy, complete: completeSpy});
service.startDownload('file.pdf', cancelSubject);
service.cancelDownload();
expect(nextSpy).toHaveBeenCalled();
expect(completeSpy).toHaveBeenCalled();
expect(service.isDownloadInProgress()).toBe(false);
});
});
describe('DownloadProgressService - API Contract Tests', () => {
let service: DownloadProgressService;
beforeEach(() => {
service = new DownloadProgressService();
});
describe('DownloadProgress interface contract', () => {
it('should have all required fields', () => {
const cancelSubject = new Subject<void>();
service.startDownload('test.txt', cancelSubject);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress).toHaveProperty('visible');
expect(progress).toHaveProperty('filename');
expect(progress).toHaveProperty('progress');
expect(progress).toHaveProperty('loaded');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('cancelSubject');
});
});
it('should allow cancelSubject to be undefined after complete', () => {
service.completeDownload();
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.cancelSubject).toBeUndefined();
});
});
});
describe('Behavior contract', () => {
it('should emit correct progress values', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(25, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(25);
expect(progress.loaded).toBe(25);
expect(progress.total).toBe(100);
});
});
it('should not exceed 100% progress', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(150, 100);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(100);
});
});
it('should set progress to 0 if total is 0', () => {
const cancelSubject = new Subject<void>();
service.startDownload('file.pdf', cancelSubject);
service.updateProgress(50, 0);
service.downloadProgress$.pipe(take(1)).subscribe(progress => {
expect(progress.progress).toBe(0);
});
});
});
describe('API contract', () => {
it('should expose downloadProgress$ as observable', () => {
expect(typeof service.downloadProgress$.subscribe).toBe('function');
});
it('should expose isDownloadInProgress as boolean', () => {
expect(typeof service.isDownloadInProgress()).toBe('boolean');
});
it('should expose startDownload, updateProgress, completeDownload, cancelDownload', () => {
expect(typeof service.startDownload).toBe('function');
expect(typeof service.updateProgress).toBe('function');
expect(typeof service.completeDownload).toBe('function');
expect(typeof service.cancelDownload).toBe('function');
});
});
});
@@ -7,6 +7,7 @@ export interface DownloadProgress {
progress: number;
loaded: number;
total: number;
preparing: boolean;
cancelSubject?: Subject<void>;
}
@@ -19,7 +20,8 @@ export class DownloadProgressService {
filename: '',
progress: 0,
loaded: 0,
total: 0
total: 0,
preparing: false
});
private lastUpdateTime = 0;
@@ -33,7 +35,7 @@ export class DownloadProgressService {
return this.downloadProgressSubject.value.visible;
}
startDownload(filename: string, cancelSubject: Subject<void>): void {
startDownload(filename: string, cancelSubject: Subject<void>, preparing: boolean = false): void {
this.lastUpdateTime = 0;
this.pendingUpdate = null;
if (this.throttleTimer) {
@@ -47,6 +49,7 @@ export class DownloadProgressService {
progress: 0,
loaded: 0,
total: 0,
preparing,
cancelSubject
});
}
@@ -62,6 +65,7 @@ export class DownloadProgressService {
progress,
loaded,
total,
preparing: false, // No longer preparing once we have progress
cancelSubject: current.cancelSubject
};
@@ -114,7 +118,8 @@ export class DownloadProgressService {
filename: '',
progress: 0,
loaded: 0,
total: 0
total: 0,
preparing: false
});
}
@@ -1,197 +0,0 @@
import {beforeEach, describe, expect, it, vi, afterEach} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http';
import {of, Subject} from 'rxjs';
import {FileDownloadService} from './file-download.service';
import {DownloadProgressService} from './download-progress.service';
import {MessageService} from 'primeng/api';
describe('FileDownloadService', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
it('should trigger download and handle progress and completion', () => {
const events = [
{type: HttpEventType.DownloadProgress, loaded: 50, total: 100},
{
type: HttpEventType.Response,
body: new Blob(['test']),
headers: new HttpHeaders(),
clone: () => this,
status: 200,
statusText: 'OK',
url: '',
ok: true
}
];
httpClientMock.get.mockReturnValue(of(...events));
// Mock DOM for download
const link = document.createElement('a');
vi.spyOn(link, 'click').mockImplementation(() => {});
vi.spyOn(document, 'createElement').mockReturnValue(link);
vi.spyOn(document.body, 'appendChild').mockImplementation(() => link);
vi.spyOn(document.body, 'removeChild').mockImplementation(() => link);
vi.spyOn(document.body, 'contains').mockReturnValue(true);
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:url');
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
service.downloadFile('/api/file', 'file.txt');
expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'}));
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject));
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100);
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
it('should extract filename from Content-Disposition header', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''test%20file.txt"});
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('test file.txt');
});
it('should fallback to default filename if Content-Disposition is missing', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
const filename = (service as any).extractFilenameFromResponse(response, 'default.txt');
expect(filename).toBe('default.txt');
});
it('should throw if no file content received', () => {
const response = new HttpResponse({body: undefined, headers: new HttpHeaders()});
expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received');
});
});
describe('FileDownloadService - API Contract Tests', () => {
let service: FileDownloadService;
let httpClientMock: any;
let downloadProgressServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
downloadProgressServiceMock = {
isDownloadInProgress: vi.fn().mockReturnValue(false),
startDownload: vi.fn(),
updateProgress: vi.fn(),
completeDownload: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileDownloadService,
{provide: HttpClient, useValue: httpClientMock},
{provide: DownloadProgressService, useValue: downloadProgressServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService));
vi.useFakeTimers();
});
afterEach(() => {
vi.runAllTimers();
vi.useRealTimers();
});
describe('API contract', () => {
it('should expose downloadFile as a function', () => {
expect(typeof service.downloadFile).toBe('function');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint and options for downloadFile', () => {
httpClientMock.get.mockReturnValue(of());
service.downloadFile('/api/file', 'file.txt');
expect(httpClientMock.get).toHaveBeenCalledWith(
'/api/file',
expect.objectContaining({
responseType: 'blob',
observe: 'events',
reportProgress: true
})
);
});
});
describe('Request/Response contract', () => {
it('should expect Blob in HttpResponse', () => {
const headers = new HttpHeaders();
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'file.txt')).toBe('file.txt');
});
it('should handle Content-Disposition with encoded filename', () => {
const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''encoded%20file.pdf"});
const response = new HttpResponse({body: new Blob(['test']), headers});
expect((service as any).extractFilenameFromResponse(response, 'fallback.pdf')).toBe('encoded file.pdf');
});
});
describe('Behavior contract', () => {
it('should call startDownload and updateProgress on DownloadProgressService', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20}));
service.downloadFile('/api/file', 'file.txt');
expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled();
expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20);
});
it('should call completeDownload on finalize', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt');
expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled();
});
it('should show success message on download complete', () => {
httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true}));
service.downloadFile('/api/file', 'file.txt');
expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'}));
});
});
});
@@ -16,6 +16,9 @@ export class FileDownloadService {
downloadFile(url: string, defaultFilename: string): void {
const cancelSubject = new Subject<void>();
// Show preparing state immediately
this.downloadProgressService.startDownload(defaultFilename, cancelSubject, true);
this.initiateDownload(url)
.pipe(
takeUntil(cancelSubject),
@@ -55,9 +58,7 @@ export class FileDownloadService {
cancelSubject: Subject<void>
): void {
if (event.total) {
if (!this.downloadProgressService.isDownloadInProgress()) {
this.downloadProgressService.startDownload(defaultFilename, cancelSubject);
}
// Download already started with preparing state, just update progress
this.downloadProgressService.updateProgress(event.loaded, event.total);
}
}
@@ -1,139 +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 {FileMoveRequest, FileOperationsService} from './file-operations.service';
describe('FileOperationsService', () => {
let service: FileOperationsService;
let httpClientMock: any;
const mockRequest: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
it('should move files and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.moveFiles(mockRequest).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
mockRequest
);
});
});
it('should handle move files error', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.moveFiles(mockRequest).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('FileOperationsService - API Contract Tests', () => {
let service: FileOperationsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
FileOperationsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService));
});
describe('FileMoveRequest interface contract', () => {
it('should have required fields', () => {
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
expect(req).toHaveProperty('bookIds');
expect(req).toHaveProperty('moves');
expect(Array.isArray(req.bookIds)).toBe(true);
expect(Array.isArray(req.moves)).toBe(true);
expect(req.moves[0]).toHaveProperty('bookId');
expect(req.moves[0]).toHaveProperty('targetLibraryId');
expect(req.moves[0]).toHaveProperty('targetLibraryPathId');
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/files\/move$/),
req
);
});
});
describe('Request payload contract', () => {
it('should send FileMoveRequest with correct structure', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1, 2],
moves: [
{bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100},
{bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200}
]
};
service.moveFiles(req).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
req
);
});
});
describe('Response type contract', () => {
it('should expect void from moveFiles', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const req: FileMoveRequest = {
bookIds: [1],
moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}]
};
service.moveFiles(req).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,98 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of, Subject, take} from 'rxjs';
import {IconPickerService, IconSelection} from './icon-picker.service';
import {DialogLauncherService} from '../services/dialog-launcher.service';
describe('IconPickerService', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
it('should open icon picker dialog and return selection observable', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-book'};
const subject = new Subject<IconSelection>();
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: subject.asObservable()});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
subject.next(selection);
expect(result).toEqual(selection);
});
it('should call openIconPickerDialog on open()', () => {
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of({type: 'CUSTOM_SVG', value: '<svg></svg>'})});
service.open().pipe(take(1)).subscribe();
expect(dialogLauncherServiceMock.openIconPickerDialog).toHaveBeenCalled();
});
});
describe('IconPickerService - API Contract Tests', () => {
let service: IconPickerService;
let dialogLauncherServiceMock: any;
beforeEach(() => {
dialogLauncherServiceMock = {
openIconPickerDialog: vi.fn()
};
TestBed.configureTestingModule({
providers: [
IconPickerService,
{provide: DialogLauncherService, useValue: dialogLauncherServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService));
});
describe('IconSelection interface contract', () => {
it('should have required fields', () => {
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(selection).toHaveProperty('type');
expect(selection).toHaveProperty('value');
expect(typeof selection.type).toBe('string');
expect(typeof selection.value).toBe('string');
});
it('should only allow valid type values', () => {
const validTypes = ['PRIME_NG', 'CUSTOM_SVG'];
const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'};
expect(validTypes).toContain(selection.type);
});
});
describe('API contract', () => {
it('should expose open as a function', () => {
expect(typeof service.open).toBe('function');
});
it('should return Observable<IconSelection> from open()', () => {
const selection: IconSelection = {type: 'CUSTOM_SVG', value: '<svg></svg>'};
dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of(selection)});
let result: IconSelection | undefined;
service.open().pipe(take(1)).subscribe(sel => {
result = sel;
});
expect(result).toEqual(selection);
});
});
});
@@ -1,111 +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 {MetadataMatchWeightsService} from './metadata-match-weights.service';
import {API_CONFIG} from '../../core/config/api-config';
describe('MetadataMatchWeightsService', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataMatchWeightsService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should call recalculateAll and return void', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
it('should handle error from recalculateAll', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.recalculateAll().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('MetadataMatchWeightsService - API Contract Tests', () => {
let service: MetadataMatchWeightsService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn()
};
TestBed.configureTestingModule({
providers: [
MetadataMatchWeightsService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(MetadataMatchWeightsService));
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
`${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`,
{}
);
});
});
describe('Request payload contract', () => {
it('should send empty object as payload for recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.any(String),
{}
);
});
});
describe('Response type contract', () => {
it('should expect void from recalculateAll', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.recalculateAll().subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -1,241 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {of} from 'rxjs';
import {MetadataProgressService} from './metadata-progress.service';
import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../features/book/service/metadata-task';
import {UserService} from '../../features/settings/user-management/user.service';
describe('MetadataProgressService', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
const mockUserState = {
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
};
const mockTasks: MetadataBatchProgressNotification[] = [
{taskId: '1', completed: 10, total: 100, message: '', status: MetadataBatchStatus.IN_PROGRESS, review: false},
{taskId: '2', completed: 100, total: 100, message: '', status: MetadataBatchStatus.COMPLETED, review: false}
];
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of(mockTasks))
};
userServiceMock = {
userState$: of(mockUserState)
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should initialize and fetch active tasks if user has permissions', () => {
expect(metadataTaskServiceMock.getActiveTasks).toHaveBeenCalled();
});
it('should not fetch active tasks if user has no permissions', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
it('should handle incoming progress and update state', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '3',
completed: 50,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let update: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => update = val);
service.handleIncomingProgress(progress);
expect(update).toEqual(progress);
expect(service.getActiveTasks()['3']).toEqual(progress);
sub.unsubscribe();
});
it('should clear task from active tasks', () => {
const progress: MetadataBatchProgressNotification = {
taskId: '4',
completed: 20,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
service.handleIncomingProgress(progress);
expect(service.getActiveTasks()['4']).toBeDefined();
service.clearTask('4');
expect(service.getActiveTasks()['4']).toBeUndefined();
});
it('should complete all subjects on destroy', () => {
const spy = vi.spyOn(service['progressUpdatesSubject'], 'complete');
service.ngOnDestroy();
expect(spy).toHaveBeenCalled();
});
});
describe('MetadataProgressService - API Contract Tests', () => {
let service: MetadataProgressService;
let metadataTaskServiceMock: any;
let userServiceMock: any;
beforeEach(() => {
metadataTaskServiceMock = {
getActiveTasks: vi.fn().mockReturnValue(of([]))
};
userServiceMock = {
userState$: of({
user: {
permissions: {
admin: true,
canEditMetadata: true
}
}
})
};
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(MetadataProgressService)
);
});
describe('MetadataBatchProgressNotification contract', () => {
it('should require taskId, completed, total, message, status, and review fields', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'abc',
completed: 42,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
expect(progress).toHaveProperty('taskId');
expect(progress).toHaveProperty('completed');
expect(progress).toHaveProperty('total');
expect(progress).toHaveProperty('message');
expect(progress).toHaveProperty('status');
expect(progress).toHaveProperty('review');
});
});
describe('Active tasks structure', () => {
it('should return an object with taskId keys and progress notification values', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'xyz',
completed: 99,
total: 100,
message: '',
status: MetadataBatchStatus.COMPLETED,
review: false
};
service.handleIncomingProgress(progress);
const active = service.getActiveTasks();
expect(active).toHaveProperty('xyz');
expect(active['xyz']).toEqual(progress);
});
});
describe('Observable contract', () => {
it('should emit progress updates on progressUpdates$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'emit',
completed: 1,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: MetadataBatchProgressNotification | undefined;
const sub = service.progressUpdates$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted).toEqual(progress);
sub.unsubscribe();
});
it('should emit active tasks on activeTasks$', () => {
const progress: MetadataBatchProgressNotification = {
taskId: 'active',
completed: 2,
total: 100,
message: '',
status: MetadataBatchStatus.IN_PROGRESS,
review: false
};
let emitted: { [taskId: string]: MetadataBatchProgressNotification } | undefined;
const sub = service.activeTasks$.subscribe(val => {
emitted = val;
});
service.handleIncomingProgress(progress);
expect(emitted && emitted['active']).toEqual(progress);
sub.unsubscribe();
});
});
describe('Permissions contract', () => {
it('should only fetch tasks if user has admin or canEditMetadata', () => {
userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}});
metadataTaskServiceMock.getActiveTasks.mockClear();
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
MetadataProgressService,
{provide: MetadataTaskService, useValue: metadataTaskServiceMock},
{provide: UserService, useValue: userServiceMock}
]
});
TestBed.inject(MetadataProgressService);
expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled();
});
});
});
@@ -1,84 +0,0 @@
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {Title} from '@angular/platform-browser';
import {PageTitleService} from './page-title.service';
import {Book, BookType} from '../../features/book/model/book.model';
describe('PageTitleService', () => {
let service: PageTitleService;
let titleService: Title;
let setTitleMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
setTitleMock = vi.fn();
TestBed.configureTestingModule({
providers: [
PageTitleService,
{ provide: Title, useValue: { setTitle: setTitleMock } }
]
});
service = TestBed.inject(PageTitleService);
titleService = TestBed.inject(Title);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should set page title with setPageTitle', () => {
service.setPageTitle('Dashboard');
expect(setTitleMock).toHaveBeenCalledWith('Dashboard - BookLore');
});
it('should set book page title with all fields', () => {
const book: Book = {
id: 1,
bookType: 'PDF' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.pdf',
metadata: {
bookId: 1,
title: 'Book Title',
seriesName: 'Series',
authors: ['Author1', 'Author2']
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (Series series) - by Author1 and Author2 (PDF) - BookLore'
);
});
it('should set book page title without series and authors', () => {
const book: Book = {
id: 1,
bookType: 'EPUB' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.epub',
metadata: {
bookId: 1,
title: 'Book Title'
}
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/Book Title (EPUB) - BookLore'
);
});
it('should set book page title with fallback to fileName', () => {
const book: Book = {
id: 1,
bookType: 'CBX' as BookType,
libraryId: 2,
libraryName: 'Lib',
fileName: 'file.cbx'
};
service.setBookPageTitle(book);
expect(setTitleMock).toHaveBeenCalledWith(
'Lib/file.cbx (CBX) - BookLore'
);
});
});
@@ -13,7 +13,7 @@ export class PageTitleService {
`${book.libraryName}/${book.metadata?.title || book.fileName}`,
book.metadata?.seriesName ? `(${book.metadata.seriesName} series)` : false,
book.metadata?.authors?.length ? `- by ${new Intl.ListFormat('en').format(book.metadata?.authors)}` : false,
`(${book.bookType})`
`(${book.primaryFile?.bookType})`
].filter(part => part);
this.setPageTitle(title.join(' '));
@@ -1,252 +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 {CreateReadingSessionDto, PageableResponse, ReadingSessionApiService, ReadingSessionResponse} from './reading-session-api.service';
import {BookType} from '../../features/book/model/book.model';
describe('ReadingSessionApiService', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
const BASE_URL = '/api/v1/reading-sessions';
const mockSessionDto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF' as BookType,
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s',
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end'
};
const mockPageableResponse: PageableResponse<ReadingSessionResponse> = {
content: [{
id: 1,
bookId: 1,
bookTitle: 'Book',
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
startProgress: 0,
endProgress: 10,
progressDelta: 10,
startLocation: 'start',
endLocation: 'end',
createdAt: '2024-01-01T00:10:01Z'
}],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 1,
last: true,
totalPages: 1,
numberOfElements: 1,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: false
};
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call POST to createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
service.createSession(mockSessionDto).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
mockSessionDto
);
});
});
it('should call GET to getSessionsByBookId with correct params', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(1, 2, 10).subscribe(resp => {
expect(resp).toEqual(mockPageableResponse);
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringContaining(`${BASE_URL}/book/1`),
expect.objectContaining({
params: expect.any(HttpParams)
})
);
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('2');
expect(params.get('size')).toBe('10');
});
});
it('should default to page=0 and size=5 if not provided', () => {
httpClientMock.get.mockReturnValue(of(mockPageableResponse));
service.getSessionsByBookId(2).subscribe();
const params = httpClientMock.get.mock.calls[0][1].params;
expect(params.get('page')).toBe('0');
expect(params.get('size')).toBe('5');
});
it('should handle error in createSession', () => {
httpClientMock.post.mockReturnValue(throwError(() => new Error('fail')));
service.createSession(mockSessionDto).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle error in getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getSessionsByBookId(1).subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should send beacon successfully', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
vi.stubGlobal('navigator', {sendBeacon: sendBeaconMock});
const result = service.sendSessionBeacon(mockSessionDto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringContaining(BASE_URL),
expect.any(Blob)
);
expect(result).toBe(true);
});
it('should return false if sendBeacon throws', () => {
vi.stubGlobal('navigator', {
sendBeacon: vi.fn().mockImplementation(() => {
throw new Error('fail');
})
});
const result = service.sendSessionBeacon(mockSessionDto);
expect(result).toBe(false);
});
});
describe('ReadingSessionApiService - API Contract Tests', () => {
let service: ReadingSessionApiService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
post: vi.fn(),
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
ReadingSessionApiService,
{provide: HttpClient, useValue: httpClientMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService));
});
it('should call correct endpoint for createSession', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.createSession(dto).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
dto
);
});
it('should call correct endpoint for getSessionsByBookId', () => {
httpClientMock.get.mockReturnValue(of({content: []}));
service.getSessionsByBookId(123).subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions\/book\/123$/),
expect.objectContaining({params: expect.any(HttpParams)})
);
});
it('should send beacon to correct endpoint', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
vi.stubGlobal('navigator', {sendBeacon: sendBeaconMock});
const dto: CreateReadingSessionDto = {
bookId: 1,
bookType: 'PDF',
startTime: '2024-01-01T00:00:00Z',
endTime: '2024-01-01T00:10:00Z',
durationSeconds: 600,
durationFormatted: '10m 0s'
};
service.sendSessionBeacon(dto);
expect(sendBeaconMock).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/reading-sessions$/),
expect.any(Blob)
);
});
it('should expect PageableResponse<ReadingSessionResponse> from getSessionsByBookId', () => {
const mockResponse: PageableResponse<ReadingSessionResponse> = {
content: [],
pageable: {
pageNumber: 0,
pageSize: 5,
sort: {empty: true, sorted: false, unsorted: true},
offset: 0,
paged: true,
unpaged: false
},
totalElements: 0,
last: true,
totalPages: 1,
numberOfElements: 0,
first: true,
size: 5,
number: 0,
sort: {empty: true, sorted: false, unsorted: true},
empty: true
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getSessionsByBookId(1).subscribe(resp => {
expect(resp).toHaveProperty('content');
expect(Array.isArray(resp.content)).toBe(true);
expect(resp).toHaveProperty('totalElements');
});
});
});
@@ -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 {of, throwError} from 'rxjs';
import {SettingsHelperService} from './settings-helper.service';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
describe('SettingsHelperService', () => {
let service: SettingsHelperService;
let appSettingsServiceMock: any;
let messageServiceMock: any;
beforeEach(() => {
appSettingsServiceMock = {
saveSettings: vi.fn()
};
messageServiceMock = {
add: vi.fn()
};
TestBed.configureTestingModule({
providers: [
SettingsHelperService,
{provide: AppSettingsService, useValue: appSettingsServiceMock},
{provide: MessageService, useValue: messageServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(SettingsHelperService));
});
it('should call saveSettings and show success message on success', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(of(void 0));
service.saveSetting('theme', 'dark').subscribe(result => {
expect(result).toBeUndefined();
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Settings Saved',
detail: 'The settings were successfully saved!'
});
});
});
it('should call saveSettings and show error message on error', () => {
appSettingsServiceMock.saveSettings.mockReturnValue(throwError(() => new Error('fail')));
service.saveSetting('theme', 'light').subscribe({
error: (err: any) => {
expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'light'}]);
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'error',
summary: 'Error',
detail: 'There was an error saving the settings.'
});
expect(err).toBeInstanceOf(Error);
}
});
});
it('should show custom message via showMessage', () => {
service.showMessage('success', 'Yay', 'It worked!');
expect(messageServiceMock.add).toHaveBeenCalledWith({
severity: 'success',
summary: 'Yay',
detail: 'It worked!'
});
});
});
@@ -1,362 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {UrlHelperService} from './url-helper.service';
import {AuthService} from './auth.service';
import {BookService} from '../../features/book/service/book.service';
import {Router, UrlTree} from '@angular/router';
import {Book} from '../../features/book/model/book.model';
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
describe('UrlHelperService', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
describe('Token handling', () => {
it('should append token from OIDC', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token');
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=oidc-token');
});
it('should append token from internal', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue('internal-token');
const url = (service as any).appendToken('http://test');
expect(url).toContain('token=internal-token');
});
it('should not append token if none present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should append token with correct separator', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect((service as any).appendToken('http://a')).toBe('http://a?token=tok');
expect((service as any).appendToken('http://a?x=1')).toBe('http://a?x=1&token=tok');
});
it('should handle empty string token gracefully', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('');
authServiceMock.getInternalAccessToken.mockReturnValue('');
const url = (service as any).appendToken('http://test');
expect(url).toBe('http://test');
});
it('should handle undefined url in appendToken', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(() => (service as any).appendToken(undefined)).toThrow();
});
});
describe('getThumbnailUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 1, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, 'v123');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?v123.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(3);
expect(url).toMatch(/\/api\/v1\/media\/book\/3\/thumbnail\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 1} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(1);
expect(url).toMatch(/\/api\/v1\/media\/book\/1\/thumbnail\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 1, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url');
const url = service.getThumbnailUrl(1);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl(2, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?token=tok/);
});
});
describe('getThumbnailUrl1', () => {
it('should always use API url and append token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4, 'v456');
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?v456.*token=tok/);
});
it('should handle undefined coverUpdatedOn', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getThumbnailUrl1(4);
expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?token=tok/);
});
});
describe('getCoverUrl', () => {
it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => {
const book: Book = {id: 5, metadata: {title: 'T', authors: ['A']}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should use API url if coverUpdatedOn present', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, 'v789');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?v789.*token=tok/);
});
it('should use API url if no book in state', () => {
bookServiceMock.getBookByIdFromState.mockReturnValue(undefined);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(7);
expect(url).toMatch(/\/api\/v1\/media\/book\/7\/cover\?token=tok/);
});
it('should handle book with no metadata', () => {
const book: Book = {id: 5} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(5);
expect(url).toMatch(/\/api\/v1\/media\/book\/5\/cover\?token=tok/);
});
it('should handle book with empty metadata', () => {
const book: Book = {id: 5, metadata: {}} as any;
bookServiceMock.getBookByIdFromState.mockReturnValue(book);
const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2');
const url = service.getCoverUrl(5);
expect(genSpy).toHaveBeenCalled();
expect(url).toBe('cover-url2');
genSpy.mockRestore();
});
it('should handle coverUpdatedOn with empty string', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getCoverUrl(6, '');
expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?token=tok/);
});
});
describe('getBackupCoverUrl', () => {
it('should return backup cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBackupCoverUrl(8);
expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover$/);
});
});
describe('getBookdropCoverUrl', () => {
it('should return bookdrop cover url with token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover\?token=tok/);
});
it('should handle missing token', () => {
authServiceMock.getOidcAccessToken.mockReturnValue(null);
authServiceMock.getInternalAccessToken.mockReturnValue(null);
const url = service.getBookdropCoverUrl(9);
expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover$/);
});
});
describe('getBookUrl', () => {
it('should call router.createUrlTree with correct args', () => {
const book: Book = {id: 10} as any;
routerMock.createUrlTree.mockReturnValue('url-tree');
const urlTree = service.getBookUrl(book);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', 10], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
it('should handle book with undefined id', () => {
routerMock.createUrlTree.mockReturnValue('url-tree');
const minimalBook = {
id: undefined,
bookType: undefined,
libraryId: undefined,
libraryName: undefined
} as any;
const urlTree = service.getBookUrl(minimalBook);
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', undefined], {queryParams: {tab: 'view'}});
expect(urlTree).toBe('url-tree');
});
});
describe('filterBooksBy', () => {
it('should route to /series if filterKey is series', () => {
routerMock.createUrlTree.mockReturnValue('series-url');
const urlTree = service.filterBooksBy('series', 'My Series');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/series', encodeURIComponent('My Series')]);
expect(urlTree).toBe('series-url');
});
it('should route to /all-books with correct queryParams for other filters', () => {
routerMock.createUrlTree.mockReturnValue('all-books-url');
const urlTree = service.filterBooksBy('author', 'Author Name');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
{
queryParams: {
view: 'grid',
sort: 'title',
direction: 'asc',
sidebar: true,
filter: 'author:' + encodeURIComponent('Author Name')
}
}
);
expect(urlTree).toBe('all-books-url');
});
it('should handle empty filterValue', () => {
routerMock.createUrlTree.mockReturnValue('empty-filter-url');
const urlTree = service.filterBooksBy('author', '');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:'
})
})
);
expect(urlTree).toBe('empty-filter-url');
});
it('should handle empty filterKey', () => {
routerMock.createUrlTree.mockReturnValue('empty-key-url');
const urlTree = service.filterBooksBy('', 'SomeValue');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: ':' + encodeURIComponent('SomeValue')
})
})
);
expect(urlTree).toBe('empty-key-url');
});
});
});
describe('UrlHelperService - API Contract Tests', () => {
let service: UrlHelperService;
let authServiceMock: any;
let bookServiceMock: any;
let routerMock: any;
beforeEach(() => {
authServiceMock = {
getOidcAccessToken: vi.fn(),
getInternalAccessToken: vi.fn()
};
bookServiceMock = {
getBookByIdFromState: vi.fn()
};
routerMock = {
createUrlTree: vi.fn()
};
TestBed.configureTestingModule({
providers: [
UrlHelperService,
{provide: AuthService, useValue: authServiceMock},
{provide: BookService, useValue: bookServiceMock},
{provide: Router, useValue: routerMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService));
});
it('should generate correct API endpoints for covers and thumbnails', () => {
authServiceMock.getOidcAccessToken.mockReturnValue('tok');
expect(service.getThumbnailUrl1(11)).toMatch(/\/api\/v1\/media\/book\/11\/thumbnail\?token=tok/);
expect(service.getCoverUrl(12, 'v1')).toMatch(/\/api\/v1\/media\/book\/12\/cover\?v1.*token=tok/);
expect(service.getBackupCoverUrl(13)).toMatch(/\/api\/v1\/media\/book\/13\/backup-cover\?token=tok/);
expect(service.getBookdropCoverUrl(14)).toMatch(/\/api\/v1\/media\/bookdrop\/14\/cover\?token=tok/);
});
it('should encode filter values in filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValue('tree');
service.filterBooksBy('author', 'A&B');
expect(routerMock.createUrlTree).toHaveBeenCalledWith(
['/all-books'],
expect.objectContaining({
queryParams: expect.objectContaining({
filter: 'author:' + encodeURIComponent('A&B')
})
})
);
});
it('should always return a string or UrlTree from getBookUrl/filterBooksBy', () => {
routerMock.createUrlTree.mockReturnValueOnce('tree1').mockReturnValueOnce({} as UrlTree);
expect(typeof service.getBookUrl({id: 1} as any)).toMatch(/string|object/);
expect(typeof service.filterBooksBy('series', 'X')).toMatch(/string|object/);
});
});
@@ -1,133 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {AppVersion, ReleaseNote, VersionService} from './version.service';
describe('VersionService', () => {
let service: VersionService;
let httpClientMock: any;
const mockVersion: AppVersion = {
current: '1.0.0',
latest: '1.2.0'
};
const mockChangelog: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(VersionService);
});
it('should get version', () => {
httpClientMock.get.mockReturnValue(of(mockVersion));
service.getVersion().subscribe(version => {
expect(version).toEqual(mockVersion);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
});
});
it('should get changelog', () => {
httpClientMock.get.mockReturnValue(of(mockChangelog));
service.getChangelog().subscribe(changelog => {
expect(changelog).toEqual(mockChangelog);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});
it('should handle getVersion error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getVersion().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should handle getChangelog error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service.getChangelog().subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
});
describe('VersionService - API Contract Tests', () => {
let service: VersionService;
let httpClientMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn()
};
TestBed.configureTestingModule({
providers: [
{provide: HttpClient, useValue: httpClientMock}
]
});
service = TestBed.inject(VersionService);
});
it('should expect AppVersion from getVersion', () => {
const response: AppVersion = {current: '1.0.0', latest: '1.2.0'};
httpClientMock.get.mockReturnValue(of(response));
service.getVersion().subscribe(version => {
expect(typeof version.current).toBe('string');
expect(typeof version.latest).toBe('string');
});
});
it('should expect ReleaseNote[] from getChangelog', () => {
const response: ReleaseNote[] = [
{
version: '1.2.0',
name: 'Release 1.2.0',
changelog: 'Bug fixes and improvements',
url: 'https://example.com/release/1.2.0',
publishedAt: '2024-01-01T00:00:00Z'
}
];
httpClientMock.get.mockReturnValue(of(response));
service.getChangelog().subscribe(notes => {
expect(Array.isArray(notes)).toBe(true);
expect(notes[0]).toHaveProperty('version');
expect(notes[0]).toHaveProperty('name');
expect(notes[0]).toHaveProperty('changelog');
expect(notes[0]).toHaveProperty('url');
expect(notes[0]).toHaveProperty('publishedAt');
});
});
it('should call correct endpoints', () => {
httpClientMock.get.mockReturnValue(of({}));
service.getVersion().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/));
service.getChangelog().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/));
});
});