Improve Angular project structure and code organization (#1328)

This commit is contained in:
Aditya Chandel
2025-10-12 02:01:59 -06:00
committed by GitHub
parent 54a8bacccd
commit 7c9bd56f63
405 changed files with 463 additions and 727 deletions
@@ -0,0 +1,435 @@
import {DOCUMENT, isPlatformBrowser} from '@angular/common';
import {effect, inject, Injectable, PLATFORM_ID, signal} from '@angular/core';
import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes';
import Aura from '@primeng/themes/aura';
import {AppState} from '../model/app-state.model';
type ColorPalette = Record<string, string>;
interface Palette {
name: string;
palette: ColorPalette;
}
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
private readonly STORAGE_KEY = 'appConfigState';
appState = signal<AppState>({});
document = inject(DOCUMENT);
platformId = inject(PLATFORM_ID);
private initialized = false;
readonly surfaces: Palette[] = [
{
name: 'slate',
palette: {
0: '#ffffff',
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
900: '#0f172a',
950: '#020617'
}
},
{
name: 'gray',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'neutral',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f5f5f5',
200: '#e5e5e5',
300: '#d4d4d4',
400: '#a3a3a3',
500: '#737373',
600: '#525252',
700: '#404040',
800: '#262626',
900: '#171717',
950: '#0a0a0a'
}
},
{
name: 'zinc',
palette: {
0: '#ffffff',
50: '#fafafa',
100: '#f4f4f5',
200: '#e4e4e7',
300: '#d4d4d8',
400: '#a1a1aa',
500: '#71717a',
600: '#52525b',
700: '#3f3f46',
800: '#27272a',
900: '#18181b',
950: '#09090b'
}
},
{
name: 'stone',
palette: {
0: '#ffffff',
50: '#fafaf9',
100: '#f5f5f4',
200: '#e7e5e4',
300: '#d6d3d1',
400: '#a8a29e',
500: '#78716c',
600: '#57534e',
700: '#44403c',
800: '#292524',
900: '#1c1917',
950: '#0c0a09'
}
},
{
name: 'iron',
palette: {
0: '#ffffff',
50: '#f1f3f4',
100: '#e3e5e6',
200: '#d2d4d6',
300: '#b8bbc0',
400: '#9ca0a6',
500: '#7d8288',
600: '#646a70',
700: '#4c5258',
800: '#353a40',
900: '#1a1d20',
950: '#0d0f11'
}
},
{
name: 'steel',
palette: {
0: '#ffffff',
50: '#f3f4f6',
100: '#e5e7eb',
200: '#d1d5db',
300: '#b0b7c3',
400: '#8b93a6',
500: '#6b7280',
600: '#545861',
700: '#3f4347',
800: '#2c2f33',
900: '#16181b',
950: '#0b0d0e'
}
},
{
name: 'carbon',
palette: {
0: '#ffffff',
50: '#eef0f2',
100: '#dde1e6',
200: '#c7cdd5',
300: '#a8b0bc',
400: '#8691a0',
500: '#697080',
600: '#545a66',
700: '#41464f',
800: '#303439',
900: '#181a1d',
950: '#0c0e10'
}
},
{
name: 'ash',
palette: {
0: '#ffffff',
50: '#f4f6f8',
100: '#e6e9ed',
200: '#d3d8de',
300: '#b4bcc7',
400: '#919ca9',
500: '#71808a',
600: '#5a666f',
700: '#464f56',
800: '#34393e',
900: '#1a1e21',
950: '#0d1012'
}
},
{
name: 'smoke',
palette: {
0: '#ffffff',
50: '#f6f6f7',
100: '#ebebed',
200: '#dadadd',
300: '#bbbcc1',
400: '#989aa1',
500: '#797c84',
600: '#63666d',
700: '#4f5257',
800: '#3a3d42',
900: '#1d2023',
950: '#0e1011'
}
},
{
name: 'midnight-blue',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f7f8fb',
200: '#f0f2f7',
300: '#e5e8f0',
400: '#d3d8e3',
500: '#5c6b7a',
600: '#4a5866',
700: '#3b4651',
800: '#2d353e',
900: '#1f252c',
950: '#121518'
}
},
{
name: 'charcoal',
palette: {
0: '#ffffff',
50: '#f0f0f0',
100: '#e5e5e5',
200: '#d1d1d1',
300: '#b8b8b8',
400: '#9a9a9a',
500: '#7d7d7d',
600: '#666666',
700: '#525252',
800: '#3d3d3d',
900: '#2a2a2a',
950: '#141414'
}
},
{
name: 'soho',
palette: {
0: '#ffffff',
50: '#ececec',
100: '#dedfdf',
200: '#c4c4c6',
300: '#adaeb0',
400: '#97979b',
500: '#7f8084',
600: '#6a6b70',
700: '#55565b',
800: '#3f4046',
900: '#2c2c34',
950: '#16161d'
}
},
{
name: 'viva',
palette: {
0: '#ffffff',
50: '#f3f3f3',
100: '#e7e7e8',
200: '#cfd0d0',
300: '#b7b8b9',
400: '#9fa1a1',
500: '#87898a',
600: '#6e7173',
700: '#565a5b',
800: '#3e4244',
900: '#262b2c',
950: '#0e1315'
}
},
{
name: 'ocean',
palette: {
0: '#ffffff',
50: '#fbfcfc',
100: '#F7F9F8',
200: '#EFF3F2',
300: '#DADEDD',
400: '#B1B7B6',
500: '#828787',
600: '#5F7274',
700: '#415B61',
800: '#29444E',
900: '#183240',
950: '#0c1920'
}
},
{
name: 'light-slate',
palette: {
0: '#ffffff',
50: '#fcfcfd',
100: '#f8fafc',
200: '#f1f5f9',
300: '#e2e8f0',
400: '#cbd5e1',
500: '#94a3b8',
600: '#64748b',
700: '#475569',
800: '#334155',
900: '#1e293b',
950: '#0f172a'
}
},
{
name: 'olive',
palette: {
0: '#ffffff',
50: '#fcfcfb',
100: '#f8f9f6',
200: '#f1f4ed',
300: '#e6eadc',
400: '#d4dfc5',
500: '#6a755e',
600: '#555d4c',
700: '#434a3d',
800: '#333930',
900: '#232824',
950: '#131614'
}
},
{
name: 'crimson',
palette: {
0: '#ffffff',
50: '#fcfbfb',
100: '#f8f5f5',
200: '#f1ebeb',
300: '#e6d9d9',
400: '#d4c3c3',
500: '#755e5e',
600: '#5d4c4c',
700: '#4a3d3d',
800: '#382f2f',
900: '#242020',
950: '#141212'
}
}
];
constructor() {
const initialState = this.loadAppState();
this.appState.set({...initialState});
this.document.documentElement.classList.add('p-dark');
if (isPlatformBrowser(this.platformId)) {
this.onPresetChange();
}
effect(() => {
const state = this.appState();
if (!this.initialized || !state) {
this.initialized = true;
return;
}
this.saveAppState(state);
this.onPresetChange();
}, {allowSignalWrites: true});
}
private loadAppState(): AppState {
if (isPlatformBrowser(this.platformId)) {
const storedState = localStorage.getItem(this.STORAGE_KEY);
if (storedState) {
return JSON.parse(storedState);
}
}
return {
preset: 'Aura',
primary: 'green',
surface: 'neutral',
};
}
private saveAppState(state: AppState): void {
if (isPlatformBrowser(this.platformId)) {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state));
}
}
private getSurfacePalette(surface: string): ColorPalette {
return this.surfaces.find(s => s.name === surface)?.palette ?? {};
}
getPresetExt(): object {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const primaryName = this.appState().primary ?? 'green';
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
const color = presetPalette[primaryName] ?? {};
if (primaryName === 'noir') {
return {
semantic: {
primary: {...surfacePalette},
colorScheme: {
dark: {
primary: {
color: '{primary.50}',
contrastColor: '{primary.950}',
hoverColor: '{primary.200}',
activeColor: '{primary.300}'
},
highlight: {
background: '{primary.50}',
focusBackground: '{primary.300}',
color: '{primary.950}',
focusColor: '{primary.950}'
}
}
}
}
};
}
return {
semantic: {
primary: color,
colorScheme: {
dark: {
primary: {
color: '{primary.400}',
contrastColor: '{surface.900}',
hoverColor: '{primary.300}',
activeColor: '{primary.200}'
},
highlight: {
background: 'color-mix(in srgb, {primary.400}, transparent 84%)',
focusBackground: 'color-mix(in srgb, {primary.400}, transparent 76%)',
color: 'rgba(255,255,255,.87)',
focusColor: 'rgba(255,255,255,.87)'
}
}
}
}
};
}
onPresetChange(): void {
const surfacePalette = this.getSurfacePalette(this.appState().surface ?? 'neutral');
const preset = this.getPresetExt();
$t().preset(Aura).preset(preset).surfacePalette(surfacePalette).use({useDefaultOptions: true});
}
}
@@ -0,0 +1,143 @@
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, finalize, shareReplay, tap} from 'rxjs/operators';
import {API_CONFIG} from '../../core/config/api-config';
import {AppSettings, OidcProviderDetails} from '../model/app-settings.model';
import {AuthService} from './auth.service';
export interface PublicAppSettings {
oidcEnabled: boolean;
oidcProviderDetails: OidcProviderDetails;
}
@Injectable({providedIn: 'root'})
export class AppSettingsService {
private http = inject(HttpClient);
private injector = inject(Injector);
private readonly apiUrl = `${API_CONFIG.BASE_URL}/api/v1/settings`;
private readonly publicApiUrl = `${API_CONFIG.BASE_URL}/api/v1/public-settings`;
private loading$: Observable<AppSettings> | null = null;
private appSettingsSubject = new BehaviorSubject<AppSettings | null>(null);
appSettings$ = this.appSettingsSubject.asObservable().pipe(
tap(state => {
if (!state && !this.loading$) {
this.loading$ = this.fetchAppSettings().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private publicLoading$: Observable<PublicAppSettings> | null = null;
private publicAppSettingsSubject = new BehaviorSubject<PublicAppSettings | null>(null);
publicAppSettings$ = this.publicAppSettingsSubject.asObservable().pipe(
tap(state => {
if (!state && !this.publicLoading$) {
this.publicLoading$ = this.fetchPublicSettings().pipe(
shareReplay(1),
finalize(() => (this.publicLoading$ = null))
);
this.publicLoading$.subscribe();
}
})
);
private fetchAppSettings(): Observable<AppSettings> {
return this.http.get<AppSettings>(this.apiUrl).pipe(
tap(settings => {
this.appSettingsSubject.next(settings);
this.syncPublicSettings(settings);
}),
catchError(err => {
console.error('Error loading app settings:', err);
this.appSettingsSubject.next(null);
throw err;
})
);
}
private fetchPublicSettings(): Observable<PublicAppSettings> {
return this.http.get<PublicAppSettings>(this.publicApiUrl).pipe(
tap(settings => this.publicAppSettingsSubject.next(settings)),
catchError(err => {
console.error('Failed to fetch public settings', err);
throw err;
})
);
}
private syncPublicSettings(appSettings: AppSettings): void {
const updatedPublicSettings: PublicAppSettings = {
oidcEnabled: appSettings.oidcEnabled,
oidcProviderDetails: appSettings.oidcProviderDetails
};
const current = this.publicAppSettingsSubject.value;
if (
!current ||
current.oidcEnabled !== updatedPublicSettings.oidcEnabled ||
JSON.stringify(current.oidcProviderDetails) !== JSON.stringify(updatedPublicSettings.oidcProviderDetails)
) {
this.publicAppSettingsSubject.next(updatedPublicSettings);
}
}
saveSettings(settings: { key: string; newValue: any }[]): Observable<void> {
const payload = settings.map(setting => ({
name: setting.key,
value: setting.newValue
}));
return this.http.put<void>(this.apiUrl, payload).pipe(
tap(() => {
const current = this.appSettingsSubject.value;
if (current) {
settings.forEach(s => (current as any)[s.key] = s.newValue);
this.appSettingsSubject.next({...current});
this.syncPublicSettings(current);
} else {
this.loading$ = this.fetchAppSettings().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
}),
catchError(err => {
console.error('Error saving settings:', err);
return of();
})
);
}
toggleOidcEnabled(enabled: boolean): Observable<void> {
const payload = [{name: 'OIDC_ENABLED', value: enabled}];
return this.http.put<void>(this.apiUrl, payload).pipe(
tap(() => {
const current = this.appSettingsSubject.value;
if (current) {
current.oidcEnabled = enabled;
this.appSettingsSubject.next({...current});
this.syncPublicSettings(current);
}
if (!enabled) {
setTimeout(() => {
const authService = this.injector.get(AuthService);
authService.clearOIDCTokens();
});
}
}),
catchError(err => {
console.error('Error toggling OIDC:', err);
return of();
})
);
}
}
@@ -0,0 +1,109 @@
import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs';
import {RxStompService} from '../websocket/rx-stomp.service';
import {API_CONFIG} from '../../core/config/api-config';
import {createRxStompConfig} from '../websocket/rx-stomp.config';
import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc';
import {Router} from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`;
private rxStompService?: RxStompService;
private http = inject(HttpClient);
private injector = inject(Injector);
private oAuthService = inject(OAuthService);
private oAuthStorage = inject(OAuthStorage);
private router = inject(Router);
public tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
public token$ = this.tokenSubject.asObservable();
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.initializeWebSocketConnection();
}
})
);
}
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, {refreshToken}).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
}
})
);
}
saveInternalTokens(accessToken: string, refreshToken: string): void {
localStorage.setItem('accessToken_Internal', accessToken);
localStorage.setItem('refreshToken_Internal', refreshToken);
this.tokenSubject.next(accessToken);
}
getInternalAccessToken(): string | null {
return localStorage.getItem('accessToken_Internal');
}
getOidcAccessToken(): string | null {
return this.oAuthService.getIdToken();
}
getInternalRefreshToken(): string | null {
return localStorage.getItem('refreshToken_Internal');
}
clearOIDCTokens(): void {
const hasInternalTokens = this.getInternalAccessToken() || this.getInternalRefreshToken();
if (!hasInternalTokens) {
this.oAuthStorage.removeItem("access_token");
this.oAuthStorage.removeItem("refresh_token");
this.oAuthStorage.removeItem("id_token");
this.router.navigate(['/login']);
}
}
logout(): void {
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal');
this.oAuthStorage.removeItem("access_token");
this.oAuthStorage.removeItem("refresh_token");
this.oAuthStorage.removeItem("id_token");
this.tokenSubject.next(null);
this.getRxStompService().deactivate();
this.router.navigate(['/login']);
}
getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
}
initializeWebSocketConnection(): void {
const token = this.getOidcAccessToken() || this.getInternalAccessToken();
if (!token) return;
const stompService = this.getRxStompService();
const config = createRxStompConfig(this);
stompService.updateConfig(config);
stompService.activate();
}
}
export function websocketInitializer(authService: AuthService): () => void {
return () => authService.initializeWebSocketConnection();
}
@@ -0,0 +1,15 @@
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs';
@Injectable({ providedIn: 'root' })
export class BookMetadataHostService {
private bookSwitchRequest$ = new Subject<number>();
requestBookSwitch(bookId: number) {
this.bookSwitchRequest$.next(bookId);
}
get bookSwitches$() {
return this.bookSwitchRequest$.asObservable();
}
}
@@ -0,0 +1,42 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface BookNote {
id: number;
userId: number;
bookId: number;
title: string;
content: string;
createdAt: string;
updatedAt: string;
}
export interface CreateBookNoteRequest {
id?: number;
bookId: number;
title: string;
content: string;
}
@Injectable({
providedIn: 'root'
})
export class BookNoteService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/book-notes`;
private readonly http = inject(HttpClient);
getNotesForBook(bookId: number): Observable<BookNote[]> {
return this.http.get<BookNote[]>(`${this.url}/book/${bookId}`);
}
createOrUpdateNote(request: CreateBookNoteRequest): Observable<BookNote> {
return this.http.post<BookNote>(this.url, request);
}
deleteNote(noteId: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${noteId}`);
}
}
@@ -0,0 +1,25 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface FileMoveRequest {
bookIds: number[];
moves: {
bookId: number;
targetLibraryId: number | null;
}[];
}
@Injectable({
providedIn: 'root'
})
export class FileOperationsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/files`;
private http = inject(HttpClient);
moveFiles(request: FileMoveRequest): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/move`, request);
}
}
@@ -0,0 +1,27 @@
import { Injectable, inject } from '@angular/core';
import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import { IconPickerComponent } from '../components/icon-picker-component/icon-picker-component';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class IconPickerService {
private dialog = inject(DialogService);
open(): Observable<string> {
const isMobile = window.innerWidth <= 768;
const ref: DynamicDialogRef = this.dialog.open(IconPickerComponent, {
header: 'Choose an Icon',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
}
});
return ref.onClose as Observable<string>;
}
}
@@ -0,0 +1,18 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
private loadingSubject = new BehaviorSubject<boolean>(false);
loading$ = this.loadingSubject.asObservable();
show(): void {
this.loadingSubject.next(true);
}
hide(): void {
this.loadingSubject.next(false);
}
}
@@ -0,0 +1,25 @@
import {Injectable} from '@angular/core';
@Injectable({providedIn: 'root'})
export class LocalStorageService {
get<T>(key: string): T | null {
try {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) as T : null;
} catch {
return null;
}
}
set<T>(key: string, value: T): void {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
}
}
remove(key: string): void {
localStorage.removeItem(key);
}
}
@@ -0,0 +1,38 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface MetadataMatchWeights {
title: number;
subtitle: number;
description: number;
publisher: number;
publishedDate: number;
authors: number;
categories: number;
seriesName: number;
seriesNumber: number;
isbn13: number;
isbn10: number;
pageCount: number;
language: number;
amazonRating: number;
amazonReviewCount: number;
goodreadsRating: number;
goodreadsReviewCount: number;
hardcoverRating: number;
hardcoverReviewCount: number;
coverImage: number;
}
@Injectable({providedIn: 'root'})
export class MetadataMatchWeightsService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
private http = inject(HttpClient);
recalculateAll(): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {});
}
}
@@ -0,0 +1,87 @@
import {inject, Injectable, OnDestroy} from '@angular/core';
import {BehaviorSubject, Subject, Subscription} from 'rxjs';
import {MetadataBatchProgressNotification} from '../model/metadata-batch-progress.model';
import {MetadataTaskService} from '../../features/book/service/metadata-task';
import {UserService} from '../../features/settings/user-management/user.service';
import {filter, take} from 'rxjs/operators';
@Injectable({providedIn: 'root'})
export class MetadataProgressService implements OnDestroy {
private progressMap = new Map<string, BehaviorSubject<MetadataBatchProgressNotification>>();
private progressUpdatesSubject = new Subject<MetadataBatchProgressNotification>();
progressUpdates$ = this.progressUpdatesSubject.asObservable();
private activeTasksSubject = new BehaviorSubject<{ [taskId: string]: MetadataBatchProgressNotification }>({});
activeTasks$ = this.activeTasksSubject.asObservable();
private metadataTaskService = inject(MetadataTaskService);
private userService = inject(UserService);
private subscriptions = new Subscription();
constructor() {
const sub = this.userService.userState$
.pipe(
filter(userState => !!userState?.user),
take(1)
)
.subscribe(userState => {
if (!this.hasMetadataPermissions(userState.user)) {
return;
}
const activeTasksSub = this.metadataTaskService.getActiveTasks().subscribe({
next: (tasks) => this.initializeActiveTasks(tasks),
error: (err) => console.warn('Failed to fetch active metadata tasks:', err)
});
this.subscriptions.add(activeTasksSub);
});
this.subscriptions.add(sub);
}
handleIncomingProgress(progress: MetadataBatchProgressNotification): void {
const {taskId} = progress;
if (!this.progressMap.has(taskId)) {
this.progressMap.set(taskId, new BehaviorSubject(progress));
} else {
this.progressMap.get(taskId)!.next(progress);
}
this.progressUpdatesSubject.next(progress);
this.activeTasksSubject.next(this.getActiveTasks());
}
clearTask(taskId: string): void {
this.progressMap.delete(taskId);
this.activeTasksSubject.next(this.getActiveTasks());
}
getActiveTasks(): { [taskId: string]: MetadataBatchProgressNotification } {
const result: { [taskId: string]: MetadataBatchProgressNotification } = {};
this.progressMap.forEach((subject, taskId) => {
result[taskId] = subject.getValue();
});
return result;
}
private hasMetadataPermissions(user: any): boolean {
return !!(user?.permissions?.admin || user?.permissions?.canEditMetadata);
}
private initializeActiveTasks(tasks: MetadataBatchProgressNotification[]): void {
for (const task of tasks) {
this.progressMap.set(task.taskId, new BehaviorSubject(task));
this.progressUpdatesSubject.next(task);
}
this.activeTasksSubject.next(this.getActiveTasks());
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
this.progressMap.forEach(subject => subject.complete());
this.progressUpdatesSubject.complete();
this.activeTasksSubject.complete();
}
}
@@ -0,0 +1,60 @@
import {Injectable, inject} from '@angular/core';
import {AppSettingsService} from './app-settings.service';
import {MessageService} from 'primeng/api';
import {Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SettingsHelperService {
private readonly appSettingsService = inject(AppSettingsService);
private readonly messageService = inject(MessageService);
saveSetting(key: string, value: unknown): Observable<void> {
const observable = this.appSettingsService.saveSettings([{key, newValue: value}]);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
console.error('Failed to save setting:', error);
this.showErrorMessage();
}
});
return observable;
}
saveMultipleSettings(settings: { key: string, newValue: unknown }[]): Observable<void> {
const observable = this.appSettingsService.saveSettings(settings);
observable.subscribe({
next: () => this.showSuccessMessage(),
error: (error) => {
console.error('Failed to save settings:', error);
this.showErrorMessage();
}
});
return observable;
}
private showSuccessMessage(): void {
this.messageService.add({
severity: 'success',
summary: 'Settings Saved',
detail: 'The settings were successfully saved!'
});
}
private showErrorMessage(): void {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'There was an error saving the settings.'
});
}
showMessage(severity: 'success' | 'error', summary: string, detail: string): void {
this.messageService.add({severity, summary, detail});
}
}
@@ -0,0 +1,28 @@
import {Injectable, inject} from '@angular/core';
import {AuthService} from './auth.service';
import {UserService} from '../../features/settings/user-management/user.service';
import {filter, catchError} from 'rxjs/operators';
import {of} from 'rxjs';
import {OAuthService} from 'angular-oauth2-oidc';
@Injectable({providedIn: 'root'})
export class StartupService {
private authService = inject(AuthService);
private userService = inject(UserService);
load(): Promise<void> {
this.authService.token$
.pipe(filter(t => !!t))
.subscribe(() => {
this.userService.getMyself()
.pipe(catchError(() => of(null)))
.subscribe(user => {
if (user) {
this.userService.setInitialUser(user);
}
});
});
return Promise.resolve();
}
}
@@ -0,0 +1,26 @@
import {inject, Injectable} from '@angular/core';
import {MessageService} from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class ToastService {
private messageService = inject(MessageService);
showSuccess(summary: string, detail: string) {
this.messageService.add({ severity: 'success', summary, detail });
}
showError(summary: string, detail: string) {
this.messageService.add({ severity: 'error', summary, detail });
}
showInfo(summary: string, detail: string) {
this.messageService.add({ severity: 'info', summary, detail });
}
showWarning(summary: string, detail: string) {
this.messageService.add({ severity: 'warn', summary, detail });
}
}
@@ -0,0 +1,55 @@
import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class UrlHelperService {
private readonly baseUrl = API_CONFIG.BASE_URL;
private readonly mediaBaseUrl = `${this.baseUrl}/api/v1/media`;
private authService = inject(AuthService);
private getToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
private appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getThumbnailUrl(bookId: number, coverUpdatedOn?: string): string {
if (!coverUpdatedOn) return 'assets/images/missing-cover.jpg';
const url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail?${coverUpdatedOn}`;
return this.appendToken(url);
}
getCoverUrl(bookId: number, coverUpdatedOn?: string): string {
if (!coverUpdatedOn) return 'assets/images/missing-cover.jpg';
const url = `${this.mediaBaseUrl}/book/${bookId}/cover?${coverUpdatedOn}`;
return this.appendToken(url);
}
getBackupCoverUrl(bookId: number): string {
const url = `${this.mediaBaseUrl}/book/${bookId}/backup-cover`;
return this.appendToken(url);
}
getBookdropCoverUrl(bookdropId: number): string {
const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`;
return this.appendToken(url);
}
getBackgroundImageUrl(lastUpdated?: number): string {
let url = `${this.mediaBaseUrl}/background`;
if (lastUpdated) {
url += `?t=${lastUpdated}`;
}
const token = this.getToken();
if (token) {
url += `${url.includes('?') ? '&' : '?'}token=${token}`;
}
return url;
}
}
@@ -0,0 +1,34 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import {API_CONFIG} from '../../core/config/api-config';
export interface AppVersion {
current: string;
latest: string;
}
export interface ReleaseNote {
version: string;
name: string;
changelog: string;
url: string;
publishedAt: string;
}
@Injectable({
providedIn: 'root'
})
export class VersionService {
private versionUrl = `${API_CONFIG.BASE_URL}/api/v1/version`;
constructor(private http: HttpClient) {}
getVersion(): Observable<AppVersion> {
return this.http.get<AppVersion>(this.versionUrl);
}
getChangelog(): Observable<ReleaseNote[]> {
return this.http.get<ReleaseNote[]>(`${this.versionUrl}/changelog`);
}
}