Merge pull request #492 from adityachandelgit/develop
Merge Develop into Master for Release
This commit is contained in:
+11
-2
@@ -3,9 +3,11 @@ package com.adityachandel.booklore.controller;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.*;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.quartz.JobSchedulerService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataUpdater;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -24,6 +26,7 @@ public class MetadataController {
|
||||
private final BookMetadataUpdater bookMetadataUpdater;
|
||||
private final JobSchedulerService jobSchedulerService;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
|
||||
@PostMapping("/{bookId}/metadata/prospective")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@@ -36,8 +39,7 @@ public class MetadataController {
|
||||
public ResponseEntity<BookMetadata> updateMetadata(
|
||||
@RequestBody BookMetadata setMetadataRequest, @PathVariable long bookId,
|
||||
@RequestParam(defaultValue = "true") boolean mergeCategories) {
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(
|
||||
bookMetadataUpdater.setBookMetadata(bookId, setMetadataRequest, true, mergeCategories), true);
|
||||
BookMetadata bookMetadata = bookMetadataMapper.toBookMetadata(bookMetadataUpdater.setBookMetadata(bookId, setMetadataRequest, true, mergeCategories), true);
|
||||
return ResponseEntity.ok(bookMetadata);
|
||||
}
|
||||
|
||||
@@ -79,4 +81,11 @@ public class MetadataController {
|
||||
public void regenerateCovers(@PathVariable Long bookId) {
|
||||
bookMetadataService.regenerateCover(bookId);
|
||||
}
|
||||
|
||||
@PostMapping("/metadata/recalculate-match-scores")
|
||||
@PreAuthorize("@securityUtil.isAdmin()")
|
||||
public ResponseEntity<Void> recalculateMatchScores() {
|
||||
metadataMatchService.recalculateAllMatchScores();
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+14
-34
@@ -42,46 +42,26 @@ public class BookLoreUserTransformer {
|
||||
|
||||
for (UserSettingEntity settingEntity : userEntity.getSettings()) {
|
||||
String key = settingEntity.getSettingKey();
|
||||
String jsonValue = settingEntity.getSettingValue();
|
||||
String value = settingEntity.getSettingValue();
|
||||
|
||||
try {
|
||||
UserSettingKey settingKey = UserSettingKey.fromDbKey(key);
|
||||
|
||||
switch (settingKey) {
|
||||
case PER_BOOK_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.PerBookSetting.class);
|
||||
userSettings.setPerBookSetting(value);
|
||||
if (settingKey.isJson()) {
|
||||
switch (settingKey) {
|
||||
case PER_BOOK_SETTING -> userSettings.setPerBookSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PerBookSetting.class));
|
||||
case PDF_READER_SETTING -> userSettings.setPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PdfReaderSetting.class));
|
||||
case EPUB_READER_SETTING -> userSettings.setEpubReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EpubReaderSetting.class));
|
||||
case CBX_READER_SETTING -> userSettings.setCbxReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.CbxReaderSetting.class));
|
||||
case NEW_PDF_READER_SETTING -> userSettings.setNewPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.NewPdfReaderSetting.class));
|
||||
case SIDEBAR_LIBRARY_SORTING -> userSettings.setSidebarLibrarySorting(objectMapper.readValue(value, SidebarSortOption.class));
|
||||
case SIDEBAR_SHELF_SORTING -> userSettings.setSidebarShelfSorting(objectMapper.readValue(value, SidebarSortOption.class));
|
||||
case ENTITY_VIEW_PREFERENCES -> userSettings.setEntityViewPreferences(objectMapper.readValue(value, BookLoreUser.UserSettings.EntityViewPreferences.class));
|
||||
}
|
||||
case PDF_READER_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.PdfReaderSetting.class);
|
||||
userSettings.setPdfReaderSetting(value);
|
||||
}
|
||||
case EPUB_READER_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.EpubReaderSetting.class);
|
||||
userSettings.setEpubReaderSetting(value);
|
||||
}
|
||||
case CBX_READER_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
|
||||
userSettings.setCbxReaderSetting(value);
|
||||
}
|
||||
case NEW_PDF_READER_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.NewPdfReaderSetting.class);
|
||||
userSettings.setNewPdfReaderSetting(value);
|
||||
}
|
||||
case SIDEBAR_LIBRARY_SORTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
|
||||
userSettings.setSidebarLibrarySorting(value);
|
||||
}
|
||||
case SIDEBAR_SHELF_SORTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
|
||||
userSettings.setSidebarShelfSorting(value);
|
||||
}
|
||||
case ENTITY_VIEW_PREFERENCES -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.EntityViewPreferences.class);
|
||||
userSettings.setEntityViewPreferences(value);
|
||||
} else {
|
||||
if (settingKey == UserSettingKey.FILTER_SORTING_MODE) {
|
||||
userSettings.setFilterSortingMode(value);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Unknown setting key encountered: {}", key);
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -22,6 +22,7 @@ public class Book {
|
||||
private Instant lastReadTime;
|
||||
private Instant addedOn;
|
||||
private BookMetadata metadata;
|
||||
private Float metadataMatchScore;
|
||||
private PdfProgress pdfProgress;
|
||||
private EpubProgress epubProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
|
||||
@@ -41,6 +41,7 @@ public class BookLoreUser {
|
||||
public SidebarSortOption sidebarLibrarySorting;
|
||||
public SidebarSortOption sidebarShelfSorting;
|
||||
public EntityViewPreferences entityViewPreferences;
|
||||
public String filterSortingMode;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
public record ReleaseNote(String version, String name, String changelog, String url) {
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record ReleaseNote(String version, String name, String changelog, String url, LocalDateTime publishedAt) {
|
||||
}
|
||||
|
||||
+1
@@ -10,6 +10,7 @@ public enum AppSettingKey {
|
||||
SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true),
|
||||
METADATA_PROVIDER_SETTINGS("metadata_provider_settings", true),
|
||||
METADATA_MATCH_WEIGHTS("metadata_match_weights", true),
|
||||
|
||||
AUTO_BOOK_SEARCH("auto_book_search", false),
|
||||
COVER_IMAGE_RESOLUTION("cover_image_resolution", false),
|
||||
|
||||
+1
@@ -26,4 +26,5 @@ public class AppSettings {
|
||||
private OidcProviderDetails oidcProviderDetails;
|
||||
private OidcAutoProvisionDetails oidcAutoProvisionDetails;
|
||||
private MetadataProviderSettings metadataProviderSettings;
|
||||
private MetadataMatchWeights metadataMatchWeights;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.adityachandel.booklore.model.dto.settings;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class MetadataMatchWeights {
|
||||
private int title;
|
||||
private int subtitle;
|
||||
private int description;
|
||||
private int authors;
|
||||
private int publisher;
|
||||
private int publishedDate;
|
||||
private int seriesName;
|
||||
private int seriesNumber;
|
||||
private int seriesTotal;
|
||||
private int isbn13;
|
||||
private int isbn10;
|
||||
private int language;
|
||||
private int pageCount;
|
||||
private int categories;
|
||||
private int amazonRating;
|
||||
private int amazonReviewCount;
|
||||
private int goodreadsRating;
|
||||
private int goodreadsReviewCount;
|
||||
private int hardcoverRating;
|
||||
private int hardcoverReviewCount;
|
||||
private int coverImage;
|
||||
|
||||
public int totalWeight() {
|
||||
return title + subtitle + description + authors + publisher + publishedDate +
|
||||
seriesName + seriesNumber + seriesTotal + isbn13 + isbn10 + language +
|
||||
pageCount + categories + amazonRating + amazonReviewCount +
|
||||
goodreadsRating + goodreadsReviewCount + hardcoverRating +
|
||||
hardcoverReviewCount + coverImage;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -11,7 +11,8 @@ public enum UserSettingKey {
|
||||
CBX_READER_SETTING("cbxReaderSetting", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true),
|
||||
ENTITY_VIEW_PREFERENCES("entityViewPreferences", true);
|
||||
ENTITY_VIEW_PREFERENCES("entityViewPreferences", true),
|
||||
FILTER_SORTING_MODE("filterSortingMode", false);
|
||||
|
||||
private final String dbKey;
|
||||
private final boolean isJson;
|
||||
|
||||
@@ -37,6 +37,9 @@ public class BookEntity {
|
||||
@Column(name = "file_size_kb")
|
||||
private Long fileSizeKb;
|
||||
|
||||
@Column(name = "metadata_match_score")
|
||||
private Float metadataMatchScore;
|
||||
|
||||
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private BookMetadataEntity metadata;
|
||||
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ public class UserSettingEntity {
|
||||
@Column(name = "setting_key", nullable = false, length = 100)
|
||||
private String settingKey;
|
||||
|
||||
@Column(name = "setting_value", columnDefinition = "json", nullable = false)
|
||||
@Column(name = "setting_value", nullable = false)
|
||||
private String settingValue;
|
||||
|
||||
@CreationTimestamp
|
||||
|
||||
@@ -9,6 +9,8 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -71,11 +73,15 @@ public class VersionService {
|
||||
String tag = release.get("tag_name").asText();
|
||||
if (isVersionGreater(tag, currentVersion)) {
|
||||
String url = "https://github.com/" + GITHUB_REPO + "/releases/tag/" + tag;
|
||||
String publishedAtStr = release.get("published_at").asText();
|
||||
LocalDateTime publishedAt = LocalDateTime.parse(publishedAtStr, DateTimeFormatter.ISO_DATE_TIME);
|
||||
|
||||
updates.add(new ReleaseNote(
|
||||
tag,
|
||||
release.get("name").asText(),
|
||||
release.get("body").asText(),
|
||||
url
|
||||
url,
|
||||
publishedAt
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -68,6 +68,7 @@ public class AppSettingService {
|
||||
builder.oidcProviderDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_PROVIDER_DETAILS, OidcProviderDetails.class, null, false));
|
||||
builder.oidcAutoProvisionDetails(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.OIDC_AUTO_PROVISION_DETAILS, OidcAutoProvisionDetails.class, null, false));
|
||||
builder.metadataProviderSettings(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_PROVIDER_SETTINGS, MetadataProviderSettings.class, settingPersistenceHelper.getDefaultMetadataProviderSettings(), true));
|
||||
builder.metadataMatchWeights(settingPersistenceHelper.getJsonSetting(settingsMap, AppSettingKey.METADATA_MATCH_WEIGHTS, MetadataMatchWeights.class, settingPersistenceHelper.getDefaultMetadataMatchWeights(), true));
|
||||
|
||||
builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350"));
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true")));
|
||||
|
||||
+27
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.appsettings;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettingKey;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings;
|
||||
import com.adityachandel.booklore.model.entity.AppSettingEntity;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
@@ -140,4 +141,30 @@ public class SettingPersistenceHelper {
|
||||
fieldOptions
|
||||
);
|
||||
}
|
||||
|
||||
public MetadataMatchWeights getDefaultMetadataMatchWeights() {
|
||||
return MetadataMatchWeights.builder()
|
||||
.title(10)
|
||||
.subtitle(1)
|
||||
.description(10)
|
||||
.authors(10)
|
||||
.publisher(5)
|
||||
.publishedDate(3)
|
||||
.seriesName(2)
|
||||
.seriesNumber(2)
|
||||
.seriesTotal(1)
|
||||
.isbn13(3)
|
||||
.isbn10(5)
|
||||
.language(2)
|
||||
.pageCount(1)
|
||||
.categories(10)
|
||||
.amazonRating(3)
|
||||
.amazonReviewCount(2)
|
||||
.goodreadsRating(4)
|
||||
.goodreadsReviewCount(2)
|
||||
.hardcoverRating(2)
|
||||
.hardcoverReviewCount(1)
|
||||
.coverImage(5)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+4
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
@@ -37,6 +38,7 @@ public class CbxProcessor implements FileProcessor {
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -58,6 +60,8 @@ public class CbxProcessor implements FileProcessor {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookEntity = bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
|
||||
+14
-12
@@ -23,6 +23,7 @@ import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
@@ -60,6 +61,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -80,6 +82,8 @@ public class EpubProcessor implements FileProcessor {
|
||||
protected Book processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
|
||||
setBookMetadata(bookEntity);
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
@@ -104,7 +108,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
String href = res.getHref();
|
||||
|
||||
if ((id != null && id.toLowerCase().contains("cover")) ||
|
||||
(href != null && href.toLowerCase().contains("cover"))) {
|
||||
(href != null && href.toLowerCase().contains("cover"))) {
|
||||
|
||||
if (res.getMediaType() != null && res.getMediaType().getName().startsWith("image")) {
|
||||
coverImage = res;
|
||||
@@ -133,14 +137,12 @@ public class EpubProcessor implements FileProcessor {
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
log.debug("***Setting metadata for book {}", bookEntity.getFileName());
|
||||
try (FileInputStream fis =
|
||||
new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
|
||||
try (FileInputStream fis = new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
|
||||
|
||||
io.documentnode.epub4j.domain.Book book =
|
||||
new EpubReader().readEpub(fis);
|
||||
io.documentnode.epub4j.domain.Book book = new EpubReader().readEpub(fis);
|
||||
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
|
||||
if (epubMetadata != null) {
|
||||
bookMetadata.setTitle(truncate(epubMetadata.getFirstTitle(), 1000));
|
||||
@@ -207,7 +209,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Calibre (EPUB2) series tags
|
||||
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
|
||||
if (seriesName != null && !seriesName.isEmpty()) {
|
||||
@@ -228,18 +230,18 @@ public class EpubProcessor implements FileProcessor {
|
||||
extractFromOpf(FileUtils.getBookFullPath(bookEntity), bookMetadata);
|
||||
|
||||
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
|
||||
|
||||
|
||||
// Get subjects and filter out invalid ones
|
||||
List<String> subjects = epubMetadata.getSubjects();
|
||||
List<String> validSubjects = new ArrayList<>();
|
||||
|
||||
|
||||
if (subjects != null && !subjects.isEmpty()) {
|
||||
for (String subject : subjects) {
|
||||
// Skip null or empty subjects
|
||||
if (subject == null || subject.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Skip subjects that are too long (likely not real categories)
|
||||
// Real categories are typically short, descriptive terms
|
||||
if (subject.length() > 100) {
|
||||
@@ -248,7 +250,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
subject.substring(0, Math.min(50, subject.length())) + "...");
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// Skip subjects that contain newlines or excessive whitespace (likely descriptions)
|
||||
if (subject.contains("\n") || subject.contains("\r") || subject.contains(" ")) {
|
||||
log.warn("Skipping subject with newlines/whitespace in {}: '{}'",
|
||||
@@ -260,7 +262,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
validSubjects.add(subject);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
+4
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -39,6 +40,7 @@ public class PdfProcessor implements FileProcessor {
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -62,6 +64,8 @@ public class PdfProcessor implements FileProcessor {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookEntity = bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
|
||||
-1
@@ -136,7 +136,6 @@ public class BookMetadataService {
|
||||
if (metadata != null) {
|
||||
BookMetadataEntity bookMetadata = bookMetadataUpdater.setBookMetadata(bookEntity.getId(), metadata, replaceCover, mergeCategories);
|
||||
bookEntity.setMetadata(bookMetadata);
|
||||
bookRepository.save(bookEntity);
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_UPDATE, book);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Book metadata updated: " + book.getMetadata().getTitle()));
|
||||
|
||||
+6
@@ -32,6 +32,7 @@ public class BookMetadataUpdater {
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final FileService fileService;
|
||||
private final MetadataMatchService metadataMatchService;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public BookMetadataEntity setBookMetadata(long bookId, BookMetadata newMetadata, boolean setThumbnail, boolean mergeCategories) {
|
||||
@@ -51,6 +52,11 @@ public class BookMetadataUpdater {
|
||||
updateThumbnailIfNeeded(bookId, newMetadata, metadata, setThumbnail);
|
||||
|
||||
bookMetadataRepository.save(metadata);
|
||||
|
||||
Float score = metadataMatchService.calculateMatchScore(bookEntity);
|
||||
bookEntity.setMetadataMatchScore(score);
|
||||
bookRepository.save(bookEntity);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.adityachandel.booklore.service.metadata;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.MetadataMatchWeights;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class MetadataMatchService {
|
||||
|
||||
private final AppSettingService appSettingsService;
|
||||
private final BookQueryService bookQueryService;
|
||||
|
||||
public void recalculateAllMatchScores() {
|
||||
List<BookEntity> allBooks = bookQueryService.getAllFullBookEntities();
|
||||
for (BookEntity book : allBooks) {
|
||||
Float score = calculateMatchScore(book);
|
||||
book.setMetadataMatchScore(score);
|
||||
}
|
||||
bookQueryService.saveAll(allBooks);
|
||||
}
|
||||
|
||||
public Float calculateMatchScore(BookEntity book) {
|
||||
if (book == null || book.getMetadata() == null) return 0f;
|
||||
|
||||
BookMetadataEntity metadata = book.getMetadata();
|
||||
|
||||
AppSettings appSettings = appSettingsService.getAppSettings();
|
||||
if (appSettings == null || appSettings.getMetadataMatchWeights() == null) return 0f;
|
||||
|
||||
MetadataMatchWeights weights = appSettings.getMetadataMatchWeights();
|
||||
float totalWeight = weights.totalWeight();
|
||||
if (totalWeight == 0) return 0f;
|
||||
|
||||
float score = 0f;
|
||||
|
||||
if (isPresent(metadata.getTitle())) score += weights.getTitle();
|
||||
if (isPresent(metadata.getSubtitle())) score += weights.getSubtitle();
|
||||
if (isPresent(metadata.getDescription())) score += weights.getDescription();
|
||||
if (hasContent(metadata.getAuthors())) score += weights.getAuthors();
|
||||
if (isPresent(metadata.getPublisher())) score += weights.getPublisher();
|
||||
if (metadata.getPublishedDate() != null) score += weights.getPublishedDate();
|
||||
if (isPresent(metadata.getSeriesName())) score += weights.getSeriesName();
|
||||
if (metadata.getSeriesNumber() != null && metadata.getSeriesNumber() > 0) score += weights.getSeriesNumber();
|
||||
if (metadata.getSeriesTotal() != null && metadata.getSeriesTotal() > 0) score += weights.getSeriesTotal();
|
||||
if (isPresent(metadata.getIsbn13())) score += weights.getIsbn13();
|
||||
if (isPresent(metadata.getIsbn10())) score += weights.getIsbn10();
|
||||
if (isPresent(metadata.getLanguage())) score += weights.getLanguage();
|
||||
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) score += weights.getPageCount();
|
||||
if (hasContent(metadata.getCategories())) score += weights.getCategories();
|
||||
if (isPositive(metadata.getAmazonRating())) score += weights.getAmazonRating();
|
||||
if (isPositive(metadata.getAmazonReviewCount())) score += weights.getAmazonReviewCount();
|
||||
if (isPositive(metadata.getGoodreadsRating())) score += weights.getGoodreadsRating();
|
||||
if (isPositive(metadata.getGoodreadsReviewCount())) score += weights.getGoodreadsReviewCount();
|
||||
if (isPositive(metadata.getHardcoverRating())) score += weights.getHardcoverRating();
|
||||
if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount();
|
||||
if (isPresent(metadata.getThumbnail())) score += weights.getCoverImage();
|
||||
|
||||
return score / totalWeight;
|
||||
}
|
||||
|
||||
private boolean isPresent(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
|
||||
private boolean hasContent(Iterable<?> iterable) {
|
||||
return iterable != null && iterable.iterator().hasNext();
|
||||
}
|
||||
|
||||
private boolean isPositive(Number number) {
|
||||
return number != null && number.doubleValue() > 0;
|
||||
}
|
||||
}
|
||||
+19
-8
@@ -1,17 +1,12 @@
|
||||
package com.adityachandel.booklore.service.migration;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
import com.adityachandel.booklore.repository.AppMigrationRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -19,7 +14,6 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -28,6 +22,8 @@ public class AppMigrationService {
|
||||
|
||||
private AppMigrationRepository migrationRepository;
|
||||
private BookRepository bookRepository;
|
||||
private BookQueryService bookQueryService;
|
||||
private MetadataMatchService metadataMatchService;
|
||||
|
||||
@Transactional
|
||||
public void populateMissingFileSizesOnce() {
|
||||
@@ -52,4 +48,19 @@ public class AppMigrationService {
|
||||
migrationRepository.save(migration);
|
||||
log.info("Migration 'populateFileSizes' executed successfully.");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void populateMetadataScoresOnce() {
|
||||
if (migrationRepository.existsById("populateMetadataScores")) return;
|
||||
|
||||
List<BookEntity> books = bookQueryService.getAllFullBookEntities();
|
||||
for (BookEntity book : books) {
|
||||
Float score = metadataMatchService.calculateMatchScore(book);
|
||||
book.setMetadataMatchScore(score);
|
||||
}
|
||||
bookRepository.saveAll(books);
|
||||
|
||||
log.info("Migration 'populateMetadataScores' applied to {} books.", books.size());
|
||||
migrationRepository.save(new AppMigrationEntity("populateMetadataScores", LocalDateTime.now(), "Calculate and store metadata match score for all books"));
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -14,5 +14,6 @@ public class AppMigrationStartup {
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void runMigrationsOnce() {
|
||||
appMigrationService.populateMissingFileSizesOnce();
|
||||
appMigrationService.populateMetadataScoresOnce();
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -29,6 +29,7 @@ public class DefaultUserSettingsProvider {
|
||||
defaultSettings.put(UserSettingKey.SIDEBAR_LIBRARY_SORTING, this::buildDefaultSidebarLibrarySorting);
|
||||
defaultSettings.put(UserSettingKey.SIDEBAR_SHELF_SORTING, this::buildDefaultSidebarShelfSorting);
|
||||
defaultSettings.put(UserSettingKey.ENTITY_VIEW_PREFERENCES, this::buildDefaultEntityViewPreferences);
|
||||
defaultSettings.put(UserSettingKey.FILTER_SORTING_MODE, () -> "count");
|
||||
}
|
||||
|
||||
public Set<UserSettingKey> getAllKeys() {
|
||||
|
||||
+17
-4
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.dto.request.ChangePasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ChangeUserPasswordRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UpdateUserSettingRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.UserUpdateRequest;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
@@ -121,7 +122,8 @@ public class UserService {
|
||||
}
|
||||
|
||||
public void updateUserSetting(Long userId, UpdateUserSettingRequest request) {
|
||||
BookLoreUserEntity user = userRepository.findById(userId).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
BookLoreUserEntity user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
String key = request.getKey();
|
||||
Object value = request.getValue();
|
||||
@@ -130,7 +132,12 @@ public class UserService {
|
||||
throw ApiError.INVALID_INPUT.createException("Setting key cannot be null or blank.");
|
||||
}
|
||||
|
||||
JsonNode valueNode = objectMapper.valueToTree(value);
|
||||
UserSettingKey settingKey;
|
||||
try {
|
||||
settingKey = UserSettingKey.fromDbKey(key);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw ApiError.INVALID_INPUT.createException("Unknown setting key: " + key);
|
||||
}
|
||||
|
||||
UserSettingEntity setting = user.getSettings().stream()
|
||||
.filter(s -> s.getSettingKey().equals(key))
|
||||
@@ -144,8 +151,14 @@ public class UserService {
|
||||
});
|
||||
|
||||
try {
|
||||
setting.setSettingValue(objectMapper.writeValueAsString(valueNode));
|
||||
} catch (JsonProcessingException e) {
|
||||
String serializedValue;
|
||||
if (settingKey.isJson()) {
|
||||
serializedValue = objectMapper.writeValueAsString(value);
|
||||
} else {
|
||||
serializedValue = value.toString();
|
||||
}
|
||||
setting.setSettingValue(serializedValue);
|
||||
} catch (Exception e) {
|
||||
throw ApiError.INVALID_INPUT.createException("Could not serialize setting value.");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE book
|
||||
ADD COLUMN metadata_match_score FLOAT;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE user_settings
|
||||
MODIFY setting_value TEXT NOT NULL;
|
||||
@@ -46,44 +46,34 @@
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
(click)="seriesCollapseOverlay.toggle($event)"
|
||||
pTooltip="Series collapse settings"
|
||||
pTooltip="Display settings"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-cog"></i>
|
||||
</a>
|
||||
<p-popover #seriesCollapseOverlay [dismissable]="true" appendTo="body">
|
||||
<div class="w-[220px] p-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-[220px] p-3 space-y-4 text-sm">
|
||||
<div class="flex flex-col gap-2">
|
||||
<label for="collapse-series-checkbox" class="font-medium">Collapse series</label>
|
||||
<p-checkbox
|
||||
inputId="collapse-series-checkbox"
|
||||
[binary]="true"
|
||||
[ngModel]="seriesCollapseFilter.isSeriesCollapsed"
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)"
|
||||
inputId="collapse-series-checkbox">
|
||||
(onChange)="onSeriesCollapseCheckboxChange($event.checked)">
|
||||
</p-checkbox>
|
||||
<label for="collapse-series-checkbox">Collapse series</label>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
</div>
|
||||
<div>
|
||||
<a
|
||||
class="topbar-items topbar-item"
|
||||
(click)="sizeOverlay.toggle($event)"
|
||||
pTooltip="Adjust grid item scale"
|
||||
tooltipPosition="top">
|
||||
<i class="pi pi-th-large"></i>
|
||||
</a>
|
||||
<p-popover #sizeOverlay [dismissable]="true" appendTo="body">
|
||||
<div style="width: 220px; padding: 8px;">
|
||||
<p-slider
|
||||
[(ngModel)]="coverScaleManager.scaleFactor"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }"
|
||||
(onChange)="updateScale()"
|
||||
></p-slider>
|
||||
<div style="text-align: center; margin-top: 8px;">
|
||||
{{ coverScaleManager.scaleFactor.toFixed(2) }}x
|
||||
<div class="flex flex-col gap-2">
|
||||
<label class="font-medium text-sm">Grid item size</label>
|
||||
<p-slider
|
||||
[(ngModel)]="coverScaleManager.scaleFactor"
|
||||
[min]="0.5"
|
||||
[max]="1.5"
|
||||
[step]="0.01"
|
||||
[style]="{ width: '100%' }"
|
||||
(onChange)="updateScale()">
|
||||
</p-slider>
|
||||
<div class="text-center">
|
||||
{{ coverScaleManager.scaleFactor.toFixed(2) }}x
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</p-popover>
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 1.5rem;
|
||||
font-size: 5rem;
|
||||
border: 1px solid var(--border-color);
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
|
||||
@@ -29,15 +29,16 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
import {Fluid} from 'primeng/fluid';
|
||||
import {EntityViewPreferences, UserService} from '../../../settings/user-management/user.service';
|
||||
import {OverlayPanelModule} from 'primeng/overlaypanel';
|
||||
import {Slider} from 'primeng/slider';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {SeriesCollapseFilter} from './filters/SeriesCollapseFilter';
|
||||
import {SideBarFilter} from './filters/SidebarFilter';
|
||||
import {HeaderFilter} from './filters/HeaderFilter';
|
||||
import {CoverScaleManager} from './CoverScaleManager';
|
||||
import {BookSorter} from './sorting/BookSorter';
|
||||
import {BookDialogHelperService} from './BookDialogHelperService';
|
||||
import {DropdownModule} from 'primeng/dropdown';
|
||||
import {Checkbox} from 'primeng/checkbox';
|
||||
import {Popover} from 'primeng/popover';
|
||||
import {Slider} from 'primeng/slider';
|
||||
|
||||
export enum EntityType {
|
||||
LIBRARY = 'Library',
|
||||
@@ -70,7 +71,7 @@ const SORT_DIRECTION = {
|
||||
standalone: true,
|
||||
templateUrl: './book-browser.component.html',
|
||||
styleUrls: ['./book-browser.component.scss'],
|
||||
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, Slider, Popover, Checkbox],
|
||||
imports: [Button, VirtualScrollerModule, BookCardComponent, AsyncPipe, ProgressSpinner, Menu, InputText, FormsModule, BookTableComponent, BookFilterComponent, Tooltip, NgClass, Fluid, PrimeTemplate, NgStyle, OverlayPanelModule, DropdownModule, Checkbox, Popover, Slider],
|
||||
providers: [SeriesCollapseFilter],
|
||||
animations: [
|
||||
trigger('slideInOut', [
|
||||
@@ -129,8 +130,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
private router = inject(Router);
|
||||
private changeDetectorRef = inject(ChangeDetectorRef);
|
||||
private libraryShelfMenuService = inject(LibraryShelfMenuService);
|
||||
protected seriesCollapseFilter = inject(SeriesCollapseFilter);
|
||||
|
||||
protected seriesCollapseFilter = new SeriesCollapseFilter();
|
||||
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
|
||||
private headerFilter = new HeaderFilter(this.searchTerm$);
|
||||
protected bookSorter = new BookSorter((selectedSort) => this.applySortOption(selectedSort));
|
||||
@@ -432,7 +433,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
return bookState;
|
||||
}
|
||||
|
||||
|
||||
private fetchLibrary(libraryId: number): Observable<Library | null> {
|
||||
return this.libraryService.libraryState$.pipe(
|
||||
map(libraryState => {
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
}
|
||||
</span>
|
||||
</p-accordion-header>
|
||||
<p-accordion-content class="h-[31rem] !overflow-y-auto">
|
||||
<p-accordion-content class="h-[27.5rem] !overflow-y-auto">
|
||||
@if (filterStreams[filterType] | async; as filters) {
|
||||
<div>
|
||||
@for (filter of filters; track filter) {
|
||||
|
||||
+66
-22
@@ -1,6 +1,6 @@
|
||||
import {Component, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
|
||||
import {combineLatest, Observable, of, Subject} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {filter, map, take} from 'rxjs/operators';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {Library} from '../../../model/library.model';
|
||||
import {Shelf} from '../../../model/shelf.model';
|
||||
@@ -11,6 +11,7 @@ import {AsyncPipe, NgClass, TitleCasePipe} from '@angular/common';
|
||||
import {Badge} from 'primeng/badge';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
type Filter<T> = { value: T; bookCount: number };
|
||||
|
||||
@@ -44,6 +45,16 @@ export const pageCountRanges = [
|
||||
{id: '1000plus', label: '1000+ pages', min: 1000, max: Infinity}
|
||||
];
|
||||
|
||||
export const matchScoreRanges = [
|
||||
{id: '0.95-1.0', min: 0.95, max: 1.01, name: 'Outstanding (95–100%)', sortIndex: 0},
|
||||
{id: '0.90-0.94', min: 0.90, max: 0.95, name: 'Excellent (90–94%)', sortIndex: 1},
|
||||
{id: '0.80-0.89', min: 0.80, max: 0.90, name: 'Great (80–89%)', sortIndex: 2},
|
||||
{id: '0.70-0.79', min: 0.70, max: 0.80, name: 'Good (70–79%)', sortIndex: 3},
|
||||
{id: '0.50-0.69', min: 0.50, max: 0.70, name: 'Fair (50–69%)', sortIndex: 4},
|
||||
{id: '0.30-0.49', min: 0.30, max: 0.50, name: 'Weak (30–49%)', sortIndex: 5},
|
||||
{id: '0.00-0.29', min: 0.00, max: 0.30, name: 'Poor (0–29%)', sortIndex: 6}
|
||||
];
|
||||
|
||||
const getLanguageFilter = (book: Book) => {
|
||||
const lang = book.metadata?.language;
|
||||
return lang ? [{id: lang, name: lang}] : [];
|
||||
@@ -79,6 +90,12 @@ function getPageCountRangeFilters(pageCount?: number) {
|
||||
return match ? [{id: match.id, name: match.label}] : [];
|
||||
}
|
||||
|
||||
export function getMatchScoreRangeFilters(score?: number | null): { id: string; name: string; sortIndex?: number }[] {
|
||||
if (score == null) return [];
|
||||
const match = matchScoreRanges.find(r => score >= r.min && score < r.max);
|
||||
return match ? [{id: match.id, name: match.name, sortIndex: match.sortIndex}] : [];
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-filter',
|
||||
templateUrl: './book-filter.component.html',
|
||||
@@ -128,45 +145,62 @@ export class BookFilterComponent implements OnInit {
|
||||
shelfStatus: 'Shelf Status',
|
||||
pageCount: 'Page Count',
|
||||
language: 'Language',
|
||||
matchScore: 'Metadata Match Score'
|
||||
};
|
||||
|
||||
bookService = inject(BookService);
|
||||
userService = inject(UserService);
|
||||
|
||||
ngOnInit(): void {
|
||||
if (this.entity$ && this.entityType$) {
|
||||
combineLatest([
|
||||
this.userService.userState$.pipe(
|
||||
filter((u): u is NonNullable<typeof u> => !!u),
|
||||
take(1)
|
||||
),
|
||||
this.entity$ ?? of(null),
|
||||
this.entityType$ ?? of(EntityType.ALL_BOOKS)
|
||||
]).subscribe(([user]) => {
|
||||
const sortMode = user.userSettings?.filterSortingMode ?? 'count';
|
||||
this.filterStreams = {
|
||||
author: this.getFilterStream((book: Book) => book.metadata?.authors.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
category: this.getFilterStream((book: Book) => book.metadata?.categories.map(name => ({id: name, name})) || [], 'id', 'name'),
|
||||
series: this.getFilterStream((book) => (book.metadata?.seriesName ? [{id: book.metadata.seriesName, name: book.metadata.seriesName}] : []), 'id', 'name'),
|
||||
publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name'),
|
||||
amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name'),
|
||||
goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), 'id', 'name'),
|
||||
hardcoverRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.hardcoverRating!), 'id', 'name'),
|
||||
publishedDate: this.getFilterStream(extractPublishedYearFilter, 'id', 'name'),
|
||||
fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name'),
|
||||
pageCount: this.getFilterStream((book: Book) => getPageCountRangeFilters(book.metadata?.pageCount!), 'id', 'name'),
|
||||
language: this.getFilterStream(getLanguageFilter, 'id', 'name'),
|
||||
shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name')
|
||||
author: this.getFilterStream((book: Book) => book.metadata?.authors.map(name => ({id: name, name})) || [], 'id', 'name', sortMode),
|
||||
category: this.getFilterStream((book: Book) => book.metadata?.categories.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),
|
||||
matchScore: this.getFilterStream((book: Book) => getMatchScoreRangeFilters(book.metadataMatchScore), 'id', 'name', 'sortIndex'),
|
||||
publisher: this.getFilterStream((book) => (book.metadata?.publisher ? [{id: book.metadata.publisher, name: book.metadata.publisher}] : []), 'id', 'name', sortMode),
|
||||
shelfStatus: this.getFilterStream(getShelfStatusFilter, 'id', 'name', sortMode),
|
||||
publishedDate: this.getFilterStream(extractPublishedYearFilter, 'id', 'name', sortMode),
|
||||
language: this.getFilterStream(getLanguageFilter, 'id', 'name', sortMode),
|
||||
fileSize: this.getFilterStream((book: Book) => getFileSizeRangeFilters(book.fileSizeKb), 'id', 'name', sortMode),
|
||||
amazonRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.amazonRating!), 'id', 'name', sortMode),
|
||||
goodreadsRating: this.getFilterStream((book: Book) => getRatingRangeFilters(book.metadata?.goodreadsRating!), '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.setExpandedPanels();
|
||||
});
|
||||
|
||||
if (this.resetFilter$) {
|
||||
this.resetFilter$.subscribe(() => this.clearActiveFilter());
|
||||
}
|
||||
|
||||
this.setExpandedPanels();
|
||||
}
|
||||
|
||||
private getFilterStream<T>(
|
||||
extractor: (book: Book) => T[] | undefined,
|
||||
idKey: keyof T,
|
||||
nameKey: keyof T
|
||||
nameKey: keyof T,
|
||||
sortMode: 'count' | 'alphabetical' | 'sortIndex' = 'count'
|
||||
): Observable<Filter<T[keyof T]>[]> {
|
||||
return combineLatest([this.bookService.bookState$, this.entity$ ?? of(null), this.entityType$ ?? of(EntityType.ALL_BOOKS)]).pipe(
|
||||
return combineLatest([
|
||||
this.bookService.bookState$,
|
||||
this.entity$ ?? of(null),
|
||||
this.entityType$ ?? of(EntityType.ALL_BOOKS)
|
||||
]).pipe(
|
||||
map(([state, entity, entityType]) => {
|
||||
const filteredBooks = this.filterBooksByEntityType(state.books || [], entity, entityType);
|
||||
const filterMap = new Map<any, Filter<any>>();
|
||||
|
||||
filteredBooks.forEach((book) => {
|
||||
(extractor(book) || []).forEach((item) => {
|
||||
const id = item[idKey];
|
||||
@@ -176,11 +210,21 @@ export class BookFilterComponent implements OnInit {
|
||||
filterMap.get(id)!.bookCount += 1;
|
||||
});
|
||||
});
|
||||
return Array.from(filterMap.values()).sort(
|
||||
(a, b) =>
|
||||
|
||||
const result = Array.from(filterMap.values());
|
||||
|
||||
return result.sort((a, b) => {
|
||||
if (sortMode === 'sortIndex') {
|
||||
return (a.value.sortIndex ?? 999) - (b.value.sortIndex ?? 999);
|
||||
}
|
||||
if (sortMode === 'alphabetical') {
|
||||
return a.value[nameKey].toString().localeCompare(b.value[nameKey].toString());
|
||||
}
|
||||
return (
|
||||
b.bookCount - a.bookCount ||
|
||||
a.value[nameKey].toString().localeCompare(b.value[nameKey].toString())
|
||||
);
|
||||
);
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { BookFilter } from './BookFilter';
|
||||
import { Observable, BehaviorSubject } from 'rxjs';
|
||||
import { BookState } from '../../../model/state/book-state.model';
|
||||
import { map, debounceTime, filter, take } from 'rxjs/operators';
|
||||
import { Book } from '../../../model/book.model';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { MessageService } from 'primeng/api';
|
||||
import { UserService } from '../../../../settings/user-management/user.service';
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {Observable, BehaviorSubject} from 'rxjs';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {map, debounceTime, filter, take} from 'rxjs/operators';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {UserService} from '../../../../settings/user-management/user.service';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class SeriesCollapseFilter implements BookFilter {
|
||||
private readonly userService = inject(UserService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
@@ -66,7 +66,7 @@ export class SeriesCollapseFilter implements BookFilter {
|
||||
}
|
||||
}
|
||||
|
||||
return { ...bookState, books: collapsedBooks };
|
||||
return {...bookState, books: collapsedBooks};
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import {Observable, combineLatest, of} from 'rxjs';
|
||||
import {map} from 'rxjs/operators';
|
||||
import {BookFilter} from './BookFilter';
|
||||
import {BookState} from '../../../model/state/book-state.model';
|
||||
import {fileSizeRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.component';
|
||||
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.component';
|
||||
|
||||
export function isRatingInRange(rating: number | undefined | null, rangeId: string): boolean {
|
||||
if (rating == null) return false;
|
||||
@@ -25,6 +25,13 @@ export function isPageCountInRange(pageCount: number | undefined, rangeId: strin
|
||||
return pageCount >= range.min && pageCount < range.max;
|
||||
}
|
||||
|
||||
export function isMatchScoreInRange(score: number | undefined | null, rangeId: string): boolean {
|
||||
if (score == null) return false;
|
||||
const range = matchScoreRanges.find(r => r.id === rangeId);
|
||||
if (!range) return false;
|
||||
return score >= range.min && score < range.max;
|
||||
}
|
||||
|
||||
export class SideBarFilter implements BookFilter {
|
||||
|
||||
constructor(private selectedFilter$: Observable<any>, private selectedFilterMode$: Observable<'and' | 'or'>) {
|
||||
@@ -73,6 +80,8 @@ export class SideBarFilter implements BookFilter {
|
||||
return filterValues.some(range => isPageCountInRange(book.metadata?.pageCount!, range));
|
||||
case 'language':
|
||||
return filterValues.includes(book.metadata?.language);
|
||||
case 'matchScore':
|
||||
return filterValues.some(range => isMatchScoreInRange(book.metadataMatchScore, range));
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
+13
-3
@@ -133,11 +133,9 @@
|
||||
<img src="https://books.google.com/favicon.ico" alt="Google Books"
|
||||
class="w-5 h-5 object-contain transform transition duration-200 hover:scale-125 hover:drop-shadow-lg"/>
|
||||
</a>
|
||||
|
||||
}
|
||||
|
||||
} @else {
|
||||
|
||||
<p-rating
|
||||
[(ngModel)]="metadata.rating"
|
||||
readonly
|
||||
@@ -179,10 +177,22 @@
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ metadata.publishedDate || '-' }}</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 13:</span> {{ metadata.isbn13 || '-' }}</p>
|
||||
<p class="whitespace-nowrap flex items-center gap-2">
|
||||
<span class="font-bold">Match Score:</span>
|
||||
@if (book?.metadataMatchScore != null) {
|
||||
<span
|
||||
class="inline-block px-2 py-0.5 rounded-full text-xs font-bold text-white border"
|
||||
[ngClass]="getMatchScoreColorClass(book?.metadataMatchScore!)">
|
||||
{{ (book?.metadataMatchScore! * 100) | number:'1.0-0' }}%
|
||||
</span>
|
||||
} @else {
|
||||
<span>-</span>
|
||||
}
|
||||
</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ metadata.pageCount || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB() }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Progress:</span> {{ getProgressPercent() !== null ? getProgressPercent() + '%' : '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ metadata.isbn13 || '-' }}</p>
|
||||
</div>
|
||||
<div class="pt-2 flex items-center gap-2 w-full">
|
||||
<span class="font-semibold flex-shrink-0">File Path:</span>
|
||||
|
||||
+15
-10
@@ -1,6 +1,6 @@
|
||||
import {Component, DestroyRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {Button, ButtonDirective} from 'primeng/button';
|
||||
import { AsyncPipe, DecimalPipe, NgClass } from '@angular/common';
|
||||
import {AsyncPipe, DecimalPipe, NgClass} from '@angular/common';
|
||||
import {first, Observable} from 'rxjs';
|
||||
import {BookService} from '../../../service/book.service';
|
||||
import {BookMetadataCenterService} from '../book-metadata-center.service';
|
||||
@@ -159,10 +159,6 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
this.bookService.readBook(bookId!, reader);
|
||||
}
|
||||
|
||||
getAuthorNames(authors: string[]): string {
|
||||
return authors.join(', ');
|
||||
}
|
||||
|
||||
download(bookId: number) {
|
||||
this.bookService.downloadFile(bookId);
|
||||
}
|
||||
@@ -258,15 +254,14 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
}
|
||||
|
||||
getFileTypeColorClass(fileType: string | null | undefined): string {
|
||||
if (!fileType) return 'bg-gray-500 text-white';
|
||||
|
||||
if (!fileType) return 'bg-gray-600 text-white';
|
||||
switch (fileType.toLowerCase()) {
|
||||
case 'pdf':
|
||||
return 'bg-red-700 text-white';
|
||||
return 'bg-pink-700 text-white';
|
||||
case 'epub':
|
||||
return 'bg-yellow-600 text-gray-900';
|
||||
return 'bg-indigo-600 text-white';
|
||||
case 'cbz':
|
||||
return 'bg-green-700 text-white';
|
||||
return 'bg-teal-600 text-white';
|
||||
case 'cbr':
|
||||
return 'bg-purple-700 text-white';
|
||||
case 'cb7':
|
||||
@@ -291,4 +286,14 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
return 'rgb(239, 68, 68)';
|
||||
}
|
||||
}
|
||||
|
||||
getMatchScoreColorClass(score: number): string {
|
||||
if (score >= 0.95) return 'bg-green-600 border-green-700';
|
||||
if (score >= 0.90) return 'bg-green-500 border-green-600';
|
||||
if (score >= 0.80) return 'bg-green-400 border-green-500';
|
||||
if (score >= 0.70) return 'bg-yellow-500 border-yellow-600';
|
||||
if (score >= 0.50) return 'bg-yellow-400 border-yellow-500';
|
||||
if (score >= 0.30) return 'bg-red-500 border-red-600';
|
||||
return 'bg-red-600 border-red-700';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface Book {
|
||||
filePath?: string;
|
||||
fileSizeKb?: number;
|
||||
seriesCount?: number | null;
|
||||
metadataMatchScore?: number | null;
|
||||
}
|
||||
|
||||
export interface EpubProgress {
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
import {MetadataRefreshOptions} from '../../book/metadata/model/request/metadata-refresh-options.model';
|
||||
|
||||
export interface MetadataMatchWeights {
|
||||
title: number;
|
||||
subtitle: number;
|
||||
description: number;
|
||||
authors: number;
|
||||
publisher: number;
|
||||
publishedDate: number;
|
||||
seriesName: number;
|
||||
seriesNumber: number;
|
||||
seriesTotal: number;
|
||||
isbn13: number;
|
||||
isbn10: number;
|
||||
language: number;
|
||||
pageCount: number;
|
||||
categories: number;
|
||||
amazonRating: number;
|
||||
amazonReviewCount: number;
|
||||
goodreadsRating: number;
|
||||
goodreadsReviewCount: number;
|
||||
hardcoverRating: number;
|
||||
hardcoverReviewCount: number;
|
||||
coverImage: number;
|
||||
}
|
||||
|
||||
export interface OidcProviderDetails {
|
||||
providerName: string;
|
||||
clientId: string;
|
||||
@@ -57,6 +81,7 @@ export interface AppSettings {
|
||||
cbxCacheSizeInMb: number;
|
||||
maxFileUploadSizeInMb: number;
|
||||
metadataProviderSettings: MetadataProviderSettings;
|
||||
metadataMatchWeights: MetadataMatchWeights;
|
||||
}
|
||||
|
||||
export enum AppSettingKey {
|
||||
@@ -71,5 +96,6 @@ export enum AppSettingKey {
|
||||
OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS',
|
||||
CBX_CACHE_SIZE_IN_MB = 'CBX_CACHE_SIZE_IN_MB',
|
||||
MAX_FILE_UPLOAD_SIZE_IN_MB = 'MAX_FILE_UPLOAD_SIZE_IN_MB',
|
||||
METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS'
|
||||
METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS',
|
||||
METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS'
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface ReleaseNote {
|
||||
name: string;
|
||||
changelog: string;
|
||||
url: string;
|
||||
publishedAt: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@
|
||||
<div class="border-b pb-4">
|
||||
<p class="font-bold text-2xl pb-2">
|
||||
<a [href]="release.url" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:underline">
|
||||
{{ release.name }}
|
||||
{{ release.name }} ({{ release.publishedAt | date: 'mediumDate' }})
|
||||
</a>
|
||||
</p>
|
||||
<div [innerHTML]="markdownToHtml(release.changelog)" class="prose prose-invert w-full max-w-full"></div>
|
||||
|
||||
+4
-1
@@ -3,11 +3,14 @@ import { ReleaseNote, VersionService } from '../../../../core/service/version.se
|
||||
|
||||
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
|
||||
import showdown from 'showdown';
|
||||
import {DatePipe} from '@angular/common';
|
||||
|
||||
@Component({
|
||||
selector: 'app-version-changelog-dialog',
|
||||
standalone: true,
|
||||
imports: [],
|
||||
imports: [
|
||||
DatePipe
|
||||
],
|
||||
templateUrl: './version-changelog-dialog.component.html',
|
||||
styleUrl: './version-changelog-dialog.component.scss'
|
||||
})
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from './config/api-config';
|
||||
|
||||
export interface MetadataMatchWeights {
|
||||
title: number;
|
||||
subtitle: number;
|
||||
description: number;
|
||||
publisher: number;
|
||||
publishedDate: number;
|
||||
authors: number;
|
||||
categories: number;
|
||||
seriesName: number;
|
||||
seriesNumber: number;
|
||||
isbn13: number;
|
||||
isbn10: number;
|
||||
pageCount: number;
|
||||
language: number;
|
||||
amazonRating: number;
|
||||
amazonReviewCount: number;
|
||||
goodreadsRating: number;
|
||||
goodreadsReviewCount: number;
|
||||
hardcoverRating: number;
|
||||
hardcoverReviewCount: number;
|
||||
coverImage: number;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class MetadataMatchWeightsService {
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
|
||||
recalculateAll(): Observable<void> {
|
||||
return this.http.post<void>(`${this.baseUrl}/books/metadata/recalculate-match-scores`, {});
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<div class="flex pb-8">
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
Recalculate Metadata Scores:
|
||||
<i
|
||||
class="pi pi-info-circle text-blue-500"
|
||||
pTooltip="Recomputes match scores for all books based on the latest weights."
|
||||
tooltipPosition="right"
|
||||
style="cursor: help;"
|
||||
></i>
|
||||
</p>
|
||||
|
||||
<p-button
|
||||
class="pl-4"
|
||||
type="button"
|
||||
icon="pi pi-refresh"
|
||||
label="Recalculate"
|
||||
[disabled]="isRecalculating"
|
||||
(click)="recalculate()"
|
||||
outlined
|
||||
></p-button>
|
||||
</div>
|
||||
|
||||
|
||||
<p class="text-lg flex items-center gap-2">
|
||||
Metadata Field Weights
|
||||
<i
|
||||
class="pi pi-info-circle text-blue-500"
|
||||
pTooltip="Adjust how important each metadata field is when computing match scores. Higher weights make fields more influential."
|
||||
tooltipPosition="right"
|
||||
style="cursor: help;"
|
||||
></i>
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col space-y-6 p-4">
|
||||
<div class="p-4 space-y-4 max-w-4xl custom-border">
|
||||
<form [formGroup]="form">
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-y-4 gap-x-6">
|
||||
@for (key of orderedKeys; track key) {
|
||||
<div class="flex items-center gap-2">
|
||||
<label class="capitalize w-full max-w-[150px]">
|
||||
{{ labelMap[key] }}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
pInputText
|
||||
[formControlName]="key"
|
||||
class="w-20 text-center"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="mt-4 flex justify-end">
|
||||
<p-button
|
||||
type="button"
|
||||
label="Save"
|
||||
icon="pi pi-save"
|
||||
outlined
|
||||
[disabled]="isSaving"
|
||||
(click)="save()">
|
||||
</p-button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
.custom-border {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--card-border);
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {MetadataMatchWeightsService} from '../../../metadata-match-weights-service';
|
||||
import {Button} from 'primeng/button';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettingKey, AppSettings} from '../../../core/model/app-settings.model';
|
||||
import {AppSettingsService} from '../../../core/service/app-settings.service';
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-match-weights-component',
|
||||
imports: [
|
||||
ReactiveFormsModule,
|
||||
Button,
|
||||
InputText,
|
||||
Tooltip
|
||||
],
|
||||
templateUrl: './metadata-match-weights-component.html',
|
||||
styleUrl: './metadata-match-weights-component.scss'
|
||||
})
|
||||
export class MetadataMatchWeightsComponent implements OnInit {
|
||||
|
||||
readonly labelMap: Record<string, string> = {
|
||||
title: 'Title',
|
||||
subtitle: 'Subtitle',
|
||||
authors: 'Authors',
|
||||
description: 'Description',
|
||||
publisher: 'Publisher',
|
||||
publishedDate: 'Published Date',
|
||||
categories: 'Categories',
|
||||
coverImage: 'Cover Image',
|
||||
seriesName: 'Series Name',
|
||||
seriesNumber: 'Series Number',
|
||||
language: 'Language',
|
||||
isbn13: 'ISBN-13',
|
||||
isbn10: 'ISBN-10',
|
||||
pageCount: 'Page Count',
|
||||
amazonRating: 'Amazon Rating',
|
||||
amazonReviewCount: 'Amazon Rating # ',
|
||||
goodreadsRating: 'Goodreads Rating',
|
||||
goodreadsReviewCount: 'Goodreads Rating #',
|
||||
hardcoverRating: 'Hardcover Rating',
|
||||
hardcoverReviewCount: 'Hardcover Rating #'
|
||||
};
|
||||
|
||||
form!: FormGroup;
|
||||
isSaving = false;
|
||||
isRecalculating = false;
|
||||
|
||||
private weightsService = inject(MetadataMatchWeightsService);
|
||||
private appSettingsService = inject(AppSettingsService);
|
||||
private messageService = inject(MessageService);
|
||||
private fb = inject(FormBuilder);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.form = this.fb.group({
|
||||
title: [0, [Validators.required, Validators.min(0)]],
|
||||
subtitle: [0, [Validators.required, Validators.min(0)]],
|
||||
description: [0, [Validators.required, Validators.min(0)]],
|
||||
publisher: [0, [Validators.required, Validators.min(0)]],
|
||||
publishedDate: [0, [Validators.required, Validators.min(0)]],
|
||||
authors: [0, [Validators.required, Validators.min(0)]],
|
||||
categories: [0, [Validators.required, Validators.min(0)]],
|
||||
seriesName: [0, [Validators.required, Validators.min(0)]],
|
||||
seriesNumber: [0, [Validators.required, Validators.min(0)]],
|
||||
isbn13: [0, [Validators.required, Validators.min(0)]],
|
||||
isbn10: [0, [Validators.required, Validators.min(0)]],
|
||||
pageCount: [0, [Validators.required, Validators.min(0)]],
|
||||
language: [0, [Validators.required, Validators.min(0)]],
|
||||
amazonRating: [0, [Validators.required, Validators.min(0)]],
|
||||
amazonReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
goodreadsRating: [0, [Validators.required, Validators.min(0)]],
|
||||
goodreadsReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
hardcoverRating: [0, [Validators.required, Validators.min(0)]],
|
||||
hardcoverReviewCount: [0, [Validators.required, Validators.min(0)]],
|
||||
coverImage: [0, [Validators.required, Validators.min(0)]],
|
||||
});
|
||||
this.appSettings$
|
||||
.pipe(filter((settings): settings is AppSettings => !!settings), take(1))
|
||||
.subscribe(settings => {
|
||||
if (settings.metadataMatchWeights) {
|
||||
this.form.patchValue(settings.metadataMatchWeights);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get orderedKeys(): string[] {
|
||||
return Object.keys(this.labelMap);
|
||||
}
|
||||
|
||||
save(): void {
|
||||
if (this.form.invalid) return;
|
||||
|
||||
this.isSaving = true;
|
||||
|
||||
const payload = [
|
||||
{
|
||||
key: AppSettingKey.METADATA_MATCH_WEIGHTS,
|
||||
newValue: this.form.value
|
||||
}
|
||||
];
|
||||
|
||||
this.appSettingsService.saveSettings(payload).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Saved',
|
||||
detail: 'Weights saved successfully'
|
||||
});
|
||||
this.isSaving = false;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to save weights'
|
||||
});
|
||||
this.isSaving = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
recalculate(): void {
|
||||
this.isRecalculating = true;
|
||||
this.weightsService.recalculateAll().subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Recalculated',
|
||||
detail: 'All book match scores were recalculated successfully.'
|
||||
});
|
||||
this.isRecalculating = false;
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to recalculate match scores.'
|
||||
});
|
||||
this.isRecalculating = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+8
@@ -24,4 +24,12 @@
|
||||
</app-metadata-advanced-fetch-options>
|
||||
</div>
|
||||
|
||||
<div class="pb-4">
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
|
||||
<div class="p-4 pt-4">
|
||||
<app-metadata-match-weights-component></app-metadata-match-weights-component>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
+3
-1
@@ -10,6 +10,7 @@ import {MessageService} from 'primeng/api';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AppSettingKey, AppSettings} from '../../core/model/app-settings.model';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {MetadataMatchWeightsComponent} from '../global-preferences/metadata-match-weights-component/metadata-match-weights-component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-settings-component',
|
||||
@@ -19,7 +20,8 @@ import {filter, take} from 'rxjs/operators';
|
||||
MetadataProviderSettingsComponent,
|
||||
ReactiveFormsModule,
|
||||
Tooltip,
|
||||
FormsModule
|
||||
FormsModule,
|
||||
MetadataMatchWeightsComponent
|
||||
],
|
||||
templateUrl: './metadata-settings-component.html',
|
||||
styleUrl: './metadata-settings-component.scss'
|
||||
|
||||
@@ -75,6 +75,7 @@ export interface UserSettings {
|
||||
newPdfReaderSetting: NewPdfReaderSetting;
|
||||
sidebarLibrarySorting: SidebarLibrarySorting;
|
||||
sidebarShelfSorting: SidebarShelfSorting;
|
||||
filterSortingMode: 'alphabetical' | 'count';
|
||||
entityViewPreferences: EntityViewPreferences;
|
||||
}
|
||||
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<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>
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<div class="p-4">
|
||||
<div class="flex items-center gap-2 pb-6 pt-4">
|
||||
<p class="text-lg ">Sidebar Library and Shelf Sorting Perference</p>
|
||||
<p class="text-lg">Sidebar Library and Shelf Sorting Preference</p>
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Configure sorting options for your library and shelves shown in the sidebar."
|
||||
tooltipPosition="right"
|
||||
|
||||
-2
@@ -53,7 +53,6 @@ export class SidebarSortingPreferencesComponent implements OnInit, OnDestroy {
|
||||
this.selectedShelfSorting = settings.sidebarShelfSorting;
|
||||
}
|
||||
|
||||
|
||||
private updatePreference(path: string[], value: any): void {
|
||||
if (!this.currentUser) return;
|
||||
let target: any = this.currentUser.userSettings;
|
||||
@@ -80,5 +79,4 @@ export class SidebarSortingPreferencesComponent implements OnInit, OnDestroy {
|
||||
onShelfSortingChange() {
|
||||
this.updatePreference(['sidebarShelfSorting'], this.selectedShelfSorting);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+2
@@ -2,4 +2,6 @@
|
||||
<app-view-preferences></app-view-preferences>
|
||||
<p-divider></p-divider>
|
||||
<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>
|
||||
|
||||
+3
-1
@@ -5,6 +5,7 @@ import {TableModule} from 'primeng/table';
|
||||
import {ToastModule} from 'primeng/toast';
|
||||
import {ViewPreferencesComponent} from './view-preferences/view-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({
|
||||
selector: 'app-view-preferences-parent',
|
||||
@@ -15,7 +16,8 @@ import {SidebarSortingPreferencesComponent} from './sidebar-sorting-preferences/
|
||||
TableModule,
|
||||
ToastModule,
|
||||
ViewPreferencesComponent,
|
||||
SidebarSortingPreferencesComponent
|
||||
SidebarSortingPreferencesComponent,
|
||||
SidebarFilterSortingPrefsComponent
|
||||
],
|
||||
templateUrl: './view-preferences-parent.component.html',
|
||||
styleUrl: './view-preferences-parent.component.scss'
|
||||
|
||||
Reference in New Issue
Block a user