Merge pull request #499 from adityachandelgit/develop

Merge Develop into Master for Release
This commit is contained in:
Aditya Chandel
2025-06-13 09:57:37 -06:00
committed by GitHub
24 changed files with 271 additions and 228 deletions
@@ -13,6 +13,7 @@ public class MetadataProviderSettings {
public static class Amazon { public static class Amazon {
private boolean enabled; private boolean enabled;
private String cookie; private String cookie;
private String domain;
} }
@Data @Data
@@ -36,6 +36,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("SELECT b FROM BookEntity b") @Query("SELECT b FROM BookEntity b")
List<BookEntity> findAllWithMetadata(); List<BookEntity> findAllWithMetadata();
@EntityGraph(attributePaths = {"metadata", "shelves"})
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds")
List<BookEntity> findAllWithMetadataByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
@EntityGraph(attributePaths = {"metadata", "shelves"}) @EntityGraph(attributePaths = {"metadata", "shelves"})
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds") @Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds")
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds); List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
@@ -31,6 +31,19 @@ public class BookQueryService {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription) {
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
return books.stream()
.map(book -> {
Book dto = bookMapperV2.toDTO(book);
if (!includeDescription && dto.getMetadata() != null) {
dto.getMetadata().setDescription(null);
}
return dto;
})
.collect(Collectors.toList());
}
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) { public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
return bookRepository.findAllWithMetadataByIds(bookIds); return bookRepository.findAllWithMetadataByIds(bookIds);
} }
@@ -53,7 +53,16 @@ public class BookService {
public List<Book> getBookDTOs(boolean includeDescription) { public List<Book> getBookDTOs(boolean includeDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> books = bookQueryService.getAllBooks(includeDescription); boolean isAdmin = user.getPermissions().isAdmin();
List<Book> books;
if(isAdmin) {
books = bookQueryService.getAllBooks(includeDescription);
} else{
Set<Long> libraryIds = user.getAssignedLibraries().stream()
.map(Library::getId)
.collect(Collectors.toSet());
books = bookQueryService.getAllBooksByLibraryIds(libraryIds, includeDescription);
}
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(user.getId(), books.stream().map(Book::getId).collect(Collectors.toSet())); Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(user.getId(), books.stream().map(Book::getId).collect(Collectors.toSet()));
books.forEach(book -> { books.forEach(book -> {
UserBookProgressEntity progress = progressMap.get(book.getId()); UserBookProgressEntity progress = progressMap.get(book.getId());
@@ -65,6 +65,7 @@ public class SettingPersistenceHelper {
MetadataProviderSettings.Amazon defaultAmazon = new MetadataProviderSettings.Amazon(); MetadataProviderSettings.Amazon defaultAmazon = new MetadataProviderSettings.Amazon();
defaultAmazon.setEnabled(true); defaultAmazon.setEnabled(true);
defaultAmazon.setCookie(null); defaultAmazon.setCookie(null);
defaultAmazon.setDomain("com");
MetadataProviderSettings.Google defaultGoogle = new MetadataProviderSettings.Google(); MetadataProviderSettings.Google defaultGoogle = new MetadataProviderSettings.Google();
defaultGoogle.setEnabled(true); defaultGoogle.setEnabled(true);
@@ -209,8 +209,7 @@ public class AmazonBookParser implements BookParser {
} }
String encodedSearchTerm = searchTerm.toString().replace(" ", "+"); String encodedSearchTerm = searchTerm.toString().replace(" ", "+");
String url = "https://www.amazon.com/s?k=" + encodedSearchTerm; String url = "https://www.amazon." + appSettingService.getAppSettings().getMetadataProviderSettings().getAmazon().getDomain() + "/s?k=" + encodedSearchTerm;
log.info("Query URL: {}", url); log.info("Query URL: {}", url);
return url; return url;
} }
@@ -51,7 +51,7 @@
<i class="pi pi-cog"></i> <i class="pi pi-cog"></i>
</a> </a>
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body"> <p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
<div class="w-[220px] p-3 space-y-4 text-sm"> <div class="w-[220px] p-2 space-y-4 text-sm">
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<label for="collapse-series-checkbox" class="font-medium">Collapse series</label> <label for="collapse-series-checkbox" class="font-medium">Collapse series</label>
<p-checkbox <p-checkbox
@@ -64,7 +64,7 @@
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<label class="font-medium text-sm">Grid item size</label> <label class="font-medium text-sm">Grid item size</label>
<p-slider <p-slider
[(ngModel)]="coverScaleManager.scaleFactor" [(ngModel)]="coverScalePreferenceService.scaleFactor"
[min]="0.5" [min]="0.5"
[max]="1.5" [max]="1.5"
[step]="0.01" [step]="0.01"
@@ -72,7 +72,18 @@
(onChange)="updateScale()"> (onChange)="updateScale()">
</p-slider> </p-slider>
<div class="text-center"> <div class="text-center">
{{ coverScaleManager.scaleFactor.toFixed(2) }}x {{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
</div>
</div>
<div class="flex flex-col gap-2">
<label class="font-medium text-sm">Sidbar Filter Sort:</label>
<div class="flex gap-4 justify-start">
<p-select
size="small"
[options]="filterSortPreferenceService.filterSortingOptions"
[(ngModel)]="filterSortPreferenceService.selectedFilterSorting"
placeholder="Select Sorting">
</p-select>
</div> </div>
</div> </div>
</div> </div>
@@ -32,13 +32,15 @@ import {OverlayPanelModule} from 'primeng/overlaypanel';
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter'; import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
import {SideBarFilter} from './filters/SidebarFilter'; import {SideBarFilter} from './filters/SidebarFilter';
import {HeaderFilter} from './filters/HeaderFilter'; import {HeaderFilter} from './filters/HeaderFilter';
import {CoverScaleManager} from './CoverScaleManager'; import {CoverScalePreferenceService} from './cover-scale-preference.service';
import {BookSorter} from './sorting/BookSorter'; import {BookSorter} from './sorting/BookSorter';
import {BookDialogHelperService} from './BookDialogHelperService'; import {BookDialogHelperService} from './BookDialogHelperService';
import {DropdownModule} from 'primeng/dropdown'; import {DropdownModule} from 'primeng/dropdown';
import {Checkbox} from 'primeng/checkbox'; import {Checkbox} from 'primeng/checkbox';
import {Popover} from 'primeng/popover'; import {Popover} from 'primeng/popover';
import {Slider} from 'primeng/slider'; import {Slider} from 'primeng/slider';
import {Select} from 'primeng/select';
import {FilterSortPreferenceService} from './filters/filter-sorting-preferences.service';
export enum EntityType { export enum EntityType {
LIBRARY = 'Library', LIBRARY = 'Library',
@@ -71,7 +73,7 @@ const SORT_DIRECTION = {
standalone: true, standalone: true,
templateUrl: './book-browser.component.html', templateUrl: './book-browser.component.html',
styleUrls: ['./book-browser.component.scss'], styleUrls: ['./book-browser.component.scss'],
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, DropdownModule, Checkbox, Popover, Slider], imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, DropdownModule, Checkbox, Popover, Slider, Select],
providers: [SeriesCollapseFilter], providers: [SeriesCollapseFilter],
animations: [ animations: [
trigger('slideInOut', [ trigger('slideInOut', [
@@ -118,7 +120,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
entityViewPreferences!: EntityViewPreferences; entityViewPreferences!: EntityViewPreferences;
protected userService = inject(UserService); protected userService = inject(UserService);
protected coverScaleManager = inject(CoverScaleManager); protected coverScalePreferenceService = inject(CoverScalePreferenceService);
protected filterSortPreferenceService = inject(FilterSortPreferenceService);
private activatedRoute = inject(ActivatedRoute); private activatedRoute = inject(ActivatedRoute);
private messageService = inject(MessageService); private messageService = inject(MessageService);
@@ -142,19 +145,19 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
private settingFiltersFromUrl = false; private settingFiltersFromUrl = false;
get currentCardSize() { get currentCardSize() {
return this.coverScaleManager.currentCardSize; return this.coverScalePreferenceService.currentCardSize;
} }
get gridColumnMinWidth(): string { get gridColumnMinWidth(): string {
return this.coverScaleManager.gridColumnMinWidth; return this.coverScalePreferenceService.gridColumnMinWidth;
} }
updateScale(): void { updateScale(): void {
this.coverScaleManager.setScale(this.coverScaleManager.scaleFactor); this.coverScalePreferenceService.setScale(this.coverScalePreferenceService.scaleFactor);
} }
ngOnInit(): void { ngOnInit(): void {
this.coverScaleManager.scaleChange$.pipe(debounceTime(1000)).subscribe(); this.coverScalePreferenceService.scaleChange$.pipe(debounceTime(1000)).subscribe();
this.bookService.loadBooks(); this.bookService.loadBooks();
@@ -239,11 +242,11 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.currentFilterLabel = 'All Books'; this.currentFilterLabel = 'All Books';
} }
this.entityViewPreferences = user.userSettings?.entityViewPreferences; this.entityViewPreferences = 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.coverScaleManager.scaleFactor = user.userSettings.entityViewPreferences?.global?.coverSize ?? 1.0; this.coverScalePreferenceService.initScaleValue(user?.userSettings?.entityViewPreferences?.global?.coverSize);
this.filterSortPreferenceService.initValue(user?.userSettings?.filterSortingMode);
const override = this.entityViewPreferences?.overrides?.find(o => const override = this.entityViewPreferences?.overrides?.find(o =>
o.entityType?.toUpperCase() === currentEntityTypeStr && o.entityType?.toUpperCase() === currentEntityTypeStr &&
@@ -1,6 +1,6 @@
import {Component, EventEmitter, inject, Input, OnInit, Output} from '@angular/core'; import {Component, EventEmitter, inject, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {combineLatest, Observable, of, Subject} from 'rxjs'; import {BehaviorSubject, combineLatest, Observable, of, Subject, takeUntil} from 'rxjs';
import {filter, map, take} from 'rxjs/operators'; import {distinctUntilChanged, filter, map, take} from 'rxjs/operators';
import {BookService} from '../../../service/book.service'; import {BookService} from '../../../service/book.service';
import {Library} from '../../../model/library.model'; import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model'; import {Shelf} from '../../../model/shelf.model';
@@ -12,6 +12,7 @@ import {Badge} from 'primeng/badge';
import {FormsModule} from '@angular/forms'; 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';
type Filter<T> = { value: T; bookCount: number }; type Filter<T> = { value: T; bookCount: number };
@@ -114,7 +115,7 @@ export function getMatchScoreRangeFilters(score?: number | null): { id: string;
SelectButton SelectButton
] ]
}) })
export class BookFilterComponent implements OnInit { export class BookFilterComponent implements OnInit, OnDestroy {
@Output() filterSelected = new EventEmitter<Record<string, any> | null>(); @Output() filterSelected = new EventEmitter<Record<string, any> | null>();
@Output() filterModeChanged = new EventEmitter<'and' | 'or'>(); @Output() filterModeChanged = new EventEmitter<'and' | 'or'>();
@@ -148,41 +149,42 @@ export class BookFilterComponent implements OnInit {
matchScore: 'Metadata Match Score' matchScore: 'Metadata Match Score'
}; };
private destroy$ = new Subject<void>();
bookService = inject(BookService); bookService = inject(BookService);
userService = inject(UserService); userService = inject(UserService);
filterSortPreferenceService = inject(FilterSortPreferenceService);
ngOnInit(): void { ngOnInit(): void {
combineLatest([ combineLatest([
this.userService.userState$.pipe( this.filterSortPreferenceService.sortMode$.pipe(distinctUntilChanged()),
filter((u): u is NonNullable<typeof u> => !!u),
take(1)
),
this.entity$ ?? of(null), this.entity$ ?? of(null),
this.entityType$ ?? of(EntityType.ALL_BOOKS) this.entityType$ ?? of(EntityType.ALL_BOOKS)
]).subscribe(([user]) => { ])
const sortMode = user.userSettings?.filterSortingMode ?? 'count'; .pipe(takeUntil(this.destroy$))
this.filterStreams = { .subscribe(([sortMode]) => {
author: this.getFilterStream((book: Book) => book.metadata?.authors.map(name => ({id: name, name})) || [], 'id', 'name', sortMode), this.filterStreams = {
category: this.getFilterStream((book: Book) => book.metadata?.categories.map(name => ({id: name, name})) || [], 'id', 'name', sortMode), author: this.getFilterStream((book: Book) => book.metadata?.authors.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name', sortMode), category: this.getFilterStream((book: Book) => book.metadata?.categories.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
matchScore: this.getFilterStream((book: Book) => getMatchScoreRangeFilters(book.metadataMatchScore), 'id', 'name', 'sortIndex'), series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name', sortMode),
publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name', sortMode), matchScore: this.getFilterStream((book: Book) => getMatchScoreRangeFilters(book.metadataMatchScore), 'id', 'name', 'sortIndex'),
shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name', sortMode), publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name', sortMode),
publishedDate: this.getFilterStream(extractPublishedYearFilter, 'id', 'name', sortMode), shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name', sortMode),
language: this.getFilterStream(getLanguageFilter, 'id', 'name', sortMode), publishedDate: this.getFilterStream(extractPublishedYearFilter, 'id', 'name', sortMode),
fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name', sortMode), language: this.getFilterStream(getLanguageFilter, 'id', 'name', sortMode),
amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name', sortMode), fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name', sortMode),
goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), 'id', 'name', sortMode), amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name', sortMode),
hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name', sortMode), goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), 'id', 'name', sortMode),
pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount!), 'id', 'name', sortMode), hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name', sortMode),
}; pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount!), 'id', 'name', sortMode),
};
this.filterTypes = Object.keys(this.filterStreams); this.filterTypes = Object.keys(this.filterStreams);
this.setExpandedPanels(); this.setExpandedPanels();
}); });
if (this.resetFilter$) { if (this.resetFilter$) {
this.resetFilter$.subscribe(() => this.clearActiveFilter()); this.resetFilter$.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
} }
} }
@@ -298,4 +300,9 @@ export class BookFilterComponent implements OnInit {
onFiltersChanged(): void { onFiltersChanged(): void {
this.setExpandedPanels(); this.setExpandedPanels();
} }
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
} }
@@ -1,15 +1,17 @@
import {Injectable, inject} from '@angular/core';
import {Subject} from 'rxjs'; import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators'; import {debounceTime} from 'rxjs/operators';
import {inject, Injectable} 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({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class CoverScaleManager { export class CoverScalePreferenceService {
private readonly baseWidth = 135;
private readonly baseHeight = 220; private readonly BASE_WIDTH = 135;
private readonly BASE_HEIGHT = 220;
private readonly DEBOUNCE_MS = 1000;
private readonly messageService = inject(MessageService); private readonly messageService = inject(MessageService);
private readonly userService = inject(UserService); private readonly userService = inject(UserService);
@@ -21,8 +23,12 @@ export class CoverScaleManager {
constructor() { constructor() {
this.scaleChange$ this.scaleChange$
.pipe(debounceTime(1000)) .pipe(debounceTime(this.DEBOUNCE_MS))
.subscribe(scale => this.persistScale(scale)); .subscribe(scale => this.saveScalePreference(scale));
}
initScaleValue(scale: number | undefined): void {
this.scaleFactor = scale ?? 1.0;
} }
setScale(scale: number): void { setScale(scale: number): void {
@@ -32,8 +38,8 @@ export class CoverScaleManager {
get currentCardSize(): { width: number; height: number } { get currentCardSize(): { width: number; height: number } {
return { return {
width: Math.round(this.baseWidth * this.scaleFactor), width: Math.round(this.BASE_WIDTH * this.scaleFactor),
height: Math.round(this.baseHeight * this.scaleFactor), height: Math.round(this.BASE_HEIGHT * this.scaleFactor),
}; };
} }
@@ -41,19 +47,20 @@ export class CoverScaleManager {
return `${this.currentCardSize.width}px`; return `${this.currentCardSize.width}px`;
} }
private persistScale(scale: number): void { private saveScalePreference(scale: number): void {
const user = this.userService.getCurrentUser(); const user = this.userService.getCurrentUser();
const entityViewPreferences = user?.userSettings?.entityViewPreferences; const prefs = user?.userSettings?.entityViewPreferences;
if (!user || !entityViewPreferences) {
return; if (!user || !prefs) return;
}
entityViewPreferences.global = entityViewPreferences.global ?? {}; prefs.global = {...prefs.global, coverSize: scale};
entityViewPreferences.global.coverSize = scale; this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
this.userService.updateUserSetting(user.id, 'entityViewPreferences', entityViewPreferences);
this.messageService.add({ this.messageService.add({
severity: 'success', severity: 'success',
summary: 'Cover Size Saved', summary: 'Cover Size Saved',
detail: `Cover size set to ${scale.toFixed(2)}x.` detail: `Cover size set to ${scale.toFixed(2)}x.`,
life: 1500
}); });
} }
} }
@@ -84,7 +84,8 @@ export class SeriesCollapseFilter implements BookFilter {
this.messageService.add({ this.messageService.add({
severity: 'success', severity: 'success',
summary: 'Preference Saved', summary: 'Preference Saved',
detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}.` detail: `Series collapse set to ${isCollapsed ? 'enabled' : 'disabled'}.`,
life: 1500
}); });
} }
} }
@@ -0,0 +1,52 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {UserService} from '../../../../settings/user-management/user.service';
import {MessageService} from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class FilterSortPreferenceService {
readonly filterSortingOptions = [
{ label: 'Alphabetical (A–Z)', value: 'alphabetical' },
{ label: 'Book Count (High to Low)', value: 'count' }
];
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
private readonly sortModeSubject = new BehaviorSubject<'alphabetical' | 'count'>('count');
readonly sortMode$ = this.sortModeSubject.asObservable();
initValue(value: 'alphabetical' | 'count' | null | undefined): void {
const resolved = value ?? 'count';
this.sortModeSubject.next(resolved);
}
get selectedFilterSorting(): 'alphabetical' | 'count' {
return this.sortModeSubject.value;
}
set selectedFilterSorting(value: 'alphabetical' | 'count') {
if (this.sortModeSubject.value !== value) {
this.sortModeSubject.next(value);
this.savePreference(value);
}
}
private savePreference(value: 'alphabetical' | 'count'): void {
const user = this.userService.getCurrentUser();
if (!user) return;
user.userSettings.filterSortingMode = value;
this.userService.updateUserSetting(user.id, 'filterSortingMode', value);
this.messageService.add({
severity: 'success',
summary: 'Preferences Updated',
detail: 'Your filter sorting preference has been saved.',
life: 1500
});
}
}
@@ -178,7 +178,7 @@
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p> <p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p> <p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p>
<p class="whitespace-nowrap flex items-center gap-2"> <p class="whitespace-nowrap flex items-center gap-2">
<span class="font-bold">Match Score:</span> <span class="font-bold">Metadata Score:</span>
@if (book?.metadataMatchScore != null) { @if (book?.metadataMatchScore != null) {
<span <span
class="inline-block px-2 py-0.5 rounded-full text-xs font-bold text-white border" class="inline-block px-2 py-0.5 rounded-full text-xs font-bold text-white border"
@@ -288,12 +288,14 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
} }
getMatchScoreColorClass(score: number): string { getMatchScoreColorClass(score: number): string {
if (score >= 0.95) return 'bg-green-600 border-green-700'; if (score >= 0.95) return 'bg-green-900 border-green-950';
if (score >= 0.90) return 'bg-green-500 border-green-600'; if (score >= 0.90) return 'bg-green-800 border-green-900';
if (score >= 0.80) return 'bg-green-400 border-green-500'; if (score >= 0.80) return 'bg-green-700 border-green-800';
if (score >= 0.70) return 'bg-yellow-500 border-yellow-600'; if (score >= 0.70) return 'bg-yellow-700 border-yellow-800';
if (score >= 0.50) return 'bg-yellow-400 border-yellow-500'; if (score >= 0.60) return 'bg-yellow-600 border-yellow-700';
if (score >= 0.30) return 'bg-red-500 border-red-600'; if (score >= 0.50) return 'bg-yellow-500 border-yellow-600';
return 'bg-red-600 border-red-700'; if (score >= 0.40) return 'bg-red-500 border-red-600';
if (score >= 0.30) return 'bg-red-600 border-red-700';
return 'bg-red-700 border-red-800';
} }
} }
@@ -52,6 +52,7 @@ export interface MetadataProviderSettings {
export interface Amazon { export interface Amazon {
enabled: boolean; enabled: boolean;
cookie: string; cookie: string;
domain: string;
} }
export interface Google { export interface Google {
@@ -1,4 +1,4 @@
import { CommonModule, isPlatformBrowser } from '@angular/common'; import {CommonModule, isPlatformBrowser} from '@angular/common';
import {Component, computed, inject, OnInit, PLATFORM_ID} from '@angular/core'; import {Component, computed, inject, OnInit, PLATFORM_ID} from '@angular/core';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes'; import {$t, updatePreset, updateSurfacePalette} from '@primeng/themes';
@@ -27,12 +27,11 @@ interface Palette {
imports: [CommonModule, FormsModule, InputSwitchModule, ButtonModule, RadioButtonModule, ToggleSwitchModule] imports: [CommonModule, FormsModule, InputSwitchModule, ButtonModule, RadioButtonModule, ToggleSwitchModule]
}) })
export class ThemeConfiguratorComponent implements OnInit { export class ThemeConfiguratorComponent implements OnInit {
readonly config = inject(PrimeNG);
readonly configService = inject(AppConfigService);
readonly platformId = inject(PLATFORM_ID);
config: PrimeNG = inject(PrimeNG); readonly surfaces: Palette[] = [
configService: AppConfigService = inject(AppConfigService);
platformId = inject(PLATFORM_ID);
surfaces = [
{ {
name: 'slate', name: 'slate',
palette: { palette: {
@@ -171,38 +170,35 @@ export class ThemeConfiguratorComponent implements OnInit {
} }
]; ];
selectedPrimaryColor = computed(() => { readonly selectedPrimaryColor = computed(() => this.configService.appState().primary);
return this.configService.appState().primary; readonly selectedSurfaceColor = computed(() => this.configService.appState().surface);
});
selectedSurfaceColor = computed(() => this.configService.appState().surface); readonly primaryColors = computed<Palette[]>(() => {
const presetPalette = (Aura.primitive ?? {}) as Record<string, ColorPalette>;
primaryColors = computed<Palette[]>(() => {
const presetPalette = (Aura.primitive ?? {}) as Partial<Record<string, Palette>>;
const colors = ['emerald', 'green', 'lime', 'orange', 'amber', 'yellow', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']; const colors = ['emerald', 'green', 'lime', 'orange', 'amber', 'yellow', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose'];
return [{ name: 'noir', palette: {} }].concat( return [{ name: 'noir', palette: {} }].concat(
colors.map((color) => ({ colors.map(name => ({
name: color, name,
palette: presetPalette[color] ?? {} palette: presetPalette[name] ?? {}
})) }))
); );
}); });
ngOnInit(): void {
ngOnInit() {
if (isPlatformBrowser(this.platformId)) { if (isPlatformBrowser(this.platformId)) {
this.onPresetChange(); this.onPresetChange();
} }
} }
getPresetExt(): object { getPresetExt(): object {
const color = this.primaryColors().find((c) => c.name === this.selectedPrimaryColor()); const color = this.primaryColors().find(c => c.name === this.selectedPrimaryColor());
if (!color) return {}; // Safe fallback const surface = this.surfaces.find(s => s.name === this.selectedSurfaceColor());
if (!color) return {};
if (color.name === 'noir') { if (color.name === 'noir') {
return { return {
semantic: { semantic: {
primary: {...this.surfaces.find((s) => s.name === this.selectedSurfaceColor())?.palette}, primary: { ...(surface?.palette ?? {}) },
colorScheme: { colorScheme: {
dark: { dark: {
primary: { primary: {
@@ -255,16 +251,17 @@ export class ThemeConfiguratorComponent implements OnInit {
event.stopPropagation(); event.stopPropagation();
} }
applyTheme(type: string, color: any) { applyTheme(type: 'primary' | 'surface', color: { name: string; palette?: ColorPalette }) {
if (type === 'primary') { if (type === 'primary') {
updatePreset(this.getPresetExt()); updatePreset(this.getPresetExt());
} else if (type === 'surface') { } else if (type === 'surface') {
updateSurfacePalette(color.palette); updateSurfacePalette(color.palette ?? {});
} }
} }
onPresetChange() { onPresetChange(): void {
const surfacePalette = this.primaryColors().find(c => c.name === this.selectedSurfaceColor())?.palette; const surface = this.surfaces.find(s => s.name === this.selectedSurfaceColor());
$t().preset(Aura).preset(this.getPresetExt()).surfacePalette(surfacePalette).use({useDefaultOptions: true}); const surfacePalette = surface?.palette ?? {};
$t().preset(Aura).preset(this.getPresetExt()).surfacePalette(surfacePalette).use({ useDefaultOptions: true });
} }
} }
@@ -1,5 +1,5 @@
<p class="text-lg flex items-center gap-2"> <p class="text-lg flex items-center gap-2">
Enabled Metadata Providers: Enabled Metadata Providers:
<i <i
class="pi pi-info-circle text-sky-600" class="pi pi-info-circle text-sky-600"
pTooltip="Enable or configure third-party metadata sources for enhanced book information." pTooltip="Enable or configure third-party metadata sources for enhanced book information."
@@ -13,32 +13,44 @@
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<div class="flex items-center gap-4"> <div class="flex items-center gap-4">
<p-checkbox [(ngModel)]="amazonEnabled" [binary]="true"></p-checkbox> <p-checkbox [(ngModel)]="amazonEnabled" [binary]="true"></p-checkbox>
<label>Amazon</label> <label class="font-medium">Amazon</label>
</div> </div>
<div class="flex items-center gap-4 pl-6">
<input <div class="flex flex-col gap-2 pl-9 pt-1">
type="text" <label class="font-medium text-sm">Region</label>
pInputText <p-select
placeholder="Amazon Cookie (Optional)" [options]="amazonDomains"
class="w-full max-w-3xl" [(ngModel)]="selectedAmazonDomain"
[(ngModel)]="amazonCookie" /> placeholder="Select Domain"
<i class="w-full max-w-52">
class="pi pi-info-circle text-sky-600" </p-select>
pTooltip="Providing your Amazon session cookie allows the app to access richer book metadata and bypass rate limits. Optional but recommended for best results."
tooltipPosition="right" <label class="font-medium text-sm">Cookie (Optional)</label>
style="cursor: pointer;"> <div class="flex items-center gap-2">
</i> <input
type="text"
pInputText
placeholder="Paste your Amazon cookie"
class="w-full max-w-3xl"
[(ngModel)]="amazonCookie" />
<i
class="pi pi-info-circle text-sky-600"
pTooltip="Providing your Amazon session cookie allows the app to access richer book metadata and bypass rate limits. Optional but recommended for best results."
tooltipPosition="right"
style="cursor: pointer;">
</i>
</div>
</div> </div>
</div> </div>
<div class="flex items-center gap-4"> <div class="flex items-center gap-4">
<p-checkbox [(ngModel)]="goodreadsEnabled" [binary]="true"></p-checkbox> <p-checkbox [(ngModel)]="goodreadsEnabled" [binary]="true"></p-checkbox>
<label>Goodreads</label> <label class="font-medium">Goodreads</label>
</div> </div>
<div class="flex items-center gap-4"> <div class="flex items-center gap-4">
<p-checkbox [(ngModel)]="googleEnabled" [binary]="true"></p-checkbox> <p-checkbox [(ngModel)]="googleEnabled" [binary]="true"></p-checkbox>
<label>Google</label> <label class="font-medium">Google</label>
</div> </div>
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
@@ -48,20 +60,21 @@
[(ngModel)]="hardcoverEnabled" [(ngModel)]="hardcoverEnabled"
[disabled]="!hardcoverToken"> [disabled]="!hardcoverToken">
</p-checkbox> </p-checkbox>
<label>Hardcover</label> <label class="font-medium">Hardcover</label>
</div> </div>
<div class="flex items-center gap-4 pl-6"> <div class="flex flex-col gap-2 pl-9 pt-1">
<label class="font-medium text-sm">API Token</label>
<input <input
type="text" type="text"
pInputText pInputText
placeholder="API Token" placeholder="Enter Hardcover API token"
class="w-full max-w-3xl" class="w-full max-w-3xl"
[(ngModel)]="hardcoverToken" [(ngModel)]="hardcoverToken"
(ngModelChange)="onTokenChange($event)" /> (ngModelChange)="onTokenChange($event)" />
</div> </div>
</div> </div>
</div> </div>
<div class="flex justify-start px-4"> <div class="flex justify-start px-4">
<p-button label="Save" icon="pi pi-save" [outlined]="true" (click)="saveSettings()"></p-button> <p-button label="Save" icon="pi pi-save" [outlined]="true" (click)="saveSettings()"></p-button>
</div> </div>
@@ -9,6 +9,7 @@ import {AppSettingsService} from '../../../core/service/app-settings.service';
import {filter, take} from 'rxjs/operators'; import {filter, take} from 'rxjs/operators';
import {MessageService} from 'primeng/api'; import {MessageService} from 'primeng/api';
import {AppSettingKey} from '../../../core/model/app-settings.model'; import {AppSettingKey} from '../../../core/model/app-settings.model';
import {Select} from 'primeng/select';
@Component({ @Component({
selector: 'app-metadata-provider-settings', selector: 'app-metadata-provider-settings',
@@ -19,12 +20,38 @@ import {AppSettingKey} from '../../../core/model/app-settings.model';
Checkbox, Checkbox,
InputText, InputText,
Button, Button,
FormsModule FormsModule,
Select
], ],
templateUrl: './metadata-provider-settings.component.html', templateUrl: './metadata-provider-settings.component.html',
styleUrl: './metadata-provider-settings.component.scss' styleUrl: './metadata-provider-settings.component.scss'
}) })
export class MetadataProviderSettingsComponent implements OnInit { export class MetadataProviderSettingsComponent implements OnInit {
amazonDomains = [
{label: 'amazon.com', value: 'com'},
{label: 'amazon.de', value: 'de'},
{label: 'amazon.co.uk', value: 'co.uk'},
{label: 'amazon.co.jp', value: 'co.jp'},
{label: 'amazon.ca', value: 'ca'},
{label: 'amazon.in', value: 'in'},
{label: 'amazon.com.au', value: 'com.au'},
{label: 'amazon.fr', value: 'fr'},
{label: 'amazon.it', value: 'it'},
{label: 'amazon.es', value: 'es'},
{label: 'amazon.nl', value: 'nl'},
{label: 'amazon.se', value: 'se'},
{label: 'amazon.com.br', value: 'com.br'},
{label: 'amazon.sg', value: 'sg'},
{label: 'amazon.com.mx', value: 'com.mx'},
{label: 'amazon.pl', value: 'pl'},
{label: 'amazon.ae', value: 'ae'},
{label: 'amazon.sa', value: 'sa'},
{label: 'amazon.tr', value: 'tr'}
];
selectedAmazonDomain = 'com';
hardcoverToken: string = ''; hardcoverToken: string = '';
amazonCookie: string = ''; amazonCookie: string = '';
hardcoverEnabled: boolean = false; hardcoverEnabled: boolean = false;
@@ -47,6 +74,7 @@ export class MetadataProviderSettingsComponent implements OnInit {
const metadataProviderSettings = settings!.metadataProviderSettings; const metadataProviderSettings = settings!.metadataProviderSettings;
this.amazonEnabled = metadataProviderSettings?.amazon?.enabled ?? false; this.amazonEnabled = metadataProviderSettings?.amazon?.enabled ?? false;
this.amazonCookie = metadataProviderSettings?.amazon?.cookie ?? ""; this.amazonCookie = metadataProviderSettings?.amazon?.cookie ?? "";
this.selectedAmazonDomain = metadataProviderSettings?.amazon?.domain ?? 'com';
this.goodreadsEnabled = metadataProviderSettings?.goodReads?.enabled ?? false; this.goodreadsEnabled = metadataProviderSettings?.goodReads?.enabled ?? false;
this.googleEnabled = metadataProviderSettings?.google?.enabled ?? false; this.googleEnabled = metadataProviderSettings?.google?.enabled ?? false;
this.hardcoverToken = metadataProviderSettings?.hardcover?.apiKey ?? ''; this.hardcoverToken = metadataProviderSettings?.hardcover?.apiKey ?? '';
@@ -68,7 +96,8 @@ export class MetadataProviderSettingsComponent implements OnInit {
newValue: { newValue: {
amazon: { amazon: {
enabled: this.amazonEnabled, enabled: this.amazonEnabled,
cookie: this.amazonCookie cookie: this.amazonCookie,
domain: this.selectedAmazonDomain
}, },
goodReads: {enabled: this.goodreadsEnabled}, goodReads: {enabled: this.goodreadsEnabled},
google: {enabled: this.googleEnabled}, google: {enabled: this.googleEnabled},
@@ -1,29 +0,0 @@
<div class="p-4">
<div class="flex items-center gap-2 pb-6 pt-4">
<p class="text-lg">Sidebar Filter Sorting:</p>
<i class="pi pi-info-circle text-sky-600"
pTooltip="This setting controls the order in which filter values (like authors, categories, etc.) appear in the sidebar."
tooltipPosition="right"
style="cursor: pointer;">
</i>
</div>
<div class="grid grid-cols-[auto,1fr] pl-6 gap-y-4 gap-x-4 items-center">
<p class="py-1">Sorting Mode:
<i class="pi pi-info-circle text-sky-600"
pTooltip="You can sort filter options alphabetically (A–Z) or by the number of books that match each filter value. For example, categories with more books can appear at the top."
tooltipPosition="right"
style="cursor: pointer;">
</i>
</p>
<div class="flex gap-4 justify-start">
<p-select
size="small"
[options]="filterSortingOptions"
[(ngModel)]="selectedFilterSorting"
(ngModelChange)="onFilterSortingChange()"
placeholder="Select Sorting">
</p-select>
</div>
</div>
</div>
@@ -1,74 +0,0 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {Select} from 'primeng/select';
import {Tooltip} from 'primeng/tooltip';
import {User, UserService, UserSettings} from '../../user-management/user.service';
import {MessageService} from 'primeng/api';
import {Observable, Subscription} from 'rxjs';
import {FormsModule} from '@angular/forms';
@Component({
selector: 'app-sidebar-filter-sorting-prefs-component',
imports: [
Select,
Tooltip,
FormsModule
],
templateUrl: './sidebar-filter-sorting-prefs-component.html',
styleUrl: './sidebar-filter-sorting-prefs-component.scss'
})
export class SidebarFilterSortingPrefsComponent implements OnInit, OnDestroy {
readonly filterSortingOptions = [
{label: 'Alphabetical (A–Z)', value: 'alphabetical'},
{label: 'Book Count (High to Low)', value: 'count'}
];
selectedFilterSorting: 'alphabetical' | 'count' = 'count';
private readonly userService = inject(UserService);
private readonly messageService = inject(MessageService);
userData$: Observable<User | null> = this.userService.userState$;
private subscription?: Subscription;
private currentUser: User | null = null;
ngOnInit(): void {
this.subscription = this.userData$.subscribe(user => {
if (user) {
this.currentUser = user;
this.loadPreferences(user.userSettings);
}
});
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
private loadPreferences(settings: UserSettings): void {
this.selectedFilterSorting = settings.filterSortingMode;
}
private updatePreference(path: string[], value: any): void {
if (!this.currentUser) return;
let target: any = this.currentUser.userSettings;
for (let i = 0; i < path.length - 1; i++) {
target = target[path[i]] ||= {};
}
target[path.at(-1)!] = value;
const [rootKey] = path;
const updatedValue = this.currentUser.userSettings[rootKey as keyof UserSettings];
this.userService.updateUserSetting(this.currentUser.id, rootKey, updatedValue);
this.messageService.add({
severity: 'success',
summary: 'Preferences Updated',
detail: 'Your preferences have been saved successfully.',
life: 2000
});
}
onFilterSortingChange(): void {
this.updatePreference(['filterSortingMode'], this.selectedFilterSorting);
}
}
@@ -68,7 +68,7 @@ export class SidebarSortingPreferencesComponent implements OnInit, OnDestroy {
severity: 'success', severity: 'success',
summary: 'Preferences Updated', summary: 'Preferences Updated',
detail: 'Your preferences have been saved successfully.', detail: 'Your preferences have been saved successfully.',
life: 2000 life: 1500
}); });
} }
@@ -2,6 +2,4 @@
<app-view-preferences></app-view-preferences> <app-view-preferences></app-view-preferences>
<p-divider></p-divider> <p-divider></p-divider>
<app-sidebar-sorting-preferences></app-sidebar-sorting-preferences> <app-sidebar-sorting-preferences></app-sidebar-sorting-preferences>
<p-divider></p-divider>
<app-sidebar-filter-sorting-prefs-component></app-sidebar-filter-sorting-prefs-component>
</div> </div>
@@ -5,7 +5,6 @@ import {TableModule} from 'primeng/table';
import {ToastModule} from 'primeng/toast'; import {ToastModule} from 'primeng/toast';
import {ViewPreferencesComponent} from './view-preferences/view-preferences.component'; import {ViewPreferencesComponent} from './view-preferences/view-preferences.component';
import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/sidebar-sorting-preferences.component'; import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/sidebar-sorting-preferences.component';
import {SidebarFilterSortingPrefsComponent} from './sidebar-filter-sorting-prefs-component/sidebar-filter-sorting-prefs-component';
@Component({ @Component({
selector: 'app-view-preferences-parent', selector: 'app-view-preferences-parent',
@@ -16,8 +15,7 @@ import {SidebarFilterSortingPrefsComponent} from './sidebar-filter-sorting-prefs
TableModule, TableModule,
ToastModule, ToastModule,
ViewPreferencesComponent, ViewPreferencesComponent,
SidebarSortingPreferencesComponent, SidebarSortingPreferencesComponent
SidebarFilterSortingPrefsComponent
], ],
templateUrl: './view-preferences-parent.component.html', templateUrl: './view-preferences-parent.component.html',
styleUrl: './view-preferences-parent.component.scss' styleUrl: './view-preferences-parent.component.scss'