Implement clean logout to fully clear app state and tokens

This commit is contained in:
aditya.chandel
2025-08-11 13:30:37 -06:00
committed by Aditya Chandel
parent 964b8e7f67
commit ec5157464a
32 changed files with 638 additions and 425 deletions
@@ -20,9 +20,9 @@
} }
</p> </p>
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
@if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED && @if (entityType !== EntityType.ALL_BOOKS && entityType !== EntityType.UNSHELVED &&
(userData.permissions.admin || userData.permissions.canManipulateLibrary)) { (userState.user!.permissions.admin || userState.user!.permissions.canManipulateLibrary)) {
<div class="ml-2 flex-shrink-0"> <div class="ml-2 flex-shrink-0">
<p-button <p-button
icon="pi pi-ellipsis-v" icon="pi pi-ellipsis-v"
@@ -286,13 +286,13 @@
} }
} }
@if (selectedBooks.size > 0) { @if (selectedBooks.size > 0) {
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
<div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]> <div class="book-browser-footer bg-[var(--card-background)] bg-opacity-10" [@slideInOut]>
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<div class="flex"> <div class="flex">
@if (entityType$ | async; as entityType) { @if (entityType$ | async; as entityType) {
<div class="flex gap-2 md:gap-6 pr-2"> <div class="flex gap-2 md:gap-6 pr-2">
@if (userData.permissions.canEditMetadata) { @if (userState.user!.permissions.canEditMetadata) {
<p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/> <p-menu #menu [model]="metadataMenuItems" [popup]="true" appendTo="body" class="hidden"/>
<p-button <p-button
(click)="menu.toggle($event)" (click)="menu.toggle($event)"
@@ -323,7 +323,7 @@
tooltipPosition="top"> tooltipPosition="top">
</p-button> </p-button>
} }
@if (userData.permissions.canEditMetadata) { @if (userState.user!.permissions.canEditMetadata) {
<p-button <p-button
outlined="true" outlined="true"
icon="pi pi-lock" icon="pi pi-lock"
@@ -375,7 +375,7 @@
</div> </div>
</div> </div>
@if (userData?.permissions?.admin || userData?.permissions?.canDeleteBook) { @if (userState?.user?.permissions?.admin || userState?.user?.permissions?.canDeleteBook) {
<p-divider layout="vertical"></p-divider> <p-divider layout="vertical"></p-divider>
<p-button <p-button
outlined="true" outlined="true"
@@ -45,7 +45,7 @@ import {MultiSelect} from 'primeng/multiselect';
import {TableColumnPreferenceService} from './table-column-preference-service'; import {TableColumnPreferenceService} from './table-column-preference-service';
import {TieredMenu} from 'primeng/tieredmenu'; import {TieredMenu} from 'primeng/tieredmenu';
import {BookMenuService} from '../../service/book-menu.service'; import {BookMenuService} from '../../service/book-menu.service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf-service'; import {MagicShelf, MagicShelfService} from '../../../magic-shelf.service';
import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service'; import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service';
import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component'; import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component';
@@ -136,7 +136,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
rawFilterParamFromUrl: string | null = null; rawFilterParamFromUrl: string | null = null;
hasSearchTerm = false; hasSearchTerm = false;
visibleColumns: { field: string; header: string }[] = []; visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences!: EntityViewPreferences; entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined; currentViewMode: string | undefined;
lastAppliedSort: SortOption | null = null; lastAppliedSort: SortOption | null = null;
private settingFiltersFromUrl = false; private settingFiltersFromUrl = false;
@@ -161,7 +161,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
ngOnInit(): void { ngOnInit(): void {
this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe(); this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.bookService.loadBooks();
const currentPath = this.activatedRoute.snapshot.routeConfig?.path; const currentPath = this.activatedRoute.snapshot.routeConfig?.path;
if (currentPath === 'all-books' || currentPath === 'unshelved-books') { if (currentPath === 'all-books' || currentPath === 'unshelved-books') {
@@ -206,7 +205,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
combineLatest({ combineLatest({
paramMap: this.activatedRoute.queryParamMap, paramMap: this.activatedRoute.queryParamMap,
user: this.userService.userState$.pipe( user: this.userService.userState$.pipe(
filter((user): user is NonNullable<typeof user> => !!user), filter(userState => !!userState?.user && userState.loaded),
take(1) take(1)
) )
}).subscribe(({paramMap, user}) => { }).subscribe(({paramMap, user}) => {
@@ -250,12 +249,12 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.currentFilterLabel = 'All Books'; this.currentFilterLabel = 'All Books';
} }
this.entityViewPreferences = user.userSettings?.entityViewPreferences; this.entityViewPreferences = user.user?.userSettings?.entityViewPreferences;
const globalPrefs = this.entityViewPreferences?.global; const globalPrefs = this.entityViewPreferences?.global;
const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined; const currentEntityTypeStr = this.entityType ? this.entityType.toString().toUpperCase() : undefined;
this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor); this.coverScalePreferenceService.initScaleValue(this.coverScalePreferenceService.scaleFactor);
this.filterSortPreferenceService.initValue(user?.userSettings?.filterSortingMode); this.filterSortPreferenceService.initValue(user.user?.userSettings?.filterSortingMode);
this.columnPreferenceService.initPreferences(user.userSettings?.tableColumnPreference); this.columnPreferenceService.initPreferences(user.user?.userSettings?.tableColumnPreference);
this.visibleColumns = this.columnPreferenceService.visibleColumns; this.visibleColumns = this.columnPreferenceService.visibleColumns;
@@ -67,12 +67,12 @@ export class BookCardComponent implements OnInit, OnDestroy {
ngOnInit(): void { ngOnInit(): void {
this.userService.userState$ this.userService.userState$
.pipe( .pipe(
filter(user => !!user), filter(userState => !!userState),
takeUntil(this.destroy$) takeUntil(this.destroy$)
) )
.subscribe(user => { .subscribe(userState => {
this.userPermissions = user.permissions; this.userPermissions = userState.user?.permissions;
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route'; this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
this.initMenu(); this.initMenu();
}); });
} }
@@ -13,7 +13,7 @@ import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton'; import {SelectButton} from 'primeng/selectbutton';
import {UserService} from '../../../../settings/user-management/user.service'; import {UserService} from '../../../../settings/user-management/user.service';
import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service'; import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service';
import {MagicShelf} from '../../../../magic-shelf-service'; import {MagicShelf} from '../../../../magic-shelf.service';
import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component'; import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component';
import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service'; import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service';
@@ -75,11 +75,11 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges {
ngOnInit(): void { ngOnInit(): void {
this.userService.userState$ this.userService.userState$
.pipe( .pipe(
filter(user => !!user), filter(userState => !!userState),
takeUntil(this.destroy$) takeUntil(this.destroy$)
) )
.subscribe(user => { .subscribe(userState => {
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route'; this.metadataCenterViewMode = userState?.user?.userSettings.metadataCenterViewMode ?? 'route';
}); });
this.setScrollHeight(); this.setScrollHeight();
@@ -1,27 +1,31 @@
import {BookFilter} from './BookFilter'; import {BookFilter} from './BookFilter';
import {Observable, BehaviorSubject} from 'rxjs'; import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {BookState} from '../../../model/state/book-state.model'; import {BookState} from '../../../model/state/book-state.model';
import {map, debounceTime, filter, take} from 'rxjs/operators'; import {debounceTime, filter, map, takeUntil} from 'rxjs/operators';
import {Book} from '../../../model/book.model'; import {Book} from '../../../model/book.model';
import {inject, Injectable} from '@angular/core'; import {inject, Injectable, OnDestroy} from '@angular/core';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {UserService} from '../../../../settings/user-management/user.service'; import {UserService} from '../../../../settings/user-management/user.service';
@Injectable({providedIn: 'root'}) @Injectable({providedIn: 'root'})
export class SeriesCollapseFilter implements BookFilter { export class SeriesCollapseFilter implements BookFilter, OnDestroy {
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false); private readonly seriesCollapseSubject = new BehaviorSubject<boolean>(false);
readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable(); readonly seriesCollapse$ = this.seriesCollapseSubject.asObservable();
private destroy$ = new Subject<void>();
private hasUserToggled = false; private hasUserToggled = false;
constructor() { constructor() {
this.userService.userState$ this.userService.userState$
.pipe(filter(user => !!user), take(1)) .pipe(
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe(user => { .subscribe(user => {
const prefs = user.userSettings?.entityViewPreferences; const prefs = user.user?.userSettings?.entityViewPreferences;
const initialCollapsed = prefs?.global?.seriesCollapsed ?? false; const initialCollapsed = prefs?.global?.seriesCollapsed ?? false;
this.seriesCollapseSubject.next(initialCollapsed); this.seriesCollapseSubject.next(initialCollapsed);
}); });
@@ -102,4 +106,9 @@ export class SeriesCollapseFilter implements BookFilter {
life: 1500 life: 1500
}); });
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }
@@ -1,17 +1,13 @@
import {Component, inject, Input, OnInit} from '@angular/core'; import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Book} from '../../model/book.model'; import {Book} from '../../model/book.model';
import {UrlHelperService} from '../../../utilities/service/url-helper.service'; import {UrlHelperService} from '../../../utilities/service/url-helper.service';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {BookMetadataCenterComponent} from '../../../metadata/book-metadata-center-component/book-metadata-center.component';
import {BookService} from '../../service/book.service';
import {DialogService} from 'primeng/dynamicdialog';
import {UserService} from '../../../settings/user-management/user.service'; import {UserService} from '../../../settings/user-management/user.service';
import {EmailService} from '../../../settings/email/email.service';
import {ConfirmationService, MessageService} from 'primeng/api';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {filter} from 'rxjs'; import {filter, Subject} from 'rxjs';
import {NgClass} from '@angular/common'; import {NgClass} from '@angular/common';
import {BookMetadataHostService} from '../../../utilities/service/book-metadata-host-service'; import {BookMetadataHostService} from '../../../utilities/service/book-metadata-host-service';
import {takeUntil} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-book-card-lite-component', selector: 'app-book-card-lite-component',
@@ -22,7 +18,7 @@ import {BookMetadataHostService} from '../../../utilities/service/book-metadata-
templateUrl: './book-card-lite-component.html', templateUrl: './book-card-lite-component.html',
styleUrl: './book-card-lite-component.scss' styleUrl: './book-card-lite-component.scss'
}) })
export class BookCardLiteComponent implements OnInit { export class BookCardLiteComponent implements OnInit, OnDestroy {
@Input() book!: Book; @Input() book!: Book;
private router = inject(Router); private router = inject(Router);
@@ -30,14 +26,19 @@ export class BookCardLiteComponent implements OnInit {
private userService = inject(UserService); private userService = inject(UserService);
private bookMetadataHostService = inject(BookMetadataHostService); private bookMetadataHostService = inject(BookMetadataHostService);
private destroy$ = new Subject<void>();
private metadataCenterViewMode: 'route' | 'dialog' = 'route'; private metadataCenterViewMode: 'route' | 'dialog' = 'route';
isHovered: boolean = false; isHovered: boolean = false;
ngOnInit(): void { ngOnInit(): void {
this.userService.userState$ this.userService.userState$
.pipe(filter(user => !!user)) .pipe(
filter(userState => !!userState),
takeUntil(this.destroy$)
)
.subscribe((user) => { .subscribe((user) => {
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route'; this.metadataCenterViewMode = user?.user?.userSettings.metadataCenterViewMode ?? 'route';
}); });
} }
@@ -50,4 +51,9 @@ export class BookCardLiteComponent implements OnInit {
this.bookMetadataHostService.requestBookSwitch(book.id); this.bookMetadataHostService.requestBookSwitch(book.id);
} }
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }
@@ -1,7 +1,7 @@
import {inject, Injectable} from '@angular/core'; import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs'; import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http'; import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, filter, map, tap} from 'rxjs/operators'; import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model';
import {BookState} from '../model/state/book-state.model'; import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../config/api-config'; import {API_CONFIG} from '../../config/api-config';
@@ -9,6 +9,7 @@ import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model'; import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type'; import {ResetProgressType, ResetProgressTypes} from '../../shared/constants/reset-progress-type';
import {AuthService} from '../../core/service/auth.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -17,22 +18,57 @@ export class BookService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private messageService = inject(MessageService);
private authService = inject(AuthService);
private bookStateSubject = new BehaviorSubject<BookState>({ private bookStateSubject = new BehaviorSubject<BookState>({
books: null, books: null,
loaded: false, loaded: false,
error: null, error: null,
}); });
bookState$ = this.bookStateSubject.asObservable();
private http = inject(HttpClient); private loading$: Observable<Book[]> | null = null;
private messageService = inject(MessageService);
loadBooks(): void { constructor() {
const currentState = this.bookStateSubject.value; this.authService.token$.pipe(
if (currentState.loaded && this.bookStateSubject.value.books != null) { distinctUntilChanged()
return; ).subscribe(token => {
} if (token === null) {
this.http.get<Book[]>(this.url).pipe( this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.bookStateSubject.value;
if (current.loaded && !current.books) {
this.bookStateSubject.next({
books: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
bookState$ = this.bookStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchBooks().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchBooks(): Observable<Book[]> {
return this.http.get<Book[]>(this.url).pipe(
tap(books => { tap(books => {
this.bookStateSubject.next({ this.bookStateSubject.next({
books: books || [], books: books || [],
@@ -41,14 +77,15 @@ export class BookService {
}); });
}), }),
catchError(error => { catchError(error => {
const curr = this.bookStateSubject.value;
this.bookStateSubject.next({ this.bookStateSubject.next({
books: null, books: curr.books,
loaded: true, loaded: true,
error: error.message, error: error.message,
}); });
return of(null); throw error;
}) })
).subscribe(); );
} }
getBookByIdFromState(bookId: number): Book | undefined { getBookByIdFromState(bookId: number): Book | undefined {
@@ -10,7 +10,7 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component'; import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component';
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component'; import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
import {MagicShelf, MagicShelfService} from '../../magic-shelf-service'; import {MagicShelf, MagicShelfService} from '../../magic-shelf.service';
import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component'; import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component';
@Injectable({ @Injectable({
@@ -1,119 +1,145 @@
import {inject, Injectable} from '@angular/core'; import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of, tap} from 'rxjs';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {catchError, map} from 'rxjs/operators'; import {BehaviorSubject, Observable, of} from 'rxjs';
import {Library} from '../model/library.model'; import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {BookService} from './book.service';
import {LibraryState} from '../model/state/library-state.model';
import {API_CONFIG} from '../../config/api-config';
@Injectable({ import {Library} from '../model/library.model';
providedIn: 'root', import {LibraryState} from '../model/state/library-state.model';
}) import {BookService} from './book.service';
import {API_CONFIG} from '../../config/api-config';
import {AuthService} from '../../core/service/auth.service';
@Injectable({providedIn: 'root'})
export class LibraryService { export class LibraryService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
private http = inject(HttpClient);
private bookService = inject(BookService);
private authService = inject(AuthService);
private libraryStateSubject = new BehaviorSubject<LibraryState>({ private libraryStateSubject = new BehaviorSubject<LibraryState>({
libraries: null, libraries: null,
loaded: false, loaded: false,
error: null, error: null,
}); });
libraryState$ = this.libraryStateSubject.asObservable();
private http = inject(HttpClient); private loading$: Observable<Library[]> | null = null;
private bookService = inject(BookService);
constructor() { constructor() {
this.loadLibraries(); this.authService.token$.pipe(
} distinctUntilChanged()
).subscribe(token => {
private loadLibraries(): void { if (token === null) {
this.http.get<Library[]>(this.url).pipe(
catchError(error => {
this.libraryStateSubject.next({ this.libraryStateSubject.next({
libraries: null, libraries: null,
loaded: true, loaded: true,
error: error.message, error: null,
}); });
return of([]); this.loading$ = null;
}) } else {
).subscribe(libraries => { const current = this.libraryStateSubject.value;
this.libraryStateSubject.next({ if (current.loaded && !current.libraries) {
libraries, this.libraryStateSubject.next({
loaded: true, libraries: null,
error: null, loaded: false,
}); error: null,
});
this.loading$ = null;
}
}
}); });
} }
doesLibraryExistByName(name: string): boolean { libraryState$ = this.libraryStateSubject.asObservable().pipe(
const libraries = this.libraryStateSubject.value.libraries || []; tap(state => {
return libraries.some(library => library.name === name); if (!state.loaded && !state.error && !this.loading$) {
} this.loading$ = this.fetchLibraries().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
findLibraryById(id: number): Library | undefined { private fetchLibraries(): Observable<Library[]> {
return this.libraryStateSubject.value.libraries?.find(library => library.id === id); return this.http.get<Library[]>(this.url).pipe(
} tap(libs => this.libraryStateSubject.next({libraries: libs, loaded: true, error: null})),
catchError(err => {
createLibrary(newLibrary: Library): Observable<Library> { const current = this.libraryStateSubject.value;
return this.http.post<Library>(this.url, newLibrary).pipe( this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
map(createdLibrary => { throw err;
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? [...currentState.libraries, createdLibrary] : [createdLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
return createdLibrary;
}),
catchError(error => {
throw error;
}) })
); );
} }
updateLibrary(library: Library, libraryId: number | undefined): Observable<Library> { createLibrary(lib: Library): Observable<Library> {
return this.http.put<Library>(`${this.url}/${libraryId}`, library).pipe( return this.http.post<Library>(this.url, lib).pipe(
map(updatedLibrary => { map(created => {
const currentState = this.libraryStateSubject.value; const curr = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary => const updated = curr.libraries ? [...curr.libraries, created] : [created];
existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary]; this.libraryStateSubject.next({...curr, libraries: updated});
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries,}); return created;
return updatedLibrary;
}),
catchError(error => {
throw error;
}) })
); );
} }
deleteLibrary(libraryId: number): Observable<void> { updateLibrary(lib: Library, id?: number): Observable<Library> {
return this.http.delete<void>(`${this.url}/${libraryId}`).pipe( return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
deleteLibrary(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => { tap(() => {
this.bookService.removeBooksByLibraryId(libraryId); this.bookService.removeBooksByLibraryId(id);
const currentState = this.libraryStateSubject.value; const curr = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries?.filter(library => library.id !== libraryId) || []; const filtered = curr.libraries?.filter(l => l.id !== id) || [];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries}); this.libraryStateSubject.next({...curr, libraries: filtered});
}), }),
catchError(error => { catchError(err => {
const currentState = this.libraryStateSubject.value; const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...currentState, error: error.message}); this.libraryStateSubject.next({...curr, error: err.message});
return of(); return of();
}) })
); );
} }
refreshLibrary(libraryId: number): Observable<void> { refreshLibrary(id: number): Observable<void> {
return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {}).pipe( return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
catchError(error => { catchError(err => {
const currentState = this.libraryStateSubject.value; const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...currentState, error: error.message}); this.libraryStateSubject.next({...curr, error: err.message});
throw error; throw err;
}) })
); );
} }
getBookCount(libraryId: number): Observable<number> { updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
return this.bookService.bookState$.pipe( return this.http
map(state => (state.books || []).filter(book => book.libraryId === libraryId).length) .patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
); .pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
doesLibraryExistByName(name: string): boolean {
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
}
findLibraryById(id: number): Library | undefined {
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
} }
getLibrariesFromState(): Library[] { getLibrariesFromState(): Library[] {
@@ -121,28 +147,14 @@ export class LibraryService {
} }
getLibraryPathById(pathId: number): string | undefined { getLibraryPathById(pathId: number): string | undefined {
const libraries = this.libraryStateSubject.value.libraries || []; return this.libraryStateSubject.value.libraries
for (const library of libraries) { ?.find(lib => lib.paths.some(p => p.id === pathId))
const match = library.paths.find(p => p.id === pathId); ?.paths.find(p => p.id === pathId)?.path;
if (match) {
return match.path;
}
}
return undefined;
} }
updateLibraryFileNamingPattern(libraryId: number, fileNamingPattern: string): Observable<Library> { getBookCount(libraryId: number): Observable<number> {
return this.http.patch<Library>(`${this.url}/${libraryId}/file-naming-pattern`, { fileNamingPattern }).pipe( return this.bookService.bookState$.pipe(
map(updatedLibrary => { map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
const currentState = this.libraryStateSubject.value;
const updatedLibraries = currentState.libraries ? currentState.libraries.map(existingLibrary =>
existingLibrary.id === updatedLibrary.id ? updatedLibrary : existingLibrary) : [updatedLibrary];
this.libraryStateSubject.next({...currentState, libraries: updatedLibraries});
return updatedLibrary;
}),
catchError(error => {
throw error;
})
); );
} }
} }
@@ -1,108 +1,96 @@
import {inject, Injectable} from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of, tap } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Shelf } from '../model/shelf.model'; import { BehaviorSubject, Observable, of } from 'rxjs';
import { SortOption } from '../model/sort.model'; import { tap, catchError, map, shareReplay, finalize } from 'rxjs/operators';
import { BookService } from './book.service';
import { ShelfState } from '../model/state/shelf-state.model';
import {API_CONFIG} from '../../config/api-config';
import {Library} from '../model/library.model';
@Injectable({ import { Shelf } from '../model/shelf.model';
providedIn: 'root', import { ShelfState } from '../model/state/shelf-state.model';
}) import { BookService } from './book.service';
import { API_CONFIG } from '../../config/api-config';
@Injectable({ providedIn: 'root' })
export class ShelfService { export class ShelfService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`; private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
private http = inject(HttpClient);
private bookService = inject(BookService);
private shelfStateSubject = new BehaviorSubject<ShelfState>({ private shelfStateSubject = new BehaviorSubject<ShelfState>({
shelves: null, shelves: null,
loaded: false, loaded: false,
error: null, error: null,
}); });
shelfState$ = this.shelfStateSubject.asObservable();
private http = inject(HttpClient); private loading$: Observable<Shelf[]> | null = null;
private bookService = inject(BookService);
constructor() { shelfState$ = this.shelfStateSubject.asObservable().pipe(
this.loadShelves(); tap(state => {
} if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private loadShelves(): void { private fetchShelves(): Observable<Shelf[]> {
this.http.get<Shelf[]>(this.url).pipe( return this.http.get<Shelf[]>(this.url).pipe(
catchError(error => { tap(shelves => this.shelfStateSubject.next({ shelves, loaded: true, error: null })),
this.shelfStateSubject.next({ catchError(err => {
shelves: null, const curr = this.shelfStateSubject.value;
loaded: true, this.shelfStateSubject.next({ shelves: curr.shelves, loaded: true, error: err.message });
error: error.message, throw err;
});
return of([]);
}) })
).subscribe(shelves => { );
this.shelfStateSubject.next({
shelves,
loaded: true,
error: null,
});
});
}
getShelfById(shelfId: number): Shelf | undefined {
let shelfState = this.shelfStateSubject.value;
return shelfState.shelves?.find(shelf => shelf.id === shelfId);
} }
createShelf(shelf: Shelf): Observable<Shelf> { createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe( return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => { map(newShelf => {
const currentState = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves ? [...currentState.shelves, newShelf] : [newShelf]; const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves }); this.shelfStateSubject.next({ ...curr, shelves: updated });
return newShelf; return newShelf;
}),
catchError(error => {
const currentState = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message });
throw error;
}) })
); );
} }
updateShelf(shelf: Shelf, shelfId: number | undefined): Observable<Shelf> { updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${shelfId}`, shelf).pipe( return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
map(updatedShelf => { map(updated => {
const currentState = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves ? currentState.shelves.map(existingShelf => const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
existingShelf.id === updatedShelf.id ? updatedShelf : existingShelf) : [updatedShelf]; this.shelfStateSubject.next({ ...curr, shelves: list });
this.shelfStateSubject.next({...currentState, shelves: updatedShelves,}); return updated;
return updatedShelf;
}),
catchError(error => {
throw error;
}) })
); );
} }
deleteShelf(shelfId: number): Observable<void> { deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${shelfId}`).pipe( return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => { tap(() => {
this.bookService.removeBooksFromShelf(shelfId); this.bookService.removeBooksFromShelf(id);
const currentState = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
const updatedShelves = currentState.shelves?.filter(shelf => shelf.id !== shelfId) || []; const filtered = curr.shelves?.filter(s => s.id !== id) || [];
this.shelfStateSubject.next({ ...currentState, shelves: updatedShelves }); this.shelfStateSubject.next({ ...curr, shelves: filtered });
}), }),
catchError(error => { catchError(err => {
const currentState = this.shelfStateSubject.value; const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({ ...currentState, error: error.message }); this.shelfStateSubject.next({ ...curr, error: err.message });
return of(); return of();
}) })
); );
} }
getShelfById(id: number): Shelf | undefined {
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
}
getBookCount(shelfId: number): Observable<number> { getBookCount(shelfId: number): Observable<number> {
return this.bookService.bookState$.pipe( return this.bookService.bookState$.pipe(
map(state => map(state =>
(state.books || []).filter(book => book.shelves?.some(shelf => shelf.id === shelfId)).length (state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length
) )
); );
} }
@@ -110,7 +98,7 @@ export class ShelfService {
getUnshelvedBookCount(): Observable<number> { getUnshelvedBookCount(): Observable<number> {
return this.bookService.bookState$.pipe( return this.bookService.bookState$.pipe(
map(state => map(state =>
(state.books || []).filter(book => !book.shelves || book.shelves.length === 0).length (state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
) )
); );
} }
@@ -1,6 +1,6 @@
import {inject, Injectable, Injector} from '@angular/core'; import {inject, Injectable, Injector} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs'; import {BehaviorSubject, Observable, Subject, tap} from 'rxjs';
import {RxStompService} from '../../shared/websocket/rx-stomp.service'; import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {API_CONFIG} from '../../config/api-config'; import {API_CONFIG} from '../../config/api-config';
import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config'; import {createRxStompConfig} from '../../shared/websocket/rx-stomp.config';
@@ -23,6 +23,9 @@ export class AuthService {
private tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken()); private tokenSubject = new BehaviorSubject<string | null>(this.getOidcAccessToken() || this.getInternalAccessToken());
public token$ = this.tokenSubject.asObservable(); public token$ = this.tokenSubject.asObservable();
private logoutSubject = new Subject<void>();
public logout$ = this.logoutSubject.asObservable();
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> { 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( return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => { tap((response) => {
@@ -78,6 +81,7 @@ export class AuthService {
localStorage.removeItem('accessToken_Internal'); localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('refreshToken_Internal'); localStorage.removeItem('refreshToken_Internal');
this.tokenSubject.next(null); this.tokenSubject.next(null);
this.logoutSubject.next();
this.getRxStompService().deactivate(); this.getRxStompService().deactivate();
if (this.oAuthService.clientId) { if (this.oAuthService.clientId) {
this.oAuthService.logOut(); this.oAuthService.logOut();
@@ -7,7 +7,7 @@
<div> <div>
@if (isLibrariesEmpty$ | async) { @if (isLibrariesEmpty$ | async) {
<div class="dashboard-no-library"> <div class="dashboard-no-library">
@if ((userService.userState$ | async)?.permissions; as permissions) { @if ((userService.userState$ | async)?.user?.permissions; as permissions) {
<div> <div>
@if (permissions.admin || permissions.canManipulateLibrary) { @if (permissions.admin || permissions.canManipulateLibrary) {
<div> <div>
@@ -46,7 +46,6 @@ export class MainDashboardComponent implements OnInit {
); );
ngOnInit(): void { ngOnInit(): void {
this.bookService.loadBooks();
this.lastReadBooks$ = this.bookService.bookState$.pipe( this.lastReadBooks$ = this.bookService.bookState$.pipe(
map((state: BookState) => ( map((state: BookState) => (
@@ -12,7 +12,7 @@ import {AppVersion, VersionService} from '../../../core/service/version.service'
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component'; import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component';
import {UserService} from '../../../settings/user-management/user.service'; import {UserService} from '../../../settings/user-management/user.service';
import {MagicShelf, MagicShelfService, MagicShelfState} from '../../../magic-shelf-service'; import {MagicShelfService, MagicShelfState} from '../../../magic-shelf.service';
@Component({ @Component({
selector: 'app-menu', selector: 'app-menu',
@@ -50,15 +50,15 @@ export class AppMenuComponent implements OnInit {
}); });
this.userService.userState$.pipe( this.userService.userState$.pipe(
filter(settings => !!settings)) filter(userState => !!userState?.user && userState.loaded))
.subscribe(user => { .subscribe(userState => {
if (user?.userSettings.sidebarLibrarySorting) { if (userState.user?.userSettings.sidebarLibrarySorting) {
this.librarySortField = this.validateSortField(user.userSettings.sidebarLibrarySorting.field); this.librarySortField = this.validateSortField(userState.user.userSettings.sidebarLibrarySorting.field);
this.librarySortOrder = this.validateSortOrder(user.userSettings.sidebarLibrarySorting.order); this.librarySortOrder = this.validateSortOrder(userState.user.userSettings.sidebarLibrarySorting.order);
} }
if (user?.userSettings.sidebarShelfSorting) { if (userState.user?.userSettings.sidebarShelfSorting) {
this.shelfSortField = this.validateSortField(user.userSettings.sidebarShelfSorting.field); this.shelfSortField = this.validateSortField(userState.user.userSettings.sidebarShelfSorting.field);
this.shelfSortOrder = this.validateSortOrder(user.userSettings.sidebarShelfSorting.order); this.shelfSortOrder = this.validateSortOrder(userState.user.userSettings.sidebarShelfSorting.order);
} }
this.initMenus(); this.initMenus();
}); });
@@ -67,10 +67,10 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
} }
constructor(public router: Router, private menuService: MenuService, private userService: UserService, private dialogLauncher: DialogLauncherService) { constructor(public router: Router, private menuService: MenuService, private userService: UserService, private dialogLauncher: DialogLauncherService) {
this.userService.userState$.subscribe(userData => { this.userService.userState$.subscribe(userState => {
if (userData) { if (userState?.user) {
this.canManipulateLibrary = userData.permissions.canManipulateLibrary; this.canManipulateLibrary = userState.user.permissions.canManipulateLibrary;
this.admin = userData.permissions.admin; this.admin = userState.user.permissions.admin;
} }
}); });
this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => { this.menuSourceSubscription = this.menuService.menuSource$.subscribe(value => {
@@ -29,18 +29,18 @@
<app-book-searcher class="md:block flex-grow"></app-book-searcher> <app-book-searcher class="md:block flex-grow"></app-book-searcher>
<ul class="topbar-items hidden md:flex items-center gap-3 ml-auto pl-4"> <ul class="topbar-items hidden md:flex items-center gap-3 ml-auto pl-4">
<div class="flex gap-6"> <div class="flex gap-6">
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
<li> <li>
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) { @if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="openLibraryCreatorDialog()" pTooltip="Create New Library" tooltipPosition="bottom"> <a class="topbar-item" (click)="openLibraryCreatorDialog()" pTooltip="Create New Library" tooltipPosition="bottom">
<i class="pi pi-plus-circle text-surface-100"></i> <i class="pi pi-plus-circle text-surface-100"></i>
</a> </a>
} }
</li> </li>
} }
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
<li> <li>
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) { @if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<a class="topbar-item" (click)="openFileUploadDialog()" pTooltip="Upload Book" tooltipPosition="bottom"> <a class="topbar-item" (click)="openFileUploadDialog()" pTooltip="Upload Book" tooltipPosition="bottom">
<i class="pi pi-upload text-surface-100"></i> <i class="pi pi-upload text-surface-100"></i>
</a> </a>
@@ -137,8 +137,8 @@
/> />
<p-popover #mobileMenu> <p-popover #mobileMenu>
<ul class="flex flex-col gap-1 w-48"> <ul class="flex flex-col gap-1 w-48">
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
@if (userData.permissions.canManipulateLibrary || userData.permissions.admin) { @if (userState.user?.permissions?.canManipulateLibrary || userState.user?.permissions?.admin) {
<li> <li>
<button <button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded" class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
@@ -10,7 +10,7 @@ import {InputNumber} from 'primeng/inputnumber';
import {ReadStatus} from '../book/model/book.model'; import {ReadStatus} from '../book/model/book.model';
import {LibraryService} from '../book/service/library.service'; import {LibraryService} from '../book/service/library.service';
import {Library} from '../book/model/library.model'; import {Library} from '../book/model/library.model';
import {MagicShelfService} from '../magic-shelf-service'; import {MagicShelfService} from '../magic-shelf.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {DynamicDialogConfig} from 'primeng/dynamicdialog'; import {DynamicDialogConfig} from 'primeng/dynamicdialog';
import {Chips} from 'primeng/chips'; import {Chips} from 'primeng/chips';
@@ -2,10 +2,11 @@ import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from './config/api-config'; import {API_CONFIG} from './config/api-config';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs'; import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, map, switchMap, tap} from 'rxjs/operators'; import {catchError, map, switchMap, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
import {BookService} from './book/service/book.service'; import {BookService} from './book/service/book.service';
import {GroupRule} from './magic-shelf-component/magic-shelf-component'; import {GroupRule} from './magic-shelf-component/magic-shelf-component';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service'; import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
import {AuthService} from './core/service/auth.service';
export interface MagicShelf { export interface MagicShelf {
id?: number | null; id?: number | null;
@@ -15,7 +16,7 @@ export interface MagicShelf {
} }
export interface MagicShelfState { export interface MagicShelfState {
shelves: MagicShelf[]; shelves: MagicShelf[] | null;
loaded: boolean; loaded: boolean;
error: string | null; error: string | null;
} }
@@ -29,28 +30,64 @@ export class MagicShelfService {
private readonly http = inject(HttpClient); private readonly http = inject(HttpClient);
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService); private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
private readonly authService = inject(AuthService);
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({ private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
shelves: [], shelves: null,
loaded: false, loaded: false,
error: null, error: null,
}); });
public readonly shelvesState$ = this.shelvesStateSubject.asObservable();
private loading$: Observable<MagicShelf[]> | null = null;
constructor() { constructor() {
this.loadUserShelves().subscribe(); this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.shelvesStateSubject.next({
shelves: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.shelvesStateSubject.value;
if (current.loaded && !current.shelves) {
this.shelvesStateSubject.next({
shelves: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
} }
public readonly shelvesState$ = this.shelvesStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchMagicShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private get state(): MagicShelfState { private get state(): MagicShelfState {
return this.shelvesStateSubject.value; return this.shelvesStateSubject.value;
} }
loadUserShelves(): Observable<MagicShelf[]> { private fetchMagicShelves(): Observable<MagicShelf[]> {
return this.http.get<MagicShelf[]>(this.url).pipe( return this.http.get<MagicShelf[]>(this.url).pipe(
tap((shelves) => this.updateShelves(shelves)), tap(shelves => this.shelvesStateSubject.next({shelves, loaded: true, error: null})),
catchError((error) => { catchError(err => {
this.updateError(error.message); const curr = this.shelvesStateSubject.value;
return of([]); this.shelvesStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
throw err;
}) })
); );
} }
@@ -65,12 +102,13 @@ export class MagicShelfService {
return this.http.post<MagicShelf>(this.url, payload).pipe( return this.http.post<MagicShelf>(this.url, payload).pipe(
tap((newShelf) => { tap((newShelf) => {
const shelves = this.state.shelves; const curr = this.state;
const shelves = curr.shelves || [];
const updated = shelves.some((s) => s.id === newShelf.id) const updated = shelves.some((s) => s.id === newShelf.id)
? shelves.map((s) => (s.id === newShelf.id ? newShelf : s)) ? shelves.map((s) => (s.id === newShelf.id ? newShelf : s))
: [...shelves, newShelf]; : [...shelves, newShelf];
this.updateShelves(updated); this.shelvesStateSubject.next({...curr, shelves: updated});
}), }),
catchError((error) => { catchError((error) => {
this.updateError(error.message); this.updateError(error.message);
@@ -81,15 +119,16 @@ export class MagicShelfService {
getShelf(id: number): Observable<MagicShelf | undefined> { getShelf(id: number): Observable<MagicShelf | undefined> {
return this.shelvesState$.pipe( return this.shelvesState$.pipe(
map(state => state.shelves.find(shelf => shelf.id === id)) map(state => (state.shelves || []).find(shelf => shelf.id === id))
); );
} }
deleteShelf(id: number): Observable<void> { deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe( return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => { tap(() => {
const updated = this.state.shelves.filter((s) => s.id !== id); const curr = this.state;
this.updateShelves(updated); const updated = (curr.shelves || []).filter((s) => s.id !== id);
this.shelvesStateSubject.next({...curr, shelves: updated});
}), }),
catchError((error) => { catchError((error) => {
this.updateError(error.message); this.updateError(error.message);
@@ -98,14 +137,6 @@ export class MagicShelfService {
); );
} }
private updateShelves(shelves: MagicShelf[]): void {
this.shelvesStateSubject.next({
shelves,
loaded: true,
error: null,
});
}
private updateError(error: string): void { private updateError(error: string): void {
this.shelvesStateSubject.next({ this.shelvesStateSubject.next({
...this.state, ...this.state,
@@ -67,7 +67,6 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
) {} ) {}
ngOnInit(): void { ngOnInit(): void {
this.bookService.loadBooks();
const bookIdFromDialog: number | undefined = this.config?.data?.bookId; const bookIdFromDialog: number | undefined = this.config?.data?.bookId;
if (bookIdFromDialog != null) { if (bookIdFromDialog != null) {
this.currentBookId$.next(bookIdFromDialog); this.currentBookId$.next(bookIdFromDialog);
@@ -126,10 +125,13 @@ export class BookMetadataCenterComponent implements OnInit, OnDestroy {
}); });
this.userService.userState$ this.userService.userState$
.pipe(takeUntil(this.destroy$)) .pipe(
.subscribe(userData => { filter(userState => !!userState?.user && userState.loaded),
this.canEditMetadata = userData?.permissions?.canEditMetadata ?? false; takeUntil(this.destroy$)
this.admin = userData?.permissions?.admin ?? false; )
.subscribe(userState => {
this.canEditMetadata = userState.user?.permissions?.canEditMetadata ?? false;
this.admin = userState.user?.permissions?.admin ?? false;
}); });
} }
@@ -350,7 +350,7 @@
</div> </div>
</div> </div>
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
<div class="flex flex-wrap gap-3 pt-6"> <div class="flex flex-wrap gap-3 pt-6">
@if (book!.bookType === 'PDF') { @if (book!.bookType === 'PDF') {
@if (readMenuItems$ | async; as readItems) { @if (readMenuItems$ | async; as readItems) {
@@ -376,28 +376,28 @@
outlined outlined
(onClick)="assignShelf(book.id)"> (onClick)="assignShelf(book.id)">
</p-button> </p-button>
@if (userData.permissions.canDownload || userData.permissions.admin) { @if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
<p-button <p-button
label="Download" label="Download"
icon="pi pi-download" icon="pi pi-download"
severity="success" severity="success"
outlined outlined
(onClick)="download(book.id)"> (onClick)="download(book!.id)">
</p-button> </p-button>
} }
@if (userData.permissions.canEmailBook || userData.permissions.admin) { @if (userState.user!.permissions.canEmailBook || userState.user!.permissions.admin) {
@if (emailMenuItems$ | async; as emailItems) { @if (emailMenuItems$ | async; as emailItems) {
<p-splitbutton <p-splitbutton
label="Quick Send" label="Quick Send"
icon="pi pi-send" icon="pi pi-send"
[model]="emailItems" [model]="emailItems"
(onClick)="quickSend(book.id)" (onClick)="quickSend(book!.id)"
outlined outlined
severity="info"> severity="info">
</p-splitbutton> </p-splitbutton>
} }
} }
@if (userData.permissions.canEditMetadata || userData.permissions.admin) { @if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
@if (refreshMenuItems$ | async; as refreshItems) { @if (refreshMenuItems$ | async; as refreshItems) {
<p-splitbutton <p-splitbutton
[label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'" [label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'"
@@ -405,14 +405,14 @@
[outlined]="true" [outlined]="true"
[model]="refreshItems" [model]="refreshItems"
severity="warn" severity="warn"
(onClick)="quickRefresh(book.id)" (onClick)="quickRefresh(book!.id)"
[disabled]="isAutoFetching" [disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources" pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top"> tooltipPosition="top">
</p-splitbutton> </p-splitbutton>
} }
} }
@if (userData.permissions.canDeleteBook || userData.permissions.admin) { @if (userState.user!.permissions.canDeleteBook || userState.user!.permissions.admin) {
@if (otherItems$ | async; as otherItems) { @if (otherItems$ | async; as otherItems) {
<p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button> <p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button>
<p-menu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-menu> <p-menu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-menu>
@@ -164,11 +164,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
this.userService.userState$ this.userService.userState$
.pipe( .pipe(
filter(user => !!user), filter(userState => !!userState?.user && userState.loaded),
take(1) take(1)
) )
.subscribe(user => { .subscribe(userState => {
this.metadataCenterViewMode = user?.userSettings.metadataCenterViewMode ?? 'route'; this.metadataCenterViewMode = userState.user?.userSettings.metadataCenterViewMode ?? 'route';
}); });
this.book$ this.book$
@@ -5,9 +5,9 @@ import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {Book} from '../../book/model/book.model'; import {Book} from '../../book/model/book.model';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {BookService} from '../../book/service/book.service'; import {BookService} from '../../book/service/book.service';
import {BehaviorSubject, combineLatest, Observable, Subscription} from 'rxjs'; import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {UserService} from '../../settings/user-management/user.service'; import {UserService} from '../../settings/user-management/user.service';
import {distinctUntilChanged, filter, map, shareReplay, switchMap} from 'rxjs/operators'; import {distinctUntilChanged, filter, map, shareReplay, switchMap, takeUntil} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-multi-book-metadata-editor-component', selector: 'app-multi-book-metadata-editor-component',
@@ -41,13 +41,16 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
private readonly bookService = inject(BookService); private readonly bookService = inject(BookService);
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private userSubscription: Subscription = Subscription.EMPTY; private readonly destroy$ = new Subject<void>();
ngOnInit(): void { ngOnInit(): void {
this.bookIds = this.config.data?.bookIds ?? []; this.bookIds = this.config.data?.bookIds ?? [];
this.userSubscription = this.userService.userState$.subscribe(userData => { this.userService.userState$.pipe(
const userPermissions = userData?.permissions; filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
).subscribe(userState => {
const userPermissions = userState.user?.permissions;
this.canEditMetadata = userPermissions?.canEditMetadata ?? false; this.canEditMetadata = userPermissions?.canEditMetadata ?? false;
this.admin = userPermissions?.admin ?? false; this.admin = userPermissions?.admin ?? false;
}); });
@@ -60,7 +63,8 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
map(books => { map(books => {
this.filteredBooks = books; this.filteredBooks = books;
return books; return books;
}) }),
takeUntil(this.destroy$)
); );
this.book$ = combineLatest([filteredBooks$, this.currentIndex$]).pipe( this.book$ = combineLatest([filteredBooks$, this.currentIndex$]).pipe(
@@ -70,12 +74,14 @@ export class MultiBookMetadataEditorComponent implements OnInit, OnDestroy {
switchMap(book => switchMap(book =>
this.bookService.getBookByIdFromAPI(book.id, true) this.bookService.getBookByIdFromAPI(book.id, true)
), ),
shareReplay(1) shareReplay(1),
takeUntil(this.destroy$)
); );
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.userSubscription.unsubscribe(); this.destroy$.next();
this.destroy$.complete();
this.currentIndex$.complete(); this.currentIndex$.complete();
} }
@@ -1,14 +1,15 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {FormBuilder, FormGroup, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators} from '@angular/forms';
import {InputText} from 'primeng/inputtext'; import {InputText} from 'primeng/inputtext';
import {Password} from 'primeng/password'; import {Password} from 'primeng/password';
import {User, UserService} from '../../user-management/user.service'; import {User, UserService} from '../../user-management/user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {Subscription} from 'rxjs'; import {Subject} from 'rxjs';
import {Message} from 'primeng/message'; import {Message} from 'primeng/message';
import {filter, takeUntil} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-user-profile-dialog', selector: 'app-user-profile-dialog',
@@ -20,7 +21,7 @@ import {Message} from 'primeng/message';
InputText, InputText,
Password, Password,
Message Message
], ],
templateUrl: './user-profile-dialog.component.html', templateUrl: './user-profile-dialog.component.html',
styleUrls: ['./user-profile-dialog.component.scss'] styleUrls: ['./user-profile-dialog.component.scss']
}) })
@@ -29,7 +30,7 @@ export class UserProfileDialogComponent implements OnInit, OnDestroy {
isEditing = false; isEditing = false;
currentUser: User | null = null; currentUser: User | null = null;
editUserData: Partial<User> = {}; editUserData: Partial<User> = {};
private userSubscription: Subscription | null = null; private readonly destroy$ = new Subject<void>();
changePasswordForm: FormGroup; changePasswordForm: FormGroup;
@@ -51,14 +52,18 @@ export class UserProfileDialogComponent implements OnInit, OnDestroy {
} }
ngOnInit(): void { ngOnInit(): void {
this.userSubscription = this.userService.userState$.subscribe(user => { this.userService.userState$.pipe(
this.currentUser = user; filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
).subscribe(userState => {
this.currentUser = userState.user;
this.resetEditForm(); this.resetEditForm();
}); });
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.userSubscription?.unsubscribe(); this.destroy$.next();
this.destroy$.complete();
} }
static passwordsMatchValidator(form: FormGroup) { static passwordsMatchValidator(form: FormGroup) {
@@ -1,15 +1,26 @@
import {inject, Injectable} from '@angular/core'; import {inject, Injectable, OnDestroy} from '@angular/core';
import {User, UserService, UserSettings} from '../user-management/user.service'; import {User, UserService, UserSettings} from '../user-management/user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {filter, takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
@Injectable({ providedIn: 'root' }) @Injectable({providedIn: 'root'})
export class ReaderPreferencesService { export class ReaderPreferencesService implements OnDestroy {
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private currentUser: User | null = null; private currentUser: User | null = null;
private readonly destroy$ = new Subject<void>();
constructor() { constructor() {
this.userService.userState$.subscribe(user => this.currentUser = user); this.userService.userState$.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
).subscribe(userState => this.currentUser = userState.user);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
} }
updatePreference(path: string[], value: any): void { updatePreference(path: string[], value: any): void {
@@ -1,11 +1,12 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {filter, takeUntil} from 'rxjs/operators';
import {Observable, Subscription} from 'rxjs'; import {Observable, Subject} from 'rxjs';
import {RadioButton} from 'primeng/radiobutton'; import {RadioButton} from 'primeng/radiobutton';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {User, UserService, UserSettings} from '../user-management/user.service'; import {UserService, UserSettings, UserState} from '../user-management/user.service';
import {EpubReaderPreferencesComponent} from './epub-reader-preferences-component/epub-reader-preferences-component'; import {EpubReaderPreferencesComponent} from './epub-reader-preferences-component/epub-reader-preferences-component';
import {PdfReaderPreferencesComponent} from './pdf-reader-preferences-component/pdf-reader-preferences-component'; import {PdfReaderPreferencesComponent} from './pdf-reader-preferences-component/pdf-reader-preferences-component';
import {CbxReaderPreferencesComponent} from './cbx-reader-preferences-component/cbx-reader-preferences-component'; import {CbxReaderPreferencesComponent} from './cbx-reader-preferences-component/cbx-reader-preferences-component';
@@ -27,22 +28,24 @@ export class ReaderPreferences implements OnInit, OnDestroy {
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private readonly readerPreferencesService = inject(ReaderPreferencesService); private readonly readerPreferencesService = inject(ReaderPreferencesService);
private readonly destroy$ = new Subject<void>();
userData$: Observable<User | null> = this.userService.userState$; userData$: Observable<UserState> = this.userService.userState$;
private subscription?: Subscription;
userSettings!: UserSettings; userSettings!: UserSettings;
ngOnInit(): void { ngOnInit(): void {
this.subscription = this.userData$.subscribe(user => { this.userData$.pipe(
if (user) { filter(userState => !!userState?.user && userState.loaded),
this.userSettings = user.userSettings; takeUntil(this.destroy$)
this.loadPreferences(user.userSettings); ).subscribe(userState => {
} this.userSettings = userState.user!.userSettings;
this.loadPreferences(userState.user!.userSettings);
}); });
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.subscription?.unsubscribe(); this.destroy$.next();
this.destroy$.complete();
} }
private loadPreferences(settings: UserSettings): void { private loadPreferences(settings: UserSettings): void {
@@ -1,80 +1,82 @@
@if (userService.userState$ | async; as userData) { @if (userService.userState$ | async; as userState) {
<div> @if (userState.user) {
<div class="rounded-xl overflow-hidden"> <div>
<p-tabs [(value)]="activeTab" scrollable> <div class="rounded-xl overflow-hidden">
<p-tablist> <p-tabs [(value)]="activeTab" scrollable>
<p-tab [value]="SettingsTab.ReaderSettings"> <p-tablist>
<i class="pi pi-book"></i> Reader <p-tab [value]="SettingsTab.ReaderSettings">
</p-tab> <i class="pi pi-book"></i> Reader
<p-tab [value]="SettingsTab.ViewPreferences">
<i class="pi pi-desktop"></i> View
</p-tab>
@if (userData.permissions.admin) {
<p-tab [value]="SettingsTab.MetadataSettings">
<i class="pi pi-sliders-h"></i> Metadata
</p-tab> </p-tab>
<p-tab [value]="SettingsTab.ApplicationSettings"> <p-tab [value]="SettingsTab.ViewPreferences">
<i class="pi pi-cog"></i> Application <i class="pi pi-desktop"></i> View
</p-tab> </p-tab>
<p-tab [value]="SettingsTab.UserManagement"> @if (userState.user.permissions.admin) {
<i class="pi pi-users"></i> User <p-tab [value]="SettingsTab.MetadataSettings">
</p-tab> <i class="pi pi-sliders-h"></i> Metadata
<p-tab [value]="SettingsTab.EmailSettings"> </p-tab>
<i class="pi pi-envelope"></i> Email <p-tab [value]="SettingsTab.ApplicationSettings">
</p-tab> <i class="pi pi-cog"></i> Application
<p-tab [value]="SettingsTab.NamingPattern"> </p-tab>
<i class="pi pi-sitemap"></i> Patterns <p-tab [value]="SettingsTab.UserManagement">
</p-tab> <i class="pi pi-users"></i> User
<p-tab [value]="SettingsTab.AuthenticationSettings"> </p-tab>
<i class="pi pi-lock"></i> Authentication <p-tab [value]="SettingsTab.EmailSettings">
</p-tab> <i class="pi pi-envelope"></i> Email
<p-tab [value]="SettingsTab.Opds"> </p-tab>
<i class="pi pi-globe"></i> OPDS <p-tab [value]="SettingsTab.NamingPattern">
</p-tab> <i class="pi pi-sitemap"></i> Patterns
} </p-tab>
@if (userData.permissions.admin || userData.permissions.canSyncKoReader) { <p-tab [value]="SettingsTab.AuthenticationSettings">
<p-tab [value]="SettingsTab.DeviceSettings"> <i class="pi pi-lock"></i> Authentication
<i class="pi pi-mobile"></i> Devices </p-tab>
</p-tab> <p-tab [value]="SettingsTab.Opds">
} <i class="pi pi-globe"></i> OPDS
</p-tablist> </p-tab>
<p-tabpanels> }
<p-tabpanel [value]="SettingsTab.ReaderSettings"> @if (userState.user.permissions.admin || userState.user.permissions.canSyncKoReader) {
<app-reader-preferences></app-reader-preferences> <p-tab [value]="SettingsTab.DeviceSettings">
</p-tabpanel> <i class="pi pi-mobile"></i> Devices
<p-tabpanel [value]="SettingsTab.ViewPreferences"> </p-tab>
<app-view-preferences-parent></app-view-preferences-parent> }
</p-tabpanel> </p-tablist>
@if (userData.permissions.admin) { <p-tabpanels>
<p-tabpanel [value]="SettingsTab.MetadataSettings"> <p-tabpanel [value]="SettingsTab.ReaderSettings">
<app-metadata-settings-component></app-metadata-settings-component> <app-reader-preferences></app-reader-preferences>
</p-tabpanel> </p-tabpanel>
<p-tabpanel [value]="SettingsTab.ApplicationSettings"> <p-tabpanel [value]="SettingsTab.ViewPreferences">
<app-global-preferences></app-global-preferences> <app-view-preferences-parent></app-view-preferences-parent>
</p-tabpanel> </p-tabpanel>
<p-tabpanel [value]="SettingsTab.UserManagement"> @if (userState.user.permissions.admin) {
<app-user-management></app-user-management> <p-tabpanel [value]="SettingsTab.MetadataSettings">
</p-tabpanel> <app-metadata-settings-component></app-metadata-settings-component>
<p-tabpanel [value]="SettingsTab.EmailSettings"> </p-tabpanel>
<app-email></app-email> <p-tabpanel [value]="SettingsTab.ApplicationSettings">
</p-tabpanel> <app-global-preferences></app-global-preferences>
<p-tabpanel [value]="SettingsTab.NamingPattern"> </p-tabpanel>
<app-file-naming-pattern></app-file-naming-pattern> <p-tabpanel [value]="SettingsTab.UserManagement">
</p-tabpanel> <app-user-management></app-user-management>
<p-tabpanel [value]="SettingsTab.AuthenticationSettings"> </p-tabpanel>
<app-authentication-settings></app-authentication-settings> <p-tabpanel [value]="SettingsTab.EmailSettings">
</p-tabpanel> <app-email></app-email>
<p-tabpanel [value]="SettingsTab.Opds"> </p-tabpanel>
<app-opds-settings></app-opds-settings> <p-tabpanel [value]="SettingsTab.NamingPattern">
</p-tabpanel> <app-file-naming-pattern></app-file-naming-pattern>
} </p-tabpanel>
@if (userData.permissions.admin || userData.permissions.canSyncKoReader) { <p-tabpanel [value]="SettingsTab.AuthenticationSettings">
<p-tabpanel [value]="SettingsTab.DeviceSettings"> <app-authentication-settings></app-authentication-settings>
<app-device-settings-component></app-device-settings-component> </p-tabpanel>
</p-tabpanel> <p-tabpanel [value]="SettingsTab.Opds">
} <app-opds-settings></app-opds-settings>
</p-tabpanels> </p-tabpanel>
</p-tabs> }
@if (userState.user.permissions.admin || userState.user.permissions.canSyncKoReader) {
<p-tabpanel [value]="SettingsTab.DeviceSettings">
<app-device-settings-component></app-device-settings-component>
</p-tabpanel>
}
</p-tabpanels>
</p-tabs>
</div>
</div> </div>
</div> }
} }
@@ -1,10 +1,10 @@
import {Component, inject, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component'; import {CreateUserDialogComponent} from './create-user-dialog/create-user-dialog.component';
import {TableModule} from 'primeng/table'; import {TableModule} from 'primeng/table';
import { LowerCasePipe, NgStyle, TitleCasePipe } from '@angular/common'; import {LowerCasePipe, NgStyle, TitleCasePipe} from '@angular/common';
import {User, UserService} from './user.service'; import {User, UserService} from './user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {Checkbox} from 'primeng/checkbox'; import {Checkbox} from 'primeng/checkbox';
@@ -13,7 +13,8 @@ import {Library} from '../../book/model/library.model';
import {LibraryService} from '../../book/service/library.service'; import {LibraryService} from '../../book/service/library.service';
import {Dialog} from 'primeng/dialog'; import {Dialog} from 'primeng/dialog';
import {Password} from 'primeng/password'; import {Password} from 'primeng/password';
import {filter, take} from 'rxjs/operators'; import {filter, take, takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
@Component({ @Component({
selector: 'app-user-management', selector: 'app-user-management',
@@ -28,19 +29,20 @@ import {filter, take} from 'rxjs/operators';
Password, Password,
LowerCasePipe, LowerCasePipe,
TitleCasePipe TitleCasePipe
], ],
templateUrl: './user-management.component.html', templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.scss'], styleUrls: ['./user-management.component.scss'],
}) })
export class UserManagementComponent implements OnInit { export class UserManagementComponent implements OnInit, OnDestroy {
ref: DynamicDialogRef | undefined; ref: DynamicDialogRef | undefined;
private dialogService = inject(DialogService); private dialogService = inject(DialogService);
private userService = inject(UserService); private userService = inject(UserService);
private libraryService = inject(LibraryService); private libraryService = inject(LibraryService);
private messageService = inject(MessageService); private messageService = inject(MessageService);
private readonly destroy$ = new Subject<void>();
users: User[] = []; users: User[] = [];
currentUser: User | undefined; currentUser: User | null = null;
editingLibraryIds: number[] = []; editingLibraryIds: number[] = [];
allLibraries: Library[] = []; allLibraries: Library[] = [];
@@ -49,19 +51,36 @@ export class UserManagementComponent implements OnInit {
newPassword = ''; newPassword = '';
confirmNewPassword = ''; confirmNewPassword = '';
passwordError = ''; passwordError = '';
isAdmin = false;
ngOnInit() { ngOnInit() {
this.loadUsers(); this.loadUsers();
this.userService.userState$ this.userService.userState$
.pipe(filter(user => !!user), take(1)) .pipe(
.subscribe(user => this.currentUser = user); filter(userState => !!userState?.user && userState.loaded),
take(1),
takeUntil(this.destroy$)
)
.subscribe(userState => {
this.currentUser = userState.user;
this.isAdmin = userState.user?.permissions?.admin || false;
});
this.libraryService.libraryState$ this.libraryService.libraryState$
.pipe(filter(state => !!state?.loaded), take(1)) .pipe(
filter(state => !!state?.loaded),
take(1),
takeUntil(this.destroy$)
)
.subscribe(libraries => this.allLibraries = libraries.libraries ?? []); .subscribe(libraries => this.allLibraries = libraries.libraries ?? []);
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
loadUsers() { loadUsers() {
this.userService.getUsers().subscribe({ this.userService.getUsers().subscribe({
@@ -1,12 +1,10 @@
import {inject, Injectable, Injector} from '@angular/core'; import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, throwError} from 'rxjs'; import {BehaviorSubject, Observable, throwError} from 'rxjs';
import {API_CONFIG} from '../../config/api-config'; import {API_CONFIG} from '../../config/api-config';
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {Library} from '../../book/model/library.model'; import {Library} from '../../book/model/library.model';
import {catchError} from 'rxjs/operators'; import {catchError, distinctUntilChanged, finalize, shareReplay, tap} from 'rxjs/operators';
import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model'; import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model';
import {filter, take} from 'rxjs/operators';
import {AuthService} from '../../core/service/auth.service'; import {AuthService} from '../../core/service/auth.service';
export interface EntityViewPreferences { export interface EntityViewPreferences {
@@ -113,6 +111,12 @@ export interface User {
provisioningMethod?: 'LOCAL' | 'OIDC' | 'REMOTE'; provisioningMethod?: 'LOCAL' | 'OIDC' | 'REMOTE';
} }
export interface UserState {
user: User | null;
loaded: boolean;
error: string | null;
}
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
@@ -121,16 +125,70 @@ export class UserService {
private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`; private readonly userUrl = `${API_CONFIG.BASE_URL}/api/v1/users`;
private http = inject(HttpClient); private http = inject(HttpClient);
private authService = inject(AuthService);
private userStateSubject = new BehaviorSubject<User | null>(null); private userStateSubject = new BehaviorSubject<UserState>({
userState$ = this.userStateSubject.asObservable(); user: null,
loaded: false,
error: null,
});
private loading$: Observable<User> | null = null;
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.userStateSubject.next({
user: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.userStateSubject.value;
if (current.loaded && !current.user) {
this.userStateSubject.next({
user: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
userState$ = this.userStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchMyself().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchMyself(): Observable<User> {
return this.http.get<User>(`${this.userUrl}/me`).pipe(
tap(user => this.userStateSubject.next({ user, loaded: true, error: null })),
catchError(err => {
const curr = this.userStateSubject.value;
this.userStateSubject.next({ user: curr.user, loaded: true, error: err.message });
throw err;
})
);
}
public setInitialUser(user: User): void { public setInitialUser(user: User): void {
this.userStateSubject.next(user); this.userStateSubject.next({ user, loaded: true, error: null });
} }
getCurrentUser(): User | null { getCurrentUser(): User | null {
return this.userStateSubject.getValue(); return this.userStateSubject.value.user;
} }
getMyself(): Observable<User> { getMyself(): Observable<User> {
@@ -188,11 +246,11 @@ export class UserService {
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
responseType: 'text' as 'json' responseType: 'text' as 'json'
}).subscribe(() => { }).subscribe(() => {
const currentUser = this.userStateSubject.getValue(); const currentState = this.userStateSubject.value;
if (currentUser) { if (currentState.user) {
const updatedSettings = {...currentUser.userSettings, [key]: value}; const updatedSettings = {...currentState.user.userSettings, [key]: value};
const updatedUser = {...currentUser, settings: updatedSettings}; const updatedUser = {...currentState.user, userSettings: updatedSettings};
this.userStateSubject.next(updatedUser); this.userStateSubject.next({...currentState, user: updatedUser});
} }
}); });
} }
@@ -1,10 +1,11 @@
import {Component, inject, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {RadioButton} from 'primeng/radiobutton'; import {RadioButton} from 'primeng/radiobutton';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {UserService} from '../../user-management/user.service'; import {UserService} from '../../user-management/user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {take} from 'rxjs/operators'; import {filter, take, takeUntil} from 'rxjs/operators';
import {Subject} from 'rxjs';
@Component({ @Component({
selector: 'app-meta-center-view-mode-component', selector: 'app-meta-center-view-mode-component',
@@ -16,21 +17,31 @@ import {take} from 'rxjs/operators';
templateUrl: './meta-center-view-mode-component.html', templateUrl: './meta-center-view-mode-component.html',
styleUrl: './meta-center-view-mode-component.scss' styleUrl: './meta-center-view-mode-component.scss'
}) })
export class MetaCenterViewModeComponent implements OnInit { export class MetaCenterViewModeComponent implements OnInit, OnDestroy {
viewMode: 'route' | 'dialog' = 'route'; viewMode: 'route' | 'dialog' = 'route';
private userService = inject(UserService); private userService = inject(UserService);
private messageService = inject(MessageService); private messageService = inject(MessageService);
private readonly destroy$ = new Subject<void>();
ngOnInit(): void { ngOnInit(): void {
this.userService.userState$.pipe(take(1)).subscribe(user => { this.userService.userState$.pipe(
const preference = user?.userSettings?.metadataCenterViewMode; filter(userState => !!userState?.user && userState.loaded),
take(1),
takeUntil(this.destroy$)
).subscribe(userState => {
const preference = userState.user?.userSettings?.metadataCenterViewMode;
if (preference === 'dialog' || preference === 'route') { if (preference === 'dialog' || preference === 'route') {
this.viewMode = preference; this.viewMode = preference;
} }
}); });
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
onViewModeChange(value: 'route' | 'dialog'): void { onViewModeChange(value: 'route' | 'dialog'): void {
this.viewMode = value; this.viewMode = value;
this.savePreference(value); this.savePreference(value);
@@ -1,10 +1,11 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Select} from 'primeng/select'; import {Select} from 'primeng/select';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {SidebarLibrarySorting, SidebarShelfSorting, User, UserService, UserSettings} from '../../user-management/user.service'; import {SidebarLibrarySorting, SidebarShelfSorting, User, UserService, UserSettings, UserState} from '../../user-management/user.service';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {Observable, Subscription} from 'rxjs'; import {Observable, Subject} from 'rxjs';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {filter, takeUntil} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-sidebar-sorting-preferences', selector: 'app-sidebar-sorting-preferences',
@@ -30,22 +31,24 @@ export class SidebarSortingPreferencesComponent implements OnInit, OnDestroy {
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private readonly destroy$ = new Subject<void>();
userData$: Observable<User | null> = this.userService.userState$; userData$: Observable<UserState> = this.userService.userState$;
private subscription?: Subscription;
private currentUser: User | null = null; private currentUser: User | null = null;
ngOnInit(): void { ngOnInit(): void {
this.subscription = this.userData$.subscribe(user => { this.userData$.pipe(
if (user) { filter(userState => !!userState?.user && userState.loaded),
this.currentUser = user; takeUntil(this.destroy$)
this.loadPreferences(user.userSettings); ).subscribe(userState => {
} this.currentUser = userState.user;
this.loadPreferences(userState.user!.userSettings);
}); });
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.subscription?.unsubscribe(); this.destroy$.next();
this.destroy$.complete();
} }
private loadPreferences(settings: UserSettings): void { private loadPreferences(settings: UserSettings): void {
@@ -1,4 +1,4 @@
import {Component, inject, OnInit} from '@angular/core'; import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
@@ -8,10 +8,10 @@ import {Tooltip} from 'primeng/tooltip';
import {User, UserService} from '../../user-management/user.service'; import {User, UserService} from '../../user-management/user.service';
import {LibraryService} from '../../../book/service/library.service'; import {LibraryService} from '../../../book/service/library.service';
import {ShelfService} from '../../../book/service/shelf.service'; import {ShelfService} from '../../../book/service/shelf.service';
import {combineLatest} from 'rxjs'; import {combineLatest, Subject} from 'rxjs';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {ToastModule} from 'primeng/toast'; import {ToastModule} from 'primeng/toast';
import {filter, take} from 'rxjs/operators'; import {filter, take, takeUntil} from 'rxjs/operators';
@Component({ @Component({
selector: 'app-view-preferences', selector: 'app-view-preferences',
@@ -27,7 +27,7 @@ import {filter, take} from 'rxjs/operators';
templateUrl: './view-preferences.component.html', templateUrl: './view-preferences.component.html',
styleUrl: './view-preferences.component.scss' styleUrl: './view-preferences.component.scss'
}) })
export class ViewPreferencesComponent implements OnInit { export class ViewPreferencesComponent implements OnInit, OnDestroy {
sortOptions = [ sortOptions = [
{label: 'Title', field: 'title'}, {label: 'Title', field: 'title'},
{label: 'Title + Series', field: 'titleSeries'}, {label: 'Title + Series', field: 'titleSeries'},
@@ -78,6 +78,7 @@ export class ViewPreferencesComponent implements OnInit {
}[] = []; }[] = [];
private user: User | null = null; private user: User | null = null;
private readonly destroy$ = new Subject<void>();
private libraryService = inject(LibraryService); private libraryService = inject(LibraryService);
private shelfService = inject(ShelfService); private shelfService = inject(ShelfService);
@@ -86,13 +87,15 @@ export class ViewPreferencesComponent implements OnInit {
ngOnInit(): void { ngOnInit(): void {
combineLatest([ combineLatest([
this.userService.userState$.pipe(filter(user => !!user), take(1)), this.userService.userState$.pipe(filter(userState => !!userState?.user && userState.loaded), take(1)),
this.libraryService.libraryState$.pipe(filter(libraryState => !!libraryState?.libraries && libraryState.loaded), take(1)), this.libraryService.libraryState$.pipe(filter(libraryState => !!libraryState?.libraries && libraryState.loaded), take(1)),
this.shelfService.shelfState$.pipe(filter(shelfState => !!shelfState?.shelves && shelfState.loaded), take(1)), this.shelfService.shelfState$.pipe(filter(shelfState => !!shelfState?.shelves && shelfState.loaded), take(1)),
]).subscribe(([userState, librariesState, shelfState]) => { ]).pipe(
takeUntil(this.destroy$)
).subscribe(([userState, librariesState, shelfState]) => {
this.user = userState; this.user = userState.user;
const prefs = userState?.userSettings?.entityViewPreferences; const prefs = userState.user?.userSettings?.entityViewPreferences;
const global = prefs?.global; const global = prefs?.global;
this.selectedSort = global?.sortKey ?? 'title'; this.selectedSort = global?.sortKey ?? 'title';
this.selectedSortDir = global?.sortDir ?? 'ASC'; this.selectedSortDir = global?.sortDir ?? 'ASC';
@@ -118,6 +121,11 @@ export class ViewPreferencesComponent implements OnInit {
}); });
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
getAvailableEntities(index: number, type: 'LIBRARY' | 'SHELF') { getAvailableEntities(index: number, type: 'LIBRARY' | 'SHELF') {
const selected = this.overrides.map((o, i) => i !== index ? o.library : null); const selected = this.overrides.map((o, i) => i !== index ? o.library : null);
const source = type === 'LIBRARY' ? this.libraryOptions : this.shelfOptions; const source = type === 'LIBRARY' ? this.libraryOptions : this.shelfOptions;