refactor(frontend): rename booklore-ui to frontend
- Frontend path: - rename the tracked Angular app tree from `booklore-ui/` to `frontend/` - preserve file contents during the move so this commit stays focused on the path change itself - Frontend docs: - update the moved frontend README and contribution guide where they refer to the renamed folder - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export type AnnotationStyle = 'highlight' | 'underline' | 'strikethrough' | 'squiggly';
|
||||
|
||||
export interface Annotation {
|
||||
id: number;
|
||||
userId?: number;
|
||||
bookId: number;
|
||||
cfi: string;
|
||||
text: string;
|
||||
color: string;
|
||||
style: AnnotationStyle;
|
||||
note?: string;
|
||||
chapterTitle?: string;
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateAnnotationRequest {
|
||||
bookId: number;
|
||||
cfi: string;
|
||||
text: string;
|
||||
color?: string;
|
||||
style?: AnnotationStyle;
|
||||
note?: string;
|
||||
chapterTitle?: string;
|
||||
}
|
||||
|
||||
export interface UpdateAnnotationRequest {
|
||||
color?: string;
|
||||
style?: AnnotationStyle;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AnnotationService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/annotations`;
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
getAnnotationsForBook(bookId: number): Observable<Annotation[]> {
|
||||
return this.http.get<Annotation[]>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
createAnnotation(request: CreateAnnotationRequest): Observable<Annotation> {
|
||||
return this.http.post<Annotation>(this.url, request);
|
||||
}
|
||||
|
||||
deleteAnnotation(annotationId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${annotationId}`);
|
||||
}
|
||||
|
||||
updateAnnotation(annotationId: number, request: UpdateAnnotationRequest): Observable<Annotation> {
|
||||
return this.http.put<Annotation>(`${this.url}/${annotationId}`, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
|
||||
import { effect, inject, Injectable, PLATFORM_ID, signal } from '@angular/core';
|
||||
import { $t, updatePreset, updateSurfacePalette } from '@primeuix/themes';
|
||||
import Aura from '@primeuix/themes/aura';
|
||||
import { AppState } from '../model/app-state.model';
|
||||
|
||||
type ColorPalette = Record<string, string>;
|
||||
|
||||
interface Palette {
|
||||
name: string;
|
||||
palette: ColorPalette;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AppConfigService {
|
||||
private readonly STORAGE_KEY = 'appConfigState';
|
||||
appState = signal<AppState>({});
|
||||
document = inject(DOCUMENT);
|
||||
platformId = inject(PLATFORM_ID);
|
||||
private initialized = false;
|
||||
|
||||
readonly surfaces: Palette[] = [
|
||||
{
|
||||
name: 'slate',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f8fafc',
|
||||
100: '#f1f5f9',
|
||||
200: '#e2e8f0',
|
||||
300: '#cbd5e1',
|
||||
400: '#94a3b8',
|
||||
500: '#64748b',
|
||||
600: '#475569',
|
||||
700: '#334155',
|
||||
800: '#283548',
|
||||
900: '#0f172a',
|
||||
950: '#020617'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'gray',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fafafa',
|
||||
100: '#f4f4f5',
|
||||
200: '#e4e4e7',
|
||||
300: '#d4d4d8',
|
||||
400: '#a1a1aa',
|
||||
500: '#71717a',
|
||||
600: '#52525b',
|
||||
700: '#3f3f46',
|
||||
800: '#313136',
|
||||
900: '#18181b',
|
||||
950: '#09090b'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'neutral',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fafafa',
|
||||
100: '#f5f5f5',
|
||||
200: '#e5e5e5',
|
||||
300: '#d4d4d4',
|
||||
400: '#a3a3a3',
|
||||
500: '#737373',
|
||||
600: '#525252',
|
||||
700: '#404040',
|
||||
800: '#303030',
|
||||
900: '#171717',
|
||||
950: '#0a0a0a'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'zinc',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fafafa',
|
||||
100: '#f4f4f5',
|
||||
200: '#e4e4e7',
|
||||
300: '#d4d4d8',
|
||||
400: '#a1a1aa',
|
||||
500: '#71717a',
|
||||
600: '#52525b',
|
||||
700: '#3f3f46',
|
||||
800: '#313136',
|
||||
900: '#18181b',
|
||||
950: '#09090b'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'stone',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fafaf9',
|
||||
100: '#f5f5f4',
|
||||
200: '#e7e5e4',
|
||||
300: '#d6d3d1',
|
||||
400: '#a8a29e',
|
||||
500: '#78716c',
|
||||
600: '#57534e',
|
||||
700: '#44403c',
|
||||
800: '#342f2b',
|
||||
900: '#1c1917',
|
||||
950: '#0c0a09'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'iron',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f1f3f4',
|
||||
100: '#e3e5e6',
|
||||
200: '#d2d4d6',
|
||||
300: '#b8bbc0',
|
||||
400: '#9ca0a6',
|
||||
500: '#7d8288',
|
||||
600: '#646a70',
|
||||
700: '#4c5258',
|
||||
800: '#353a40',
|
||||
900: '#1a1d20',
|
||||
950: '#0d0f11'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'steel',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f3f4f6',
|
||||
100: '#e5e7eb',
|
||||
200: '#d1d5db',
|
||||
300: '#b0b7c3',
|
||||
400: '#8b93a6',
|
||||
500: '#6b7280',
|
||||
600: '#545861',
|
||||
700: '#3f4347',
|
||||
800: '#2c2f33',
|
||||
900: '#16181b',
|
||||
950: '#0b0d0e'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'carbon',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#eef0f2',
|
||||
100: '#dde1e6',
|
||||
200: '#c7cdd5',
|
||||
300: '#a8b0bc',
|
||||
400: '#8691a0',
|
||||
500: '#697080',
|
||||
600: '#545a66',
|
||||
700: '#41464f',
|
||||
800: '#303439',
|
||||
900: '#181a1d',
|
||||
950: '#0c0e10'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'ash',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f4f6f8',
|
||||
100: '#e6e9ed',
|
||||
200: '#d3d8de',
|
||||
300: '#b4bcc7',
|
||||
400: '#919ca9',
|
||||
500: '#71808a',
|
||||
600: '#5a666f',
|
||||
700: '#464f56',
|
||||
800: '#34393e',
|
||||
900: '#1a1e21',
|
||||
950: '#0d1012'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'smoke',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f6f6f7',
|
||||
100: '#ebebed',
|
||||
200: '#dadadd',
|
||||
300: '#bbbcc1',
|
||||
400: '#989aa1',
|
||||
500: '#797c84',
|
||||
600: '#63666d',
|
||||
700: '#4f5257',
|
||||
800: '#3a3d42',
|
||||
900: '#1d2023',
|
||||
950: '#0e1011'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'midnight-blue',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fcfcfd',
|
||||
100: '#f7f8fb',
|
||||
200: '#f0f2f7',
|
||||
300: '#e5e8f0',
|
||||
400: '#d3d8e3',
|
||||
500: '#5c6b7a',
|
||||
600: '#4a5866',
|
||||
700: '#3b4651',
|
||||
800: '#38424d',
|
||||
900: '#1f252c',
|
||||
950: '#121518'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'charcoal',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f0f0f0',
|
||||
100: '#e5e5e5',
|
||||
200: '#d1d1d1',
|
||||
300: '#b8b8b8',
|
||||
400: '#9a9a9a',
|
||||
500: '#7d7d7d',
|
||||
600: '#666666',
|
||||
700: '#525252',
|
||||
800: '#3d3d3d',
|
||||
900: '#242424',
|
||||
950: '#141414'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'soho',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#ececec',
|
||||
100: '#dedfdf',
|
||||
200: '#c4c4c6',
|
||||
300: '#adaeb0',
|
||||
400: '#97979b',
|
||||
500: '#7f8084',
|
||||
600: '#6a6b70',
|
||||
700: '#55565b',
|
||||
800: '#3f4046',
|
||||
900: '#252530',
|
||||
950: '#16161d'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'viva',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#f3f3f3',
|
||||
100: '#e7e7e8',
|
||||
200: '#cfd0d0',
|
||||
300: '#b7b8b9',
|
||||
400: '#9fa1a1',
|
||||
500: '#87898a',
|
||||
600: '#6e7173',
|
||||
700: '#565a5b',
|
||||
800: '#3e4244',
|
||||
900: '#1e2324',
|
||||
950: '#0e1315'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'ocean',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fbfcfc',
|
||||
100: '#F7F9F8',
|
||||
200: '#EFF3F2',
|
||||
300: '#DADEDD',
|
||||
400: '#B1B7B6',
|
||||
500: '#828787',
|
||||
600: '#5F7274',
|
||||
700: '#415B61',
|
||||
800: '#324f5a',
|
||||
900: '#183240',
|
||||
950: '#0c1920'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'light-slate',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fcfcfd',
|
||||
100: '#f8fafc',
|
||||
200: '#f1f5f9',
|
||||
300: '#e2e8f0',
|
||||
400: '#cbd5e1',
|
||||
500: '#94a3b8',
|
||||
600: '#64748b',
|
||||
700: '#475569',
|
||||
800: '#3d5068',
|
||||
900: '#1e293b',
|
||||
950: '#0f172a'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'olive',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fcfcfb',
|
||||
100: '#f8f9f6',
|
||||
200: '#f1f4ed',
|
||||
300: '#e6eadc',
|
||||
400: '#d4dfc5',
|
||||
500: '#6a755e',
|
||||
600: '#555d4c',
|
||||
700: '#434a3d',
|
||||
800: '#3d4438',
|
||||
900: '#232824',
|
||||
950: '#131614'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'crimson',
|
||||
palette: {
|
||||
0: '#ffffff',
|
||||
50: '#fcfbfb',
|
||||
100: '#f8f5f5',
|
||||
200: '#f1ebeb',
|
||||
300: '#e6d9d9',
|
||||
400: '#d4c3c3',
|
||||
500: '#755e5e',
|
||||
600: '#5d4c4c',
|
||||
700: '#4a3d3d',
|
||||
800: '#423838',
|
||||
900: '#242020',
|
||||
950: '#141212'
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
constructor() {
|
||||
const initialState = this.loadAppState();
|
||||
this.appState.set({ ...initialState });
|
||||
this.document.documentElement.classList.add('p-dark');
|
||||
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
this.onPresetChange();
|
||||
}
|
||||
|
||||
effect(() => {
|
||||
const state = this.appState();
|
||||
if (!this.initialized || !state) {
|
||||
this.initialized = true;
|
||||
return;
|
||||
}
|
||||
this.saveAppState(state);
|
||||
this.onPresetChange();
|
||||
});
|
||||
}
|
||||
|
||||
private loadAppState(): AppState {
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
const storedState = localStorage.getItem(this.STORAGE_KEY);
|
||||
if (storedState) {
|
||||
return JSON.parse(storedState);
|
||||
}
|
||||
}
|
||||
return {
|
||||
preset: 'Aura',
|
||||
primary: 'green',
|
||||
surface: 'ash',
|
||||
};
|
||||
}
|
||||
|
||||
private saveAppState(state: AppState): void {
|
||||
if (isPlatformBrowser(this.platformId)) {
|
||||
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state));
|
||||
}
|
||||
}
|
||||
|
||||
private getSurfacePalette(surface: string): ColorPalette {
|
||||
return this.surfaces.find(s => s.name === surface)?.palette ?? {};
|
||||
}
|
||||
|
||||
getPresetExt(): object {
|
||||
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
|
||||
const primaryName = this.appState().primary ?? 'green';
|
||||
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
|
||||
const color = presetPalette[primaryName] ?? {};
|
||||
|
||||
if (primaryName === 'noir') {
|
||||
return {
|
||||
semantic: {
|
||||
primary: { ...surfacePalette },
|
||||
colorScheme: {
|
||||
dark: {
|
||||
primary: {
|
||||
color: '{primary.50}',
|
||||
contrastColor: '{primary.950}',
|
||||
hoverColor: '{primary.200}',
|
||||
activeColor: '{primary.300}'
|
||||
},
|
||||
highlight: {
|
||||
background: '{primary.50}',
|
||||
focusBackground: '{primary.300}',
|
||||
color: '{primary.950}',
|
||||
focusColor: '{primary.950}'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
semantic: {
|
||||
primary: color,
|
||||
colorScheme: {
|
||||
dark: {
|
||||
primary: {
|
||||
color: '{primary.400}',
|
||||
contrastColor: '{surface.900}',
|
||||
hoverColor: '{primary.300}',
|
||||
activeColor: '{primary.200}'
|
||||
},
|
||||
highlight: {
|
||||
background: 'color-mix(in srgb, {primary.400}, transparent 84%)',
|
||||
focusBackground: 'color-mix(in srgb, {primary.400}, transparent 76%)',
|
||||
color: 'rgba(255,255,255,.87)',
|
||||
focusColor: 'rgba(255,255,255,.87)'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
onPresetChange(): void {
|
||||
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
|
||||
const preset = this.getPresetExt();
|
||||
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({ useDefaultOptions: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export const APP_SETTINGS_QUERY_KEY = ['appSettings'] as const;
|
||||
export const PUBLIC_SETTINGS_QUERY_KEY = ['publicSettings'] as const;
|
||||
@@ -0,0 +1,131 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable, of} from 'rxjs';
|
||||
import {catchError, map, switchMap} from 'rxjs/operators';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AppSettings, OidcProviderDetails, OidcTestResult} from '../model/app-settings.model';
|
||||
import {AuthService} from './auth.service';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {APP_SETTINGS_QUERY_KEY, PUBLIC_SETTINGS_QUERY_KEY} from './app-settings-query-keys';
|
||||
|
||||
export interface PublicAppSettings {
|
||||
oidcEnabled: boolean;
|
||||
remoteAuthEnabled: boolean;
|
||||
oidcProviderDetails: OidcProviderDetails;
|
||||
oidcForceOnlyMode: boolean;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class AppSettingsService {
|
||||
private http = inject(HttpClient);
|
||||
private queryClient = inject(QueryClient);
|
||||
private authService = inject(AuthService);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/settings`;
|
||||
private readonly publicApiUrl = `${API_CONFIG.BASE_URL}/api/v1/public-settings`;
|
||||
|
||||
private publicSettingsQuery = injectQuery(() => ({
|
||||
...this.getPublicSettingsQueryOptions(),
|
||||
}));
|
||||
|
||||
private appSettingsQuery = injectQuery(() => ({
|
||||
...this.getAppSettingsQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
appSettings = computed(() => this.appSettingsQuery.data() ?? null);
|
||||
publicAppSettings = computed(() => this.publicSettingsQuery.data() ?? null);
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: APP_SETTINGS_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
|
||||
// When authenticated settings load, keep public settings cache in sync
|
||||
effect(() => {
|
||||
const settings = this.appSettings();
|
||||
if (settings) {
|
||||
this.syncPublicSettings(settings);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
getPublicSettingsQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: PUBLIC_SETTINGS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<PublicAppSettings>(this.publicApiUrl))
|
||||
});
|
||||
}
|
||||
|
||||
private getAppSettingsQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: APP_SETTINGS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<AppSettings>(this.apiUrl))
|
||||
});
|
||||
}
|
||||
|
||||
testOidcConnection(providerDetails: OidcProviderDetails): Observable<OidcTestResult> {
|
||||
return this.http.post<OidcTestResult>(`${this.apiUrl}/oidc/test`, providerDetails);
|
||||
}
|
||||
|
||||
private syncPublicSettings(appSettings: AppSettings): void {
|
||||
const updatedPublicSettings: PublicAppSettings = {
|
||||
oidcEnabled: appSettings.oidcEnabled,
|
||||
remoteAuthEnabled: appSettings.remoteAuthEnabled,
|
||||
oidcProviderDetails: appSettings.oidcProviderDetails,
|
||||
oidcForceOnlyMode: appSettings.oidcForceOnlyMode
|
||||
};
|
||||
const current = this.publicAppSettings();
|
||||
|
||||
if (
|
||||
!current ||
|
||||
current.oidcEnabled !== updatedPublicSettings.oidcEnabled ||
|
||||
current.remoteAuthEnabled !== updatedPublicSettings.remoteAuthEnabled ||
|
||||
current.oidcForceOnlyMode !== updatedPublicSettings.oidcForceOnlyMode ||
|
||||
JSON.stringify(current.oidcProviderDetails) !== JSON.stringify(updatedPublicSettings.oidcProviderDetails)
|
||||
) {
|
||||
this.queryClient.setQueryData(PUBLIC_SETTINGS_QUERY_KEY, updatedPublicSettings);
|
||||
}
|
||||
}
|
||||
|
||||
saveSettings(settings: { key: string; newValue: unknown }[]): Observable<void> {
|
||||
const payload = settings.map(setting => ({
|
||||
name: setting.key,
|
||||
value: setting.newValue
|
||||
}));
|
||||
|
||||
return this.http.put<void>(this.apiUrl, payload).pipe(
|
||||
switchMap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: APP_SETTINGS_QUERY_KEY});
|
||||
return of(void 0);
|
||||
}),
|
||||
map(() => void 0),
|
||||
catchError(err => {
|
||||
console.error('Error saving settings:', err);
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
toggleOidcEnabled(enabled: boolean): Observable<void> {
|
||||
const payload = [{name: 'OIDC_ENABLED', value: enabled}];
|
||||
return this.http.put<void>(this.apiUrl, payload).pipe(
|
||||
map(() => {
|
||||
const current = this.appSettings();
|
||||
if (current) {
|
||||
const updated = {...current, oidcEnabled: enabled};
|
||||
this.queryClient.setQueryData(APP_SETTINGS_QUERY_KEY, updated);
|
||||
this.syncPublicSettings(updated);
|
||||
}
|
||||
}),
|
||||
catchError(err => {
|
||||
console.error('Error toggling OIDC:', err);
|
||||
return of();
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import {inject, Injectable, Injector, signal} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, tap} from 'rxjs';
|
||||
import {RxStompService} from '../websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {createRxStompConfig} from '../websocket/rx-stomp.config';
|
||||
import {Router} from '@angular/router';
|
||||
import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
|
||||
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
|
||||
private rxStompService?: RxStompService;
|
||||
private postLoginInitialized = false;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private injector = inject(Injector);
|
||||
private router = inject(Router);
|
||||
private postLoginInitializer = inject(PostLoginInitializerService);
|
||||
|
||||
readonly token = signal<string | null>(this.getInternalAccessToken());
|
||||
|
||||
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
||||
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.initializeWebSocketConnection();
|
||||
this.handleSuccessfulAuth();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = this.getInternalRefreshToken();
|
||||
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
remoteLogin(): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
|
||||
return this.http.get<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/remote`).pipe(
|
||||
tap((response) => {
|
||||
if (response.accessToken && response.refreshToken) {
|
||||
this.saveInternalTokens(response.accessToken, response.refreshToken);
|
||||
this.initializeWebSocketConnection();
|
||||
this.handleSuccessfulAuth();
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
saveInternalTokens(accessToken: string, refreshToken: string): void {
|
||||
localStorage.setItem('accessToken_Internal', accessToken);
|
||||
localStorage.setItem('refreshToken_Internal', refreshToken);
|
||||
this.token.set(accessToken);
|
||||
}
|
||||
|
||||
getInternalAccessToken(): string | null {
|
||||
return localStorage.getItem('accessToken_Internal');
|
||||
}
|
||||
|
||||
getInternalRefreshToken(): string | null {
|
||||
return localStorage.getItem('refreshToken_Internal');
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
const refreshToken = this.getInternalRefreshToken();
|
||||
this.http.post<{ logoutUrl: string | null }>(`${this.apiUrl}/logout`, {refreshToken}).subscribe({
|
||||
next: (response) => {
|
||||
if (response.logoutUrl) {
|
||||
window.location.href = response.logoutUrl;
|
||||
} else {
|
||||
this.clearSession();
|
||||
this.router.navigate(['/login']).then(() => window.location.reload());
|
||||
}
|
||||
},
|
||||
error: () => {
|
||||
this.clearSession();
|
||||
this.router.navigate(['/login']).then(() => window.location.reload());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
forceLogout(reason: string): void {
|
||||
this.clearSession();
|
||||
this.router.navigate(['/login'], {queryParams: {reason}});
|
||||
}
|
||||
|
||||
clearSessionOnLoginPage(): void {
|
||||
this.clearSession();
|
||||
}
|
||||
|
||||
private clearSession(): void {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
localStorage.removeItem('refreshToken_Internal');
|
||||
this.token.set(null);
|
||||
this.postLoginInitialized = false;
|
||||
this.getRxStompService().deactivate();
|
||||
}
|
||||
|
||||
getRxStompService(): RxStompService {
|
||||
if (!this.rxStompService) {
|
||||
this.rxStompService = this.injector.get(RxStompService);
|
||||
}
|
||||
return this.rxStompService;
|
||||
}
|
||||
|
||||
initializeWebSocketConnection(): void {
|
||||
const token = this.getInternalAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
const stompService = this.getRxStompService();
|
||||
const config = createRxStompConfig(this);
|
||||
stompService.updateConfig(config);
|
||||
stompService.activate();
|
||||
|
||||
if (!this.postLoginInitialized) {
|
||||
this.handleSuccessfulAuth();
|
||||
}
|
||||
}
|
||||
|
||||
private handleSuccessfulAuth() {
|
||||
if (this.postLoginInitialized) return;
|
||||
this.postLoginInitialized = true;
|
||||
this.postLoginInitializer.initialize().subscribe({
|
||||
next: () => console.log('AuthService: Post-login initialization completed'),
|
||||
error: (err) => console.error('AuthService: Post-login initialization failed:', err)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function websocketInitializer(authService: AuthService): () => void {
|
||||
return () => authService.initializeWebSocketConnection();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export interface BookMark {
|
||||
id: number;
|
||||
userId?: number;
|
||||
bookId: number;
|
||||
cfi?: string; // For EPUB bookmarks
|
||||
positionMs?: number; // For audiobook bookmarks
|
||||
trackIndex?: number; // For folder-based audiobooks
|
||||
title: string;
|
||||
color?: string;
|
||||
notes?: string;
|
||||
priority?: number;
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateBookMarkRequest {
|
||||
bookId: number;
|
||||
cfi?: string; // For EPUB bookmarks
|
||||
positionMs?: number; // For audiobook bookmarks
|
||||
trackIndex?: number; // For folder-based audiobooks
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export interface UpdateBookMarkRequest {
|
||||
title?: string;
|
||||
cfi?: string;
|
||||
color?: string;
|
||||
notes?: string;
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookMarkService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/bookmarks`;
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
getBookmarksForBook(bookId: number): Observable<BookMark[]> {
|
||||
return this.http.get<BookMark[]>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
createBookmark(request: CreateBookMarkRequest): Observable<BookMark> {
|
||||
return this.http.post<BookMark>(this.url, request);
|
||||
}
|
||||
|
||||
deleteBookmark(bookmarkId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${bookmarkId}`);
|
||||
}
|
||||
|
||||
updateBookmark(bookmarkId: number, request: UpdateBookMarkRequest): Observable<BookMark> {
|
||||
return this.http.put<BookMark>(`${this.url}/${bookmarkId}`, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Subject} from 'rxjs';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BookMetadataHostService {
|
||||
private bookSwitchRequest$ = new Subject<number>();
|
||||
|
||||
requestBookSwitch(bookId: number) {
|
||||
this.bookSwitchRequest$.next(bookId);
|
||||
}
|
||||
|
||||
switchBook(bookId: number): void {
|
||||
this.bookSwitchRequest$.next(bookId);
|
||||
}
|
||||
|
||||
get bookSwitches$() {
|
||||
return this.bookSwitchRequest$.asObservable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export interface BookNoteV2 {
|
||||
id: number;
|
||||
userId?: number;
|
||||
bookId: number;
|
||||
cfi: string;
|
||||
selectedText?: string;
|
||||
noteContent: string;
|
||||
color?: string;
|
||||
chapterTitle?: string;
|
||||
createdAt: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface CreateBookNoteV2Request {
|
||||
bookId: number;
|
||||
cfi: string;
|
||||
selectedText?: string;
|
||||
noteContent: string;
|
||||
color?: string;
|
||||
chapterTitle?: string;
|
||||
}
|
||||
|
||||
export interface UpdateBookNoteV2Request {
|
||||
noteContent?: string;
|
||||
color?: string;
|
||||
chapterTitle?: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookNoteV2Service {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v2/book-notes`;
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
getNotesForBook(bookId: number): Observable<BookNoteV2[]> {
|
||||
return this.http.get<BookNoteV2[]>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
createNote(request: CreateBookNoteV2Request): Observable<BookNoteV2> {
|
||||
return this.http.post<BookNoteV2>(this.url, request);
|
||||
}
|
||||
|
||||
deleteNote(noteId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${noteId}`);
|
||||
}
|
||||
|
||||
updateNote(noteId: number, request: UpdateBookNoteV2Request): Observable<BookNoteV2> {
|
||||
return this.http.put<BookNoteV2>(`${this.url}/${noteId}`, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export interface BookNote {
|
||||
id: number;
|
||||
userId: number;
|
||||
bookId: number;
|
||||
title: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreateBookNoteRequest {
|
||||
id?: number;
|
||||
bookId: number;
|
||||
title: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookNoteService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/book-notes`;
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
getNotesForBook(bookId: number): Observable<BookNote[]> {
|
||||
return this.http.get<BookNote[]>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
createOrUpdateNote(request: CreateBookNoteRequest): Observable<BookNote> {
|
||||
return this.http.post<BookNote>(this.url, request);
|
||||
}
|
||||
|
||||
deleteNote(noteId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${noteId}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable, tap} from 'rxjs';
|
||||
import {CustomFont} from '../model/custom-font.model';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AuthService} from './auth.service';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
const CUSTOM_FONTS_QUERY_KEY = ['customFonts'] as const;
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CustomFontService {
|
||||
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`;
|
||||
private loadedFonts = new Set<string>();
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private fontsQuery = injectQuery(() => ({
|
||||
...this.getFontsQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
fonts = computed(() => this.fontsQuery.data() ?? []);
|
||||
isFontsLoading = computed(() => !!this.token() && this.fontsQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: CUSTOM_FONTS_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getFontsQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: CUSTOM_FONTS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<CustomFont[]>(this.apiUrl))
|
||||
});
|
||||
}
|
||||
|
||||
ensureFonts(): Promise<CustomFont[]> {
|
||||
return this.queryClient.ensureQueryData(this.getFontsQueryOptions());
|
||||
}
|
||||
|
||||
uploadFont(file: File, fontName?: string): Observable<CustomFont> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
if (fontName) {
|
||||
formData.append('fontName', fontName);
|
||||
}
|
||||
|
||||
return this.http.post<CustomFont>(`${this.apiUrl}/upload`, formData).pipe(
|
||||
tap(font => {
|
||||
this.queryClient.setQueryData<CustomFont[]>(CUSTOM_FONTS_QUERY_KEY, current =>
|
||||
[...(current ?? []), font]
|
||||
);
|
||||
this.loadFontFace(font).catch(err => {
|
||||
console.error('Failed to load font after upload:', err);
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteFont(fontId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.apiUrl}/${fontId}`).pipe(
|
||||
tap(() => {
|
||||
const currentFonts = this.fonts();
|
||||
const deletedFont = currentFonts.find(f => f.id === fontId);
|
||||
|
||||
this.queryClient.setQueryData<CustomFont[]>(CUSTOM_FONTS_QUERY_KEY, current =>
|
||||
(current ?? []).filter(f => f.id !== fontId)
|
||||
);
|
||||
|
||||
if (deletedFont) {
|
||||
this.removeFontFace(deletedFont.fontName);
|
||||
this.loadedFonts.delete(deletedFont.fontName);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getFontUrl(fontId: number): string {
|
||||
return `${this.apiUrl}/${fontId}/file`;
|
||||
}
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
public appendToken(url: string): string {
|
||||
const token = this.getToken();
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
async loadFontFace(font: CustomFont): Promise<void> {
|
||||
if (this.loadedFonts.has(font.fontName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const absoluteFontUrl = this.getFontUrl(font.id);
|
||||
const fontUrlWithToken = this.appendToken(absoluteFontUrl);
|
||||
|
||||
const fontFace = new FontFace(
|
||||
font.fontName,
|
||||
`url(${fontUrlWithToken})`,
|
||||
{
|
||||
weight: 'normal',
|
||||
style: 'normal'
|
||||
}
|
||||
);
|
||||
|
||||
await fontFace.load();
|
||||
document.fonts.add(fontFace);
|
||||
this.loadedFonts.add(font.fontName);
|
||||
} catch (error) {
|
||||
console.error(`Failed to load font ${font.fontName}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async loadAllFonts(fonts: CustomFont[]): Promise<void> {
|
||||
const loadPromises = fonts.map(font => this.loadFontFace(font));
|
||||
await Promise.allSettled(loadPromises);
|
||||
}
|
||||
|
||||
isFontLoaded(fontName: string): boolean {
|
||||
return this.loadedFonts.has(fontName);
|
||||
}
|
||||
|
||||
private removeFontFace(fontName: string): void {
|
||||
for (const font of document.fonts) {
|
||||
if (font.family === fontName) {
|
||||
document.fonts.delete(font);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class FileDownloadService {
|
||||
private http = inject(HttpClient);
|
||||
|
||||
downloadFile(url: string, filename: string): void {
|
||||
this.http.get(url, {responseType: 'blob', observe: 'response'}).subscribe(response => {
|
||||
const blob = response.body;
|
||||
if (!blob) return;
|
||||
|
||||
const resolvedFilename = this.extractFilename(response.headers.get('Content-Disposition')) ?? filename;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = resolvedFilename;
|
||||
link.click();
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
});
|
||||
}
|
||||
|
||||
private extractFilename(contentDisposition: string | null): string | null {
|
||||
if (!contentDisposition) return null;
|
||||
const match = contentDisposition.match(/filename\*=UTF-8''([\w%\-.]+)/i);
|
||||
return match ? decodeURIComponent(match[1]) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export interface FileMoveRequest {
|
||||
bookIds: number[];
|
||||
moves: {
|
||||
bookId: number;
|
||||
targetLibraryId: number | null;
|
||||
targetLibraryPathId: number | null;
|
||||
}[];
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class FileOperationsService {
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/files`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
moveFiles(request: FileMoveRequest): Observable<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/move`, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {DialogLauncherService} from '../services/dialog-launcher.service';
|
||||
|
||||
export interface IconSelection {
|
||||
type: 'PRIME_NG' | 'CUSTOM_SVG';
|
||||
value: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class IconPickerService {
|
||||
private dialogLauncherService = inject(DialogLauncherService);
|
||||
|
||||
open(): Observable<IconSelection> {
|
||||
const ref = this.dialogLauncherService.openIconPickerDialog();
|
||||
return ref!.onClose as Observable<IconSelection>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LocalStorageService {
|
||||
|
||||
get<T>(key: string): T | null {
|
||||
try {
|
||||
const value = localStorage.getItem(key);
|
||||
return value ? JSON.parse(value) as T : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
set<T>(key: string, value: T): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
remove(key: string): void {
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { API_CONFIG } from '../../core/config/api-config';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class MetadataMatchWeightsService {
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
recalculateAll(): Observable<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import {effect, inject, Injectable, OnDestroy} from '@angular/core';
|
||||
import {BehaviorSubject, Subject, Subscription} from 'rxjs';
|
||||
import {MetadataBatchProgressNotification} from '../model/metadata-batch-progress.model';
|
||||
import {MetadataTaskService} from '../../features/book/service/metadata-task';
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class MetadataProgressService implements OnDestroy {
|
||||
private progressMap = new Map<string, BehaviorSubject<MetadataBatchProgressNotification>>();
|
||||
|
||||
private progressUpdatesSubject = new Subject<MetadataBatchProgressNotification>();
|
||||
progressUpdates$ = this.progressUpdatesSubject.asObservable();
|
||||
|
||||
private activeTasksSubject = new BehaviorSubject<Record<string, MetadataBatchProgressNotification>>({});
|
||||
activeTasks$ = this.activeTasksSubject.asObservable();
|
||||
|
||||
private metadataTaskService = inject(MetadataTaskService);
|
||||
private userService = inject(UserService);
|
||||
|
||||
private subscriptions = new Subscription();
|
||||
private hasInitialized = false;
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const user = this.userService.currentUser();
|
||||
if (this.hasInitialized || !user) {
|
||||
return;
|
||||
}
|
||||
this.hasInitialized = true;
|
||||
|
||||
if (!this.hasMetadataPermissions(user)) {
|
||||
return;
|
||||
}
|
||||
const activeTasksSub = this.metadataTaskService.getActiveTasks().subscribe({
|
||||
next: (tasks) => this.initializeActiveTasks(tasks),
|
||||
error: (err) => console.warn('Failed to fetch active metadata tasks:', err)
|
||||
});
|
||||
this.subscriptions.add(activeTasksSub);
|
||||
});
|
||||
}
|
||||
|
||||
handleIncomingProgress(progress: MetadataBatchProgressNotification): void {
|
||||
const {taskId} = progress;
|
||||
|
||||
if (!this.progressMap.has(taskId)) {
|
||||
this.progressMap.set(taskId, new BehaviorSubject(progress));
|
||||
} else {
|
||||
this.progressMap.get(taskId)!.next(progress);
|
||||
}
|
||||
|
||||
this.progressUpdatesSubject.next(progress);
|
||||
this.activeTasksSubject.next(this.getActiveTasks());
|
||||
}
|
||||
|
||||
clearTask(taskId: string): void {
|
||||
this.progressMap.delete(taskId);
|
||||
this.activeTasksSubject.next(this.getActiveTasks());
|
||||
}
|
||||
|
||||
getActiveTasks(): Record<string, MetadataBatchProgressNotification> {
|
||||
const result: Record<string, MetadataBatchProgressNotification> = {};
|
||||
this.progressMap.forEach((subject, taskId) => {
|
||||
result[taskId] = subject.getValue();
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
private hasMetadataPermissions(user: { permissions: { admin: boolean; canEditMetadata: boolean } } | null): boolean {
|
||||
return !!(user?.permissions?.admin || user?.permissions?.canEditMetadata);
|
||||
}
|
||||
|
||||
private initializeActiveTasks(tasks: MetadataBatchProgressNotification[]): void {
|
||||
for (const task of tasks) {
|
||||
this.progressMap.set(task.taskId, new BehaviorSubject(task));
|
||||
this.progressUpdatesSubject.next(task);
|
||||
}
|
||||
this.activeTasksSubject.next(this.getActiveTasks());
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscriptions.unsubscribe();
|
||||
this.progressMap.forEach(subject => subject.complete());
|
||||
this.progressUpdatesSubject.complete();
|
||||
this.activeTasksSubject.complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {OidcGroupMapping} from '../model/oidc-group-mapping.model';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class OidcGroupMappingService {
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private baseUrl = `${API_CONFIG.BASE_URL}/api/v1/admin/oidc-group-mappings`;
|
||||
|
||||
getAll(): Observable<OidcGroupMapping[]> {
|
||||
return this.http.get<OidcGroupMapping[]>(this.baseUrl);
|
||||
}
|
||||
|
||||
create(mapping: OidcGroupMapping): Observable<OidcGroupMapping> {
|
||||
return this.http.post<OidcGroupMapping>(this.baseUrl, mapping);
|
||||
}
|
||||
|
||||
update(id: number, mapping: OidcGroupMapping): Observable<OidcGroupMapping> {
|
||||
return this.http.put<OidcGroupMapping>(`${this.baseUrl}/${id}`, mapping);
|
||||
}
|
||||
|
||||
delete(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.baseUrl}/${id}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {inject, Injectable} from "@angular/core";
|
||||
import {Title} from "@angular/platform-browser";
|
||||
import {Book} from "../../features/book/model/book.model";
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class PageTitleService {
|
||||
protected titleService = inject(Title)
|
||||
|
||||
private appName = 'Grimmory'
|
||||
|
||||
setBookPageTitle(book: Book) {
|
||||
const title = [
|
||||
`${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.primaryFile?.bookType})`
|
||||
].filter(part => part);
|
||||
|
||||
this.setPageTitle(title.join(' '));
|
||||
}
|
||||
|
||||
setPageTitle(pageTitle: string) {
|
||||
this.titleService.setTitle([pageTitle, this.appName].filter(part => part).join(' - '));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class PdfAnnotationService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/pdf-annotations`;
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
getAnnotations(bookId: number): Observable<{ data: string }> {
|
||||
return this.http.get<{ data: string }>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
|
||||
saveAnnotations(bookId: number, data: string): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/book/${bookId}`, {data});
|
||||
}
|
||||
|
||||
deleteAnnotations(bookId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/book/${bookId}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {BookType} from '../../features/book/model/book.model';
|
||||
|
||||
export interface ReadingSessionResponse {
|
||||
id: number;
|
||||
bookId: number;
|
||||
bookTitle: string;
|
||||
bookType: BookType;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
durationSeconds: number;
|
||||
startProgress: number;
|
||||
endProgress: number;
|
||||
progressDelta: number;
|
||||
startLocation?: string;
|
||||
endLocation?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface PageableResponse<T> {
|
||||
content: T[];
|
||||
page: {
|
||||
totalElements: number;
|
||||
totalPages: number;
|
||||
number: number;
|
||||
size: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CreateReadingSessionDto {
|
||||
bookId: number;
|
||||
bookType: BookType;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
durationSeconds: number;
|
||||
durationFormatted: string;
|
||||
startProgress?: number;
|
||||
endProgress?: number;
|
||||
progressDelta?: number;
|
||||
startLocation?: string;
|
||||
endLocation?: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadingSessionApiService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`;
|
||||
|
||||
createSession(sessionData: CreateReadingSessionDto): Observable<void> {
|
||||
return this.http.post<void>(this.url, sessionData);
|
||||
}
|
||||
|
||||
getSessionsByBookId(bookId: number, page: number = 0, size: number = 5): Observable<PageableResponse<ReadingSessionResponse>> {
|
||||
const params = new HttpParams()
|
||||
.set('page', page.toString())
|
||||
.set('size', size.toString());
|
||||
|
||||
return this.http.get<PageableResponse<ReadingSessionResponse>>(
|
||||
`${this.url}/book/${bookId}`,
|
||||
{params}
|
||||
);
|
||||
}
|
||||
|
||||
sendSessionBeacon(sessionData: CreateReadingSessionDto): boolean {
|
||||
try {
|
||||
const blob = new Blob([JSON.stringify(sessionData)], {type: 'application/json'});
|
||||
return navigator.sendBeacon(this.url, blob);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { fromEvent, merge, Subscription } from 'rxjs';
|
||||
import { debounceTime } from 'rxjs/operators';
|
||||
import { BookType } from '../../features/book/model/book.model';
|
||||
import {
|
||||
ReadingSessionApiService,
|
||||
CreateReadingSessionDto
|
||||
} from './reading-session-api.service';
|
||||
|
||||
export interface ReadingSession {
|
||||
bookId: number;
|
||||
bookType: BookType;
|
||||
startTime: Date;
|
||||
endTime?: Date;
|
||||
durationSeconds?: number;
|
||||
startLocation?: string;
|
||||
endLocation?: string;
|
||||
startProgress?: number;
|
||||
endProgress?: number;
|
||||
progressDelta?: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class ReadingSessionService {
|
||||
private readonly apiService = inject(ReadingSessionApiService);
|
||||
|
||||
private currentSession: ReadingSession | null = null;
|
||||
private idleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private activitySubscription: Subscription | null = null;
|
||||
private hiddenAt: number | null = null;
|
||||
|
||||
private readonly IDLE_TIMEOUT_MS = 5 * 60 * 1000;
|
||||
private readonly MIN_SESSION_DURATION_SECONDS = 30;
|
||||
private readonly ACTIVITY_DEBOUNCE_MS = 1000;
|
||||
|
||||
constructor() {
|
||||
this.setupBrowserLifecycleListeners();
|
||||
}
|
||||
|
||||
private setupBrowserLifecycleListeners(): void {
|
||||
window.addEventListener('beforeunload', () => {
|
||||
if (this.currentSession) {
|
||||
this.endSessionSync();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.hidden && this.currentSession) {
|
||||
this.log('Tab hidden, pausing session');
|
||||
this.hiddenAt = Date.now();
|
||||
this.pauseIdleDetection();
|
||||
} else if (!document.hidden && this.currentSession) {
|
||||
if (this.hiddenAt && Date.now() - this.hiddenAt > this.IDLE_TIMEOUT_MS) {
|
||||
this.log('Tab was hidden too long, ending session');
|
||||
this.stopIdleDetection();
|
||||
const cappedEndTime = new Date(this.hiddenAt + this.IDLE_TIMEOUT_MS);
|
||||
this.currentSession.endTime = cappedEndTime;
|
||||
const durationMs = cappedEndTime.getTime() - this.currentSession.startTime.getTime();
|
||||
this.currentSession.durationSeconds = Math.floor(durationMs / 1000);
|
||||
if (this.currentSession.startProgress != null && this.currentSession.endProgress != null) {
|
||||
this.currentSession.progressDelta = this.currentSession.endProgress - this.currentSession.startProgress;
|
||||
}
|
||||
if (this.currentSession.durationSeconds >= this.MIN_SESSION_DURATION_SECONDS) {
|
||||
this.sendSessionToBackend(this.currentSession);
|
||||
}
|
||||
this.currentSession = null;
|
||||
} else {
|
||||
this.log('Tab visible, resuming session');
|
||||
this.resumeIdleDetection();
|
||||
}
|
||||
this.hiddenAt = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
startSession(bookId: number, bookType: BookType, startLocation?: string, startProgress?: number): void {
|
||||
if (this.currentSession) {
|
||||
this.endSession();
|
||||
}
|
||||
|
||||
this.currentSession = {
|
||||
bookId,
|
||||
bookType,
|
||||
startTime: new Date(),
|
||||
startLocation,
|
||||
startProgress
|
||||
};
|
||||
|
||||
this.log('Reading session started', {
|
||||
bookId,
|
||||
startTime: this.currentSession.startTime.toISOString(),
|
||||
startLocation,
|
||||
startProgress: startProgress != null ? `${startProgress.toFixed(1)}%` : 'N/A'
|
||||
});
|
||||
|
||||
this.startIdleDetection();
|
||||
}
|
||||
|
||||
updateProgress(currentLocation?: string, currentProgress?: number): void {
|
||||
if (!this.currentSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentSession.endLocation = currentLocation;
|
||||
this.currentSession.endProgress = currentProgress;
|
||||
this.resetIdleTimer();
|
||||
}
|
||||
|
||||
endSession(endLocation?: string, endProgress?: number): void {
|
||||
if (!this.currentSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.stopIdleDetection();
|
||||
|
||||
this.currentSession.endTime = new Date();
|
||||
this.currentSession.endLocation = endLocation ?? this.currentSession.endLocation;
|
||||
this.currentSession.endProgress = endProgress ?? this.currentSession.endProgress;
|
||||
|
||||
const durationMs = this.currentSession.endTime.getTime() - this.currentSession.startTime.getTime();
|
||||
this.currentSession.durationSeconds = Math.floor(durationMs / 1000);
|
||||
|
||||
if (this.currentSession.startProgress != null && this.currentSession.endProgress != null) {
|
||||
this.currentSession.progressDelta = this.currentSession.endProgress - this.currentSession.startProgress;
|
||||
}
|
||||
|
||||
if (this.currentSession.durationSeconds >= this.MIN_SESSION_DURATION_SECONDS) {
|
||||
this.sendSessionToBackend(this.currentSession);
|
||||
} else {
|
||||
this.log('Session too short, discarding', {
|
||||
durationSeconds: this.currentSession.durationSeconds
|
||||
});
|
||||
}
|
||||
|
||||
this.currentSession = null;
|
||||
}
|
||||
|
||||
private endSessionSync(): void {
|
||||
if (!this.currentSession) {
|
||||
return;
|
||||
}
|
||||
|
||||
let endTime = new Date();
|
||||
if (this.hiddenAt && endTime.getTime() - this.hiddenAt > this.IDLE_TIMEOUT_MS) {
|
||||
endTime = new Date(this.hiddenAt + this.IDLE_TIMEOUT_MS);
|
||||
}
|
||||
const durationMs = endTime.getTime() - this.currentSession.startTime.getTime();
|
||||
const durationSeconds = Math.floor(durationMs / 1000);
|
||||
|
||||
if (durationSeconds < this.MIN_SESSION_DURATION_SECONDS) {
|
||||
this.cleanup();
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionData = this.buildSessionData(
|
||||
this.currentSession,
|
||||
endTime,
|
||||
durationSeconds
|
||||
);
|
||||
|
||||
this.log('Reading 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 sendSessionToBackend(session: ReadingSession): void {
|
||||
if (!session.endTime || session.durationSeconds == null) {
|
||||
this.logError('Invalid session data, missing endTime or duration');
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionData = this.buildSessionData(
|
||||
session,
|
||||
session.endTime,
|
||||
session.durationSeconds
|
||||
);
|
||||
|
||||
this.log('Reading 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: ReadingSession,
|
||||
endTime: Date,
|
||||
durationSeconds: number
|
||||
): CreateReadingSessionDto {
|
||||
return {
|
||||
bookId: session.bookId,
|
||||
bookType: session.bookType,
|
||||
startTime: session.startTime.toISOString(),
|
||||
endTime: endTime.toISOString(),
|
||||
durationSeconds,
|
||||
durationFormatted: this.formatDuration(durationSeconds),
|
||||
startProgress: session.startProgress != null ? Math.round(session.startProgress * 100) / 100 : undefined,
|
||||
endProgress: session.endProgress != null ? Math.round(session.endProgress * 100) / 100 : undefined,
|
||||
progressDelta: session.progressDelta != null ? Math.round(session.progressDelta * 100) / 100 : undefined,
|
||||
startLocation: session.startLocation,
|
||||
endLocation: session.endLocation
|
||||
};
|
||||
}
|
||||
|
||||
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 startIdleDetection(): void {
|
||||
this.stopIdleDetection();
|
||||
|
||||
const activity$ = merge(
|
||||
fromEvent(document, 'mousemove'),
|
||||
fromEvent(document, 'mousedown'),
|
||||
fromEvent(document, 'keypress'),
|
||||
fromEvent(document, 'scroll'),
|
||||
fromEvent(document, 'touchstart')
|
||||
).pipe(
|
||||
debounceTime(this.ACTIVITY_DEBOUNCE_MS)
|
||||
);
|
||||
|
||||
this.activitySubscription = activity$.subscribe(() => {
|
||||
this.resetIdleTimer();
|
||||
});
|
||||
|
||||
this.resetIdleTimer();
|
||||
}
|
||||
|
||||
private pauseIdleDetection(): void {
|
||||
if (this.idleTimer) {
|
||||
clearTimeout(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
}
|
||||
if (this.activitySubscription) {
|
||||
this.activitySubscription.unsubscribe();
|
||||
this.activitySubscription = null;
|
||||
}
|
||||
}
|
||||
|
||||
private resumeIdleDetection(): void {
|
||||
if (this.currentSession) {
|
||||
this.startIdleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
private resetIdleTimer(): void {
|
||||
if (this.idleTimer) {
|
||||
clearTimeout(this.idleTimer);
|
||||
}
|
||||
|
||||
this.idleTimer = setTimeout(() => {
|
||||
this.log('User idle detected, ending session');
|
||||
this.endSession();
|
||||
}, this.IDLE_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
private stopIdleDetection(): void {
|
||||
if (this.idleTimer) {
|
||||
clearTimeout(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
}
|
||||
if (this.activitySubscription) {
|
||||
this.activitySubscription.unsubscribe();
|
||||
this.activitySubscription = null;
|
||||
}
|
||||
}
|
||||
|
||||
private cleanup(): void {
|
||||
this.stopIdleDetection();
|
||||
this.currentSession = null;
|
||||
}
|
||||
|
||||
isSessionActive(): boolean {
|
||||
return this.currentSession !== null;
|
||||
}
|
||||
|
||||
private log(message: string, data?: unknown): void {
|
||||
if (data) {
|
||||
console.log(`[ReadingSession] ${message}`, data);
|
||||
} else {
|
||||
console.log(`[ReadingSession] ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
private logError(message: string, error?: unknown): void {
|
||||
if (error) {
|
||||
console.error(`[ReadingSession] ${message}`, error);
|
||||
} else {
|
||||
console.error(`[ReadingSession] ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {AppSettingsService} from './app-settings.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {Observable} from 'rxjs';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class SettingsHelperService {
|
||||
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
saveSetting(key: string, value: unknown): Observable<void> {
|
||||
const observable = this.appSettingsService.saveSettings([{key, newValue: value}]);
|
||||
|
||||
observable.subscribe({
|
||||
next: () => this.showSuccessMessage(),
|
||||
error: (error) => {
|
||||
console.error('Failed to save setting:', error);
|
||||
this.showErrorMessage();
|
||||
}
|
||||
});
|
||||
|
||||
return observable;
|
||||
}
|
||||
|
||||
private showSuccessMessage(): void {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('shared.settingsHelper.settingsSavedSummary'),
|
||||
detail: this.t.translate('shared.settingsHelper.settingsSavedDetail')
|
||||
});
|
||||
}
|
||||
|
||||
private showErrorMessage(): void {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('shared.settingsHelper.saveErrorDetail')
|
||||
});
|
||||
}
|
||||
|
||||
showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
|
||||
this.messageService.add({severity, summary, detail});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {AuthService} from './auth.service';
|
||||
import {UserService} from '../../features/settings/user-management/user.service';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class StartupService {
|
||||
private authService = inject(AuthService);
|
||||
private userService = inject(UserService);
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
load(): Promise<void> {
|
||||
if (this.authService.token()) {
|
||||
return this.queryClient.fetchQuery(this.userService.getUserQueryOptions()).then(() => {});
|
||||
}
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
import {AuthService} from './auth.service';
|
||||
import {BookService} from '../../features/book/service/book.service';
|
||||
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
|
||||
import {Router} from '@angular/router';
|
||||
import {Book,BookType} from '../../features/book/model/book.model';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class UrlHelperService {
|
||||
private readonly baseUrl = API_CONFIG.BASE_URL;
|
||||
private readonly mediaBaseUrl = `${this.baseUrl}/api/v1/media`;
|
||||
private authService = inject(AuthService);
|
||||
private bookService = inject(BookService);
|
||||
private router = inject(Router);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
const token = this.getToken();
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getThumbnailUrl(bookId: number, coverUpdatedOn?: string): string {
|
||||
if (!coverUpdatedOn) {
|
||||
const book = this.bookService.findBookById(bookId);
|
||||
if (book && book.metadata) {
|
||||
const coverGenerator = new CoverGeneratorComponent();
|
||||
coverGenerator.title = book.metadata.title || '';
|
||||
coverGenerator.author = (book.metadata.authors || []).join(', ');
|
||||
return coverGenerator.generateCover();
|
||||
}
|
||||
}
|
||||
let url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail`;
|
||||
if (coverUpdatedOn) {
|
||||
url += `?${coverUpdatedOn}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getDirectThumbnailUrl(bookId: number, coverUpdatedOn?: string): string {
|
||||
let url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail`;
|
||||
if (coverUpdatedOn) {
|
||||
url += `?${coverUpdatedOn}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getCoverUrl(bookId: number, coverUpdatedOn?: string): string {
|
||||
if (!coverUpdatedOn) {
|
||||
const book = this.bookService.findBookById(bookId);
|
||||
if (book && book.metadata) {
|
||||
const coverGenerator = new CoverGeneratorComponent();
|
||||
coverGenerator.title = book.metadata.title || '';
|
||||
coverGenerator.author = (book.metadata.authors || []).join(', ');
|
||||
return coverGenerator.generateCover();
|
||||
}
|
||||
}
|
||||
let url = `${this.mediaBaseUrl}/book/${bookId}/cover`;
|
||||
if (coverUpdatedOn) {
|
||||
url += `?${coverUpdatedOn}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getBackupCoverUrl(bookId: number): string {
|
||||
const url = `${this.mediaBaseUrl}/book/${bookId}/backup-cover`;
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getAudiobookCoverUrl(bookId: number, audiobookCoverUpdatedOn?: string): string {
|
||||
if (!audiobookCoverUpdatedOn) {
|
||||
const book = this.bookService.findBookById(bookId);
|
||||
if (book && book.metadata) {
|
||||
const coverGenerator = new CoverGeneratorComponent();
|
||||
coverGenerator.title = book.metadata.title || '';
|
||||
coverGenerator.author = (book.metadata.authors || []).join(', ');
|
||||
coverGenerator.isSquare = true;
|
||||
return coverGenerator.generateCover();
|
||||
}
|
||||
}
|
||||
let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-cover`;
|
||||
if (audiobookCoverUpdatedOn) {
|
||||
url += `?${audiobookCoverUpdatedOn}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getAudiobookThumbnailUrl(bookId: number, audiobookCoverUpdatedOn?: string): string {
|
||||
if (!audiobookCoverUpdatedOn) {
|
||||
const book = this.bookService.findBookById(bookId);
|
||||
if (book && book.metadata) {
|
||||
const coverGenerator = new CoverGeneratorComponent();
|
||||
coverGenerator.title = book.metadata.title || '';
|
||||
coverGenerator.author = (book.metadata.authors || []).join(', ');
|
||||
coverGenerator.isSquare = true;
|
||||
return coverGenerator.generateCover();
|
||||
}
|
||||
}
|
||||
let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-thumbnail`;
|
||||
if (audiobookCoverUpdatedOn) {
|
||||
url += `?${audiobookCoverUpdatedOn}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getBookdropCoverUrl(bookdropId: number): string {
|
||||
const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`;
|
||||
return this.appendToken(url);
|
||||
}
|
||||
|
||||
getBookUrl(book: Book) {
|
||||
return this.router.createUrlTree(['/book', book.id], {
|
||||
queryParams: {tab: 'view'}
|
||||
});
|
||||
}
|
||||
|
||||
getBookPrimaryReadingUrl(book: Book) {
|
||||
const bookType: BookType | undefined = book.primaryFile?.bookType;
|
||||
|
||||
let baseUrl: string | null = null;
|
||||
|
||||
switch (bookType) {
|
||||
case 'PDF':
|
||||
baseUrl = 'pdf-reader';
|
||||
break;
|
||||
|
||||
case 'EPUB':
|
||||
case 'FB2':
|
||||
case 'MOBI':
|
||||
case 'AZW3':
|
||||
baseUrl = 'ebook-reader';
|
||||
break;
|
||||
|
||||
case 'CBX':
|
||||
baseUrl = 'cbx-reader';
|
||||
break;
|
||||
|
||||
case 'AUDIOBOOK':
|
||||
baseUrl = 'audiobook-player';
|
||||
break;
|
||||
}
|
||||
|
||||
if (!baseUrl) {
|
||||
console.error('Unsupported book type:', bookType);
|
||||
//Go to book URL as a fall-back
|
||||
return this.getBookUrl(book);
|
||||
}
|
||||
|
||||
return this.router.createUrlTree([`/${baseUrl}/book/${book.id}`], undefined);
|
||||
}
|
||||
|
||||
filterBooksBy(filterKey: string, filterValue: string) {
|
||||
if (filterKey === 'series') {
|
||||
return this.router.createUrlTree(['/series', encodeURIComponent(filterValue)])
|
||||
}
|
||||
|
||||
return this.router.createUrlTree(['/all-books'], {
|
||||
queryParams: {
|
||||
view: 'grid',
|
||||
sort: 'title',
|
||||
direction: 'asc',
|
||||
sidebar: true,
|
||||
filter: `${filterKey}:${encodeURIComponent(filterValue)}`
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import {API_CONFIG} from '../../core/config/api-config';
|
||||
|
||||
export interface AppVersion {
|
||||
current: string;
|
||||
latest: string;
|
||||
}
|
||||
|
||||
export interface ReleaseNote {
|
||||
version: string;
|
||||
name: string;
|
||||
changelog: string;
|
||||
url: string;
|
||||
publishedAt: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class VersionService {
|
||||
private versionUrl = `${API_CONFIG.BASE_URL}/api/v1/version`;
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
getVersion(): Observable<AppVersion> {
|
||||
return this.http.get<AppVersion>(this.versionUrl);
|
||||
}
|
||||
|
||||
getChangelog(): Observable<ReleaseNote[]> {
|
||||
return this.http.get<ReleaseNote[]>(`${this.versionUrl}/changelog`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user