Merge pull request #788 from adityachandelgit/develop

Merge Develop into Master for release
This commit is contained in:
Aditya Chandel
2025-07-28 08:00:22 -06:00
committed by GitHub
55 changed files with 2422 additions and 256 deletions
+9
View File
@@ -9,6 +9,15 @@ BookLore is a self-hosted web app for organizing and managing your personal book
![BookLore Demo](assets/demo.gif)
## 💃 Live Demo
Try it for yourself with the [public live demo](https://demo-booklore.elfhosted.com), sponsored by [ElfHosted](https://elfhosted.com) :heart:, using the following details:
* User: `bookgeek`
* Pass: `elfhosted`
(*the demo resets every hour, on the hour, no copyrighted content uploads please*)
## ✨ Key Features
- 📚 **Powerful Book Organization**: Keep your library tidy with **Libraries** and **Shelves**. Whether you're sorting by genre, author, or mood, finding the right book is effortless.
@@ -67,7 +67,7 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
return new UsernamePasswordAuthenticationToken(username, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
}
} catch (Exception e) {
log.error("Token authentication failed", e);
log.debug("Token authentication failed", e);
}
return null;
}
@@ -0,0 +1,41 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.service.MagicShelfService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/magic-shelves")
public class MagicShelfController {
private final MagicShelfService magicShelfService;
public MagicShelfController(MagicShelfService magicShelfService) {
this.magicShelfService = magicShelfService;
}
@GetMapping
public ResponseEntity<List<MagicShelf>> getAllForUser() {
return ResponseEntity.ok(magicShelfService.getUserShelves());
}
@GetMapping("/{id}")
public ResponseEntity<MagicShelf> getShelf(@PathVariable Long id) {
return ResponseEntity.ok(magicShelfService.getShelf(id));
}
@PostMapping
public ResponseEntity<MagicShelf> createUpdateShelf(@Valid @RequestBody MagicShelf shelf) {
return ResponseEntity.ok(magicShelfService.createOrUpdateShelf(shelf));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteShelf(@PathVariable Long id) {
magicShelfService.deleteShelf(id);
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
@Data
public class MagicShelf {
private Long id;
@NotBlank(message = "Shelf name must not be blank")
@Size(max = 255, message = "Shelf name must not exceed 255 characters")
private String name;
@NotBlank(message = "Icon must not be blank")
@Size(max = 64, message = "Icon must not exceed 64 characters")
private String icon;
@NotNull(message = "Filter JSON must not be null")
@Size(min = 2, message = "Filter JSON must not be empty")
private String filterJson;
}
@@ -0,0 +1,45 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "magic_shelf", uniqueConstraints = {
@UniqueConstraint(columnNames = {"user_id", "name"})
})
public class MagicShelfEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id", nullable = false)
private Long userId;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String icon;
@Column(name = "filter_json", columnDefinition = "json", nullable = false)
private String filterJson;
@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt = LocalDateTime.now();
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt = LocalDateTime.now();
@PreUpdate
public void onUpdate() {
updatedAt = LocalDateTime.now();
}
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface MagicShelfRepository extends JpaRepository<MagicShelfEntity, Long> {
List<MagicShelfEntity> findAllByUserId(Long userId);
Optional<MagicShelfEntity> findByUserIdAndName(Long userId, String name);
boolean existsByUserIdAndName(Long userId, String name);
}
@@ -0,0 +1,79 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.model.dto.MagicShelf;
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
import com.adityachandel.booklore.repository.MagicShelfRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@AllArgsConstructor
@Service
public class MagicShelfService {
private final MagicShelfRepository repository;
private final AuthenticationService authenticationService;
public List<MagicShelf> getUserShelves() {
Long userId = authenticationService.getAuthenticatedUser().getId();
return repository.findAllByUserId(userId).stream()
.map(this::toDto)
.toList();
}
@Transactional
public MagicShelf createOrUpdateShelf(MagicShelf dto) {
Long userId = authenticationService.getAuthenticatedUser().getId();
if (dto.getId() != null) {
MagicShelfEntity existing = repository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
if (!existing.getUserId().equals(userId)) {
throw new SecurityException("You are not authorized to update this shelf");
}
existing.setName(dto.getName());
existing.setIcon(dto.getIcon());
existing.setFilterJson(dto.getFilterJson());
return toDto(repository.save(existing));
}
if (repository.existsByUserIdAndName(userId, dto.getName())) {
throw new IllegalArgumentException("A shelf with the same name already exists for this user.");
}
return toDto(repository.save(toEntity(dto, userId)));
}
@Transactional
public void deleteShelf(Long id) {
Long userId = authenticationService.getAuthenticatedUser().getId();
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
if (!shelf.getUserId().equals(userId)) {
throw new SecurityException("You are not authorized to delete this shelf");
}
repository.deleteById(id);
}
private MagicShelf toDto(MagicShelfEntity entity) {
MagicShelf dto = new MagicShelf();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setIcon(entity.getIcon());
dto.setFilterJson(entity.getFilterJson());
return dto;
}
private MagicShelfEntity toEntity(MagicShelf dto, Long userId) {
MagicShelfEntity entity = new MagicShelfEntity();
entity.setId(dto.getId());
entity.setName(dto.getName());
entity.setIcon(dto.getIcon());
entity.setFilterJson(dto.getFilterJson());
entity.setUserId(userId);
return entity;
}
public MagicShelf getShelf(Long id) {
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
return toDto(shelf);
}
}
@@ -45,9 +45,7 @@ public class BookDropService {
private final NotificationService notificationService;
private final MetadataRefreshService metadataRefreshService;
private final BookdropNotificationService bookdropNotificationService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookFileProcessorRegistry processorRegistry;
private final AppProperties appProperties;
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
@@ -169,11 +167,8 @@ public class BookDropService {
.fileName(fileName)
.build();
return switch (type) {
case PDF -> pdfProcessor.processFile(libraryFile, false);
case EPUB -> epubProcessor.processFile(libraryFile, false);
case CBX -> cbxProcessor.processFile(libraryFile, false);
};
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
public void discardAllFiles() {
@@ -17,7 +17,7 @@ import java.nio.file.Path;
import java.util.Optional;
@Slf4j
public abstract class AbstractFileProcessor implements FileProcessor {
public abstract class AbstractFileProcessor implements BookFileProcessor {
protected final BookRepository bookRepository;
protected final BookCreatorService bookCreatorService;
@@ -37,35 +37,31 @@ public abstract class AbstractFileProcessor implements FileProcessor {
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public Book processFile(LibraryFile libraryFile, boolean forceProcess) {
public Book processFile(LibraryFile libraryFile) {
Path filePath = libraryFile.getFullPath();
String fileName = filePath.getFileName().toString();
String hash = FileUtils.computeFileHash(filePath);
Optional<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, forceProcess, bookRepository, bookMapper);
Optional<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookMapper);
if (existing.isPresent()) {
return existing.get();
}
if (!forceProcess) {
Optional<BookEntity> byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
if (byName.isPresent()) {
return bookMapper.toBook(byName.get());
}
Optional<BookEntity> byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
if (byName.isPresent()) {
return bookMapper.toBook(byName.get());
}
return processNewFile(libraryFile);
BookEntity book = processNewFile(libraryFile);
book.setCurrentHash(hash);
Float score = metadataMatchService.calculateMatchScore(book);
book.setMetadataMatchScore(score);
bookCreatorService.saveConnections(book);
return bookMapper.toBook(book);
}
protected abstract Book processNewFile(LibraryFile libraryFile);
protected abstract BookEntity processNewFile(LibraryFile libraryFile);
protected Book finishAndReturnBook(BookEntity bookEntity) {
String hash = FileUtils.computeFileHash(bookEntity);
bookEntity.setCurrentHash(hash);
Float score = metadataMatchService.calculateMatchScore(bookEntity);
bookEntity.setMetadataMatchScore(score);
bookCreatorService.saveConnections(bookEntity);
return bookMapper.toBook(bookEntity);
}
}
@@ -3,8 +3,12 @@ package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import java.util.List;
public interface BookFileProcessor {
Book processNewFile(LibraryFile libraryFile);
List<BookFileType> getSupportedTypes();
Book processFile(LibraryFile libraryFile);
boolean generateCover(BookEntity bookEntity);
}
@@ -0,0 +1,44 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.model.enums.BookFileType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Component
@Slf4j
public class BookFileProcessorRegistry {
private final Map<BookFileType, BookFileProcessor> processorMap;
public BookFileProcessorRegistry(List<BookFileProcessor> processors) {
this.processorMap = new EnumMap<>(BookFileType.class);
initializeProcessorMap(processors);
}
private void initializeProcessorMap(List<BookFileProcessor> processors) {
for (BookFileProcessor processor : processors) {
List<BookFileType> supportedTypes = processor.getSupportedTypes();
for (BookFileType type : supportedTypes) {
processorMap.put(type, processor);
log.debug("Registered {} for type: {}", processor.getClass().getSimpleName(), type);
}
}
log.info("Initialized BookFileProcessorRegistry with {} processors for {} types",
processors.size(), processorMap.size());
}
public Optional<BookFileProcessor> getProcessor(BookFileType type) {
return Optional.ofNullable(processorMap.get(type));
}
public BookFileProcessor getProcessorOrThrow(BookFileType type) {
return getProcessor(type)
.orElseThrow(() -> new IllegalArgumentException(
"No processor found for file type: " + type));
}
}
@@ -1,7 +1,6 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
@@ -42,13 +41,13 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
}
@Override
public Book processNewFile(LibraryFile libraryFile) {
public BookEntity processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
if (generateCover(bookEntity)) {
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
}
setMetadata(bookEntity);
return finishAndReturnBook(bookEntity);
return bookEntity;
}
@Override
@@ -70,6 +69,11 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
return false;
}
@Override
public List<BookFileType> getSupportedTypes() {
return List.of(BookFileType.CBX);
}
private Optional<BufferedImage> extractImagesFromArchive(File file) {
String name = file.getName().toLowerCase();
if (name.endsWith(".cbz")) {
@@ -1,7 +1,6 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
@@ -16,14 +15,13 @@ import com.adityachandel.booklore.util.FileUtils;
import io.documentnode.epub4j.domain.Resource;
import io.documentnode.epub4j.epub.EpubReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.Instant;
import java.util.Objects;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -49,13 +47,13 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
}
@Override
public Book processNewFile(LibraryFile libraryFile) {
public BookEntity processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
setBookMetadata(bookEntity);
if (generateCover(bookEntity)) {
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
}
return finishAndReturnBook(bookEntity);
return bookEntity;
}
@Override
@@ -95,6 +93,11 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
}
}
@Override
public List<BookFileType> getSupportedTypes() {
return List.of(BookFileType.EPUB);
}
private void setBookMetadata(BookEntity bookEntity) {
File bookFile = new File(bookEntity.getFullFilePath().toUri());
BookMetadata epubMetadata = epubMetadataExtractor.extractMetadata(bookFile);
@@ -7,7 +7,6 @@ import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.mapper.BookMapper;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
@@ -95,13 +94,13 @@ public class FileProcessingUtils {
}
@Transactional
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, boolean forceProcess, BookRepository bookRepository, BookMapper bookMapper) {
public Optional<Book> checkForDuplicateAndUpdateMetadataIfNeeded(LibraryFile libraryFile, String hash, BookRepository bookRepository, BookMapper bookMapper) {
if (StringUtils.isBlank(hash)) {
log.warn("Skipping file due to missing hash: {}", libraryFile.getFullPath());
return Optional.empty();
}
Optional<BookEntity> existingByHash = bookRepository.findByCurrentHash(hash);
if (existingByHash.isPresent() && !forceProcess) {
if (existingByHash.isPresent()) {
BookEntity book = existingByHash.get();
String fileName = libraryFile.getFullPath().getFileName().toString();
if (!book.getFileName().equals(fileName)) {
@@ -113,6 +112,7 @@ public class FileProcessingUtils {
}
return Optional.of(bookMapper.toBook(book));
}
return Optional.empty();
}
@@ -1,8 +0,0 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
public interface FileProcessor {
Book processFile(LibraryFile libraryFile, boolean forceProcess);
}
@@ -1,7 +1,6 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
@@ -24,6 +23,7 @@ import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import static com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils.truncate;
@@ -47,13 +47,13 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
}
@Override
public Book processNewFile(LibraryFile libraryFile) {
public BookEntity processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
if (generateCover(bookEntity)) {
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
}
extractAndSetMetadata(bookEntity);
return finishAndReturnBook(bookEntity);
return bookEntity;
}
@Override
@@ -69,6 +69,11 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
}
}
@Override
public List<BookFileType> getSupportedTypes() {
return List.of(BookFileType.PDF);
}
private void extractAndSetMetadata(BookEntity bookEntity) {
try {
BookMetadata extracted = pdfMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
@@ -0,0 +1,55 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@AllArgsConstructor
@Component
@Slf4j
public class FileAsBookProcessor implements LibraryFileProcessor {
private final NotificationService notificationService;
private final BookFileProcessorRegistry processorRegistry;
@Override
@Transactional
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
for (LibraryFile libraryFile : libraryFiles) {
log.info("Processing file: {}", libraryFile.getFileName());
Book book = processLibraryFile(libraryFile);
if (book != null) {
notificationService.sendMessage(Topic.BOOK_ADD, book);
notificationService.sendMessage(Topic.LOG, createLogNotification("Book added: " + book.getFileName()));
log.info("Processed file: {}", libraryFile.getFileName());
}
}
}
@Transactional
protected Book processLibraryFile(LibraryFile libraryFile) {
BookFileType type = libraryFile.getBookFileType();
if (type == null) {
log.warn("Unsupported file type for file: {}", libraryFile.getFileName());
return null;
}
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
}
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import java.util.List;
public interface LibraryFileProcessor {
void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity);
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
// Removed unused imports
@AllArgsConstructor
@Component
public class LibraryFileProcessorRegistry {
private final FileAsBookProcessor fileAsBookProcessor;
public LibraryFileProcessor getProcessor(LibraryEntity library) {
return fileAsBookProcessor;
}
}
@@ -1,7 +1,6 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
@@ -11,9 +10,6 @@ import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -38,18 +34,17 @@ public class LibraryProcessingService {
private final LibraryRepository libraryRepository;
private final NotificationService notificationService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookRepository bookRepository;
private final FileService fileService;
private final LibraryFileProcessorRegistry fileProcessorRegistry;
@Transactional
public void processLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing library: " + libraryEntity.getName()));
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
processLibraryFiles(libraryFiles);
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(libraryFiles, libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + libraryEntity.getName()));
}
@@ -57,29 +52,36 @@ public class LibraryProcessingService {
public void rescanLibrary(long libraryId) throws IOException {
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
processLibraryFiles(detectNewBookPaths(libraryEntity));
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
deleteRemovedBooks(detectDeletedBookIds(libraryFiles, libraryEntity));
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
}
public List<Long> detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException {
Set<String> currentFileNames = getLibraryFiles(libraryEntity).stream()
.map(LibraryFile::getFileName)
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
processor.processLibraryFiles(libraryFiles, libraryEntity);
}
public static List<Long> detectDeletedBookIds(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Set<Path> currentFullPaths = libraryFiles.stream()
.map(LibraryFile::getFullPath)
.collect(Collectors.toSet());
return libraryEntity.getBookEntities().stream()
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
.filter(book -> !currentFileNames.contains(book.getFileName()))
.filter(book -> !currentFullPaths.contains(book.getFullFilePath()))
.map(BookEntity::getId)
.collect(Collectors.toList());
}
public List<LibraryFile> detectNewBookPaths(LibraryEntity libraryEntity) throws IOException {
Set<String> existingFileNames = libraryEntity.getBookEntities().stream()
.map(BookEntity::getFileName)
public static List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
Set<Path> existingFullPaths = libraryEntity.getBookEntities().stream()
.map(BookEntity::getFullFilePath)
.collect(Collectors.toSet());
return getLibraryFiles(libraryEntity).stream()
.filter(file -> !existingFileNames.contains(file.getFileName()))
return libraryFiles.stream()
.filter(file -> !existingFullPaths.contains(file.getFullPath()))
.collect(Collectors.toList());
}
@@ -118,27 +120,6 @@ public class LibraryProcessingService {
}
}
@Transactional
public void processLibraryFiles(List<LibraryFile> libraryFiles) {
for (LibraryFile libraryFile : libraryFiles) {
log.info("Processing file: {}", libraryFile.getFileName());
Book book = processLibraryFile(libraryFile);
if (book != null) {
notificationService.sendMessage(Topic.BOOK_ADD, book);
notificationService.sendMessage(Topic.LOG, createLogNotification("Book added: " + book.getFileName()));
log.info("Processed file: {}", libraryFile.getFileName());
}
}
}
@Transactional
protected Book processLibraryFile(LibraryFile libraryFile) {
return switch (libraryFile.getBookFileType()) {
case PDF -> pdfProcessor.processFile(libraryFile, false);
case EPUB -> epubProcessor.processFile(libraryFile, false);
case CBX -> cbxProcessor.processFile(libraryFile, false);
};
}
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> allFiles = new ArrayList<>();
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.Lock;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.model.websocket.Topic;
@@ -21,9 +22,8 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestore;
import com.adityachandel.booklore.service.metadata.backuprestore.MetadataBackupRestoreFactory;
import com.adityachandel.booklore.service.metadata.parser.BookParser;
@@ -61,9 +61,7 @@ public class BookMetadataService {
private final AppSettingService appSettingService;
private final BookMetadataRepository bookMetadataRepository;
private final FileService fileService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookFileProcessorRegistry processorRegistry;
private final BookQueryService bookQueryService;
private final Map<MetadataProvider, BookParser> parserMap;
private final MetadataBackupRestoreFactory metadataBackupRestoreFactory;
@@ -196,12 +194,10 @@ public class BookMetadataService {
String title = book.getMetadata().getTitle();
String message = progress + "Regenerating cover for: " + title;
notificationService.sendMessage(Topic.LOG, createLogNotification(message));
switch (book.getBookType()) {
case PDF -> pdfProcessor.generateCover(book);
case EPUB -> epubProcessor.generateCover(book);
case CBX -> cbxProcessor.generateCover(book);
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType());
}
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
processor.generateCover(book);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
}
@@ -63,7 +63,7 @@ public class MetadataMatchService {
if (isPositive(metadata.getHardcoverReviewCount())) score += weights.getHardcoverReviewCount();
if (isPresent(metadata.getThumbnail())) score += weights.getCoverImage();
return score / totalWeight;
return (score / totalWeight) * 100f;
}
private boolean isPresent(String value) {
@@ -51,7 +51,7 @@ public class AppMigrationService {
@Transactional
public void populateMetadataScoresOnce() {
if (migrationRepository.existsById("populateMetadataScores")) return;
if (migrationRepository.existsById("populateMetadataScores_v2")) return;
List<BookEntity> books = bookQueryService.getAllFullBookEntities();
for (BookEntity book : books) {
@@ -60,8 +60,8 @@ public class AppMigrationService {
}
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"));
log.info("Migration 'populateMetadataScores_v2' applied to {} books.", books.size());
migrationRepository.save(new AppMigrationEntity("populateMetadataScores_v2", LocalDateTime.now(), "Calculate and store metadata match score for all books"));
}
@Transactional
@@ -12,9 +12,8 @@ import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
@@ -46,9 +45,7 @@ import java.util.Objects;
public class FileUploadService {
private final LibraryRepository libraryRepository;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookFileProcessorRegistry processorRegistry;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final PdfMetadataExtractor pdfMetadataExtractor;
@@ -84,7 +81,7 @@ public class FileUploadService {
try {
file.transferTo(tempPath);
setTemporaryFileOwnership(tempPath);
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
@@ -167,22 +164,19 @@ public class FileUploadService {
}
}
private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType fileType) {
private Book processFile(String fileName, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile, BookFileType type) {
String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath());
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(subPath)
.bookFileType(fileType)
.bookFileType(type)
.fileName(fileName)
.build();
return switch (fileType) {
case PDF -> pdfProcessor.processFile(libraryFile, false);
case EPUB -> epubProcessor.processFile(libraryFile, false);
case CBX -> cbxProcessor.processFile(libraryFile, false);
};
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
return processor.processFile(libraryFile);
}
}
@@ -62,7 +62,7 @@ public class BookFileTransactionalHandler {
.orElseThrow(() -> new IllegalArgumentException("Unsupported book file type: " + fileName)))
.build();
libraryProcessingService.processLibraryFiles(List.of(libraryFile));
libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
log.info("[CREATE] Completed processing for file '{}'", filePath);
@@ -0,0 +1,11 @@
CREATE TABLE magic_shelf
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
name VARCHAR(255) NOT NULL,
icon VARCHAR(64) NOT NULL,
filter_json JSON NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_user_name (user_id, name)
);
@@ -6,12 +6,11 @@ import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.bookdrop.BookdropNotificationService;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
import com.adityachandel.booklore.service.bookdrop.BookdropMonitoringService;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import com.adityachandel.booklore.service.NotificationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.PathResource;
@@ -35,9 +34,6 @@ class BookDropServiceTest {
private NotificationService notificationService;
private MetadataRefreshService metadataRefreshService;
private BookdropNotificationService bookdropNotificationService;
private PdfProcessor pdfProcessor;
private EpubProcessor epubProcessor;
private CbxProcessor cbxProcessor;
private AppProperties appProperties;
private BookDropService bookDropService;
@@ -52,9 +48,7 @@ class BookDropServiceTest {
notificationService = mock(NotificationService.class);
metadataRefreshService = mock(MetadataRefreshService.class);
bookdropNotificationService = mock(BookdropNotificationService.class);
pdfProcessor = mock(PdfProcessor.class);
epubProcessor = mock(EpubProcessor.class);
cbxProcessor = mock(CbxProcessor.class);
BookFileProcessorRegistry processorRegistry = mock(BookFileProcessorRegistry.class);
appProperties = mock(AppProperties.class);
bookDropService = new BookDropService(
@@ -62,7 +56,7 @@ class BookDropServiceTest {
monitoringService, bookdropMonitoringService,
notificationService, metadataRefreshService,
bookdropNotificationService,
pdfProcessor, epubProcessor, cbxProcessor,
processorRegistry,
appProperties
);
}
@@ -110,7 +104,7 @@ class BookDropServiceTest {
Resource resource = bookDropService.getBookdropCover(bookdropId);
assertThat(resource).isInstanceOf(PathResource.class);
assertThat(((PathResource) resource).getFile().getName()).isEqualTo(bookdropId + ".jpg");
assertThat(resource.getFilename()).isEqualTo(bookdropId + ".jpg");
coverFile.delete();
}
@@ -0,0 +1,362 @@
package com.adityachandel.booklore.service.library;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class FileAsBookProcessorTest {
@Mock
private NotificationService notificationService;
@Mock
private BookFileProcessorRegistry processorRegistry;
@Mock
private BookFileProcessor bookFileProcessor;
@InjectMocks
private FileAsBookProcessor fileAsBookProcessor;
@Captor
private ArgumentCaptor<Book> bookCaptor;
private AutoCloseable mocks;
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
}
@AfterEach
void tearDown() throws Exception {
if (mocks != null) {
mocks.close();
}
}
@Test
void processLibraryFiles_shouldProcessAllValidFiles() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
List<LibraryFile> libraryFiles = new ArrayList<>();
LibraryFile file1 = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book1.epub")
.fileSubPath("books")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile file2 = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book2.pdf")
.fileSubPath("books")
.bookFileType(BookFileType.PDF)
.build();
libraryFiles.add(file1);
libraryFiles.add(file2);
Book book1 = Book.builder()
.fileName("book1.epub")
.title("Book 1")
.bookType(BookFileType.EPUB)
.build();
Book book2 = Book.builder()
.fileName("book2.pdf")
.title("Book 2")
.bookType(BookFileType.PDF)
.build();
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(file1)).thenReturn(book1);
when(bookFileProcessor.processFile(file2)).thenReturn(book2);
// When
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
// Then
verify(notificationService, times(2)).sendMessage(eq(Topic.BOOK_ADD), bookCaptor.capture());
verify(notificationService, times(2)).sendMessage(eq(Topic.LOG), any(LogNotification.class));
List<Book> capturedBooks = bookCaptor.getAllValues();
assertThat(capturedBooks).hasSize(2);
assertThat(capturedBooks).containsExactly(book1, book2);
}
@Test
void processLibraryFiles_shouldSkipFilesWithUnsupportedExtensions() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
List<LibraryFile> libraryFiles = new ArrayList<>();
LibraryFile validFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.epub")
.fileSubPath("books")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile invalidFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("document.txt")
.fileSubPath("docs")
.bookFileType(null)
.build();
libraryFiles.add(validFile);
libraryFiles.add(invalidFile);
Book book = Book.builder()
.fileName("book.epub")
.title("Valid Book")
.bookType(BookFileType.EPUB)
.build();
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(validFile)).thenReturn(book);
// When
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
// Then
verify(notificationService, times(1)).sendMessage(eq(Topic.BOOK_ADD), eq(book));
verify(notificationService, times(1)).sendMessage(eq(Topic.LOG), any(LogNotification.class));
verify(processorRegistry, times(1)).getProcessorOrThrow(any());
}
@Test
void processLibraryFiles_shouldHandleEmptyList() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
List<LibraryFile> libraryFiles = new ArrayList<>();
// When
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
// Then
verify(notificationService, never()).sendMessage(any(Topic.class), any());
verify(processorRegistry, never()).getProcessorOrThrow(any());
}
@Test
void processLibraryFile_shouldReturnNullForUnsupportedFileType() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("document.txt")
.fileSubPath("docs")
.bookFileType(null)
.build();
// When
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
// Then
assertThat(result).isNull();
verify(processorRegistry, never()).getProcessorOrThrow(any());
}
@Test
void processLibraryFile_shouldProcessSupportedFileTypes() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.epub")
.fileSubPath("books")
.bookFileType(BookFileType.EPUB)
.build();
Book expectedBook = Book.builder()
.fileName("book.epub")
.title("Test Book")
.bookType(BookFileType.EPUB)
.build();
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(libraryFile)).thenReturn(expectedBook);
// When
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
// Then
assertThat(result).isEqualTo(expectedBook);
verify(processorRegistry).getProcessorOrThrow(BookFileType.EPUB);
verify(bookFileProcessor).processFile(libraryFile);
}
@Test
void processLibraryFile_shouldHandleNullReturnFromProcessor() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.pdf")
.fileSubPath("books")
.bookFileType(BookFileType.PDF)
.build();
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(libraryFile)).thenReturn(null);
// When
Book result = fileAsBookProcessor.processLibraryFile(libraryFile);
// Then
assertThat(result).isNull();
}
@Test
void processLibraryFiles_shouldNotSendNotificationWhenProcessorReturnsNull() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
List<LibraryFile> libraryFiles = new ArrayList<>();
LibraryFile file = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.epub")
.fileSubPath("books")
.bookFileType(BookFileType.EPUB)
.build();
libraryFiles.add(file);
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(file)).thenReturn(null);
// When
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
// Then
verify(notificationService, never()).sendMessage(any(Topic.class), any());
}
@Test
void processLibraryFiles_shouldProcessAllSupportedFileExtensions() {
// Given
LibraryEntity libraryEntity = new LibraryEntity();
LibraryPathEntity libraryPathEntity = new LibraryPathEntity();
libraryPathEntity.setPath("/library/path");
List<LibraryFile> libraryFiles = new ArrayList<>();
LibraryFile epubFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.epub")
.fileSubPath("books")
.bookFileType(BookFileType.EPUB)
.build();
LibraryFile pdfFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("book.pdf")
.fileSubPath("books")
.bookFileType(BookFileType.PDF)
.build();
LibraryFile cbzFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("comic.cbz")
.fileSubPath("comics")
.bookFileType(BookFileType.CBX)
.build();
LibraryFile cbrFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileName("comic.cbr")
.fileSubPath("comics")
.bookFileType(BookFileType.CBX)
.build();
libraryFiles.add(epubFile);
libraryFiles.add(pdfFile);
libraryFiles.add(cbzFile);
libraryFiles.add(cbrFile);
Book epubBook = Book.builder()
.fileName("book.epub")
.bookType(BookFileType.EPUB)
.build();
Book pdfBook = Book.builder()
.fileName("book.pdf")
.bookType(BookFileType.PDF)
.build();
Book cbzBook = Book.builder()
.fileName("comic.cbz")
.bookType(BookFileType.CBX)
.build();
Book cbrBook = Book.builder()
.fileName("comic.cbr")
.bookType(BookFileType.CBX)
.build();
when(processorRegistry.getProcessorOrThrow(BookFileType.EPUB)).thenReturn(bookFileProcessor);
when(processorRegistry.getProcessorOrThrow(BookFileType.PDF)).thenReturn(bookFileProcessor);
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(bookFileProcessor);
when(bookFileProcessor.processFile(epubFile)).thenReturn(epubBook);
when(bookFileProcessor.processFile(pdfFile)).thenReturn(pdfBook);
when(bookFileProcessor.processFile(cbzFile)).thenReturn(cbzBook);
when(bookFileProcessor.processFile(cbrFile)).thenReturn(cbrBook);
// When
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
// Then
verify(notificationService, times(4)).sendMessage(eq(Topic.BOOK_ADD), any(Book.class));
verify(notificationService, times(4)).sendMessage(eq(Topic.LOG), any(LogNotification.class));
}
}
+3 -1
View File
@@ -1,6 +1,5 @@
import {Routes} from '@angular/router';
import {BookBrowserComponent} from './book/components/book-browser/book-browser.component';
import {MainDashboardComponent} from './dashboard/components/main-dashboard/main-dashboard.component';
import {AppLayoutComponent} from './layout/component/layout-main/app.layout.component';
import {LoginComponent} from './core/component/login/login.component';
import {AuthGuard} from './auth.guard';
@@ -17,6 +16,8 @@ import {LoginGuard} from './core/setup/ login.guard';
import {OidcCallbackComponent} from './core/security/oidc-callback/oidc-callback.component';
import {CbxReaderComponent} from './book/components/cbx-reader/cbx-reader.component';
import {BookdropFileReviewComponent} from './bookdrop/bookdrop-file-review-component/bookdrop-file-review.component';
import {MagicShelfComponent} from './magic-shelf-component/magic-shelf-component';
import {MainDashboardComponent} from './dashboard/components/main-dashboard/main-dashboard.component';
export const routes: Routes = [
{
@@ -41,6 +42,7 @@ export const routes: Routes = [
{path: 'library/:libraryId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'shelf/:shelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'unshelved-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{ path: 'magic-shelf/:magicShelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard] },
{path: 'book/:bookId', component: BookMetadataCenterComponent, canActivate: [AuthGuard]},
{path: 'bookdrop', component: BookdropFileReviewComponent, canActivate: [AuthGuard]}
]
@@ -0,0 +1,229 @@
import {Injectable} from '@angular/core';
import {Book} from './book/model/book.model';
import {GroupRule, Rule, RuleField, RuleOperator} from './magic-shelf-component/magic-shelf-component';
@Injectable({providedIn: 'root'})
export class BookRuleEvaluatorService {
evaluateGroup(book: Book, group: GroupRule): boolean {
const results = group.rules.map(rule => {
if ('type' in rule && rule.type === 'group') {
return this.evaluateGroup(book, rule as GroupRule);
} else {
return this.evaluateRule(book, rule as Rule);
}
});
return group.join === 'and' ? results.every(Boolean) : results.some(Boolean);
}
private evaluateRule(book: Book, rule: Rule): boolean {
const rawValue = this.extractBookValue(book, rule.field);
const normalize = (val: any): any => {
if (val === null || val === undefined) return val;
if (val instanceof Date) return val;
const date = new Date(val);
if (!isNaN(date.getTime())) return date;
if (typeof val === 'string') return val.toLowerCase();
return val;
};
const value = normalize(rawValue);
const ruleVal = normalize(rule.value);
const ruleStart = normalize(rule.valueStart);
const ruleEnd = normalize(rule.valueEnd);
const getArrayField = (field: RuleField): string[] => {
switch (field) {
case 'authors':
return (book.metadata?.authors ?? []).map(a => a.toLowerCase());
case 'categories':
return (book.metadata?.categories ?? []).map(c => c.toLowerCase());
case 'readStatus':
return [String(book.readStatus).toLowerCase()];
case 'fileType':
return [String(this.getFileExtension(book.fileName) ?? '').toLowerCase()];
case 'library':
return [String(book.libraryId)];
case 'language':
return [String(book.metadata?.language ?? '').toLowerCase()];
case 'title':
return [String(book.metadata?.title ?? '').toLowerCase()];
case 'subtitle':
return [String(book.metadata?.subtitle ?? '').toLowerCase()];
case 'publisher':
return [String(book.metadata?.publisher ?? '').toLowerCase()];
case 'seriesName':
return [String(book.metadata?.seriesName ?? '').toLowerCase()];
default:
return [];
}
};
const ruleList = Array.isArray(rule.value)
? rule.value.map(v => String(v).toLowerCase())
: (rule.value ? [String(rule.value).toLowerCase()] : []);
switch (rule.operator) {
case 'equals':
if (Array.isArray(value)) {
return value.some(v => ruleList.includes(v));
}
if (value instanceof Date && ruleVal instanceof Date) {
return value.getTime() === ruleVal.getTime();
}
return value === ruleVal;
case 'not_equals':
if (Array.isArray(value)) {
return value.every(v => !ruleList.includes(v));
}
if (value instanceof Date && ruleVal instanceof Date) {
return value.getTime() !== ruleVal.getTime();
}
return value !== ruleVal;
case 'contains':
if (typeof value !== 'string') return false;
if (typeof ruleVal !== 'string') return false;
return value.includes(ruleVal);
case 'does_not_contain':
if (typeof value !== 'string') return true;
if (typeof ruleVal !== 'string') return true;
return !value.includes(ruleVal);
case 'starts_with':
if (typeof value !== 'string') return false;
if (typeof ruleVal !== 'string') return false;
return value.startsWith(ruleVal);
case 'ends_with':
if (typeof value !== 'string') return false;
if (typeof ruleVal !== 'string') return false;
return value.endsWith(ruleVal);
case 'greater_than':
if (value instanceof Date && ruleVal instanceof Date) {
return value > ruleVal;
}
return Number(value) > Number(ruleVal);
case 'greater_than_equal_to':
if (value instanceof Date && ruleVal instanceof Date) {
return value >= ruleVal;
}
return Number(value) >= Number(ruleVal);
case 'less_than':
if (value instanceof Date && ruleVal instanceof Date) {
return value < ruleVal;
}
return Number(value) < Number(ruleVal);
case 'less_than_equal_to':
if (value instanceof Date && ruleVal instanceof Date) {
return value <= ruleVal;
}
return Number(value) <= Number(ruleVal);
case 'in_between':
if (value == null || ruleStart == null || ruleEnd == null) return false;
if (value instanceof Date && ruleStart instanceof Date && ruleEnd instanceof Date) {
return value >= ruleStart && value <= ruleEnd;
}
return Number(value) >= Number(ruleStart) && Number(value) <= Number(ruleEnd);
case 'is_empty':
if (value == null) return true;
if (typeof value === 'string') return value.trim() === '';
if (Array.isArray(value)) return value.length === 0;
return false;
case 'is_not_empty':
if (value == null) return false;
if (typeof value === 'string') return value.trim() !== '';
if (Array.isArray(value)) return value.length > 0;
return true;
case 'includes_all': {
const bookList = getArrayField(rule.field);
return ruleList.every(v => bookList.includes(v));
}
case 'excludes_all': {
const bookList = getArrayField(rule.field);
return ruleList.every(v => !bookList.includes(v));
}
case 'includes_any': {
const bookList = getArrayField(rule.field);
return ruleList.some(v => bookList.includes(v));
}
default:
return false;
}
}
private extractBookValue(book: Book, field: RuleField): any {
switch (field) {
case 'library':
return book.libraryId;
case 'readStatus':
return book.readStatus;
case 'fileType':
return this.getFileExtension(book.fileName)?.toLowerCase() ?? null;
case 'fileSize':
return book.fileSizeKb;
case 'metadataScore':
return book.metadataMatchScore;
case 'personalRating':
return book.metadata?.personalRating;
case 'title':
return book.metadata?.title?.toLowerCase() ?? null;
case 'subtitle':
return book.metadata?.subtitle?.toLowerCase() ?? null;
case 'authors':
return (book.metadata?.authors ?? []).map(a => a.toLowerCase());
case 'categories':
return (book.metadata?.categories ?? []).map(c => c.toLowerCase());
case 'publisher':
return book.metadata?.publisher?.toLowerCase() ?? null;
case 'publishedDate':
return book.metadata?.publishedDate ? new Date(book.metadata.publishedDate) : null;
case 'seriesName':
return book.metadata?.seriesName?.toLowerCase() ?? null;
case 'seriesNumber':
return book.metadata?.seriesNumber;
case 'seriesTotal':
return book.metadata?.seriesTotal;
case 'pageCount':
return book.metadata?.pageCount;
case 'language':
return book.metadata?.language?.toLowerCase() ?? null;
case 'amazonRating':
return book.metadata?.amazonRating;
case 'amazonReviewCount':
return book.metadata?.amazonReviewCount;
case 'goodreadsRating':
return book.metadata?.goodreadsRating;
case 'goodreadsReviewCount':
return book.metadata?.goodreadsReviewCount;
case 'hardcoverRating':
return book.metadata?.hardcoverRating;
case 'hardcoverReviewCount':
return book.metadata?.hardcoverReviewCount;
default:
return (book as any)[field];
}
}
private getFileExtension(filePath?: string): string | null {
if (!filePath) return null;
const parts = filePath.split('.');
if (parts.length < 2) return null;
return parts.pop() ?? null;
}
}
@@ -3,7 +3,7 @@ import {ActivatedRoute, Router} from '@angular/router';
import {ConfirmationService, MenuItem, MessageService, PrimeTemplate} from 'primeng/api';
import {LibraryService} from '../../service/library.service';
import {BookService} from '../../service/book.service';
import {debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {catchError, debounceTime, filter, map, switchMap, take} from 'rxjs/operators';
import {BehaviorSubject, combineLatest, Observable, of, Subject} from 'rxjs';
import {ShelfService} from '../../service/shelf.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -45,10 +45,14 @@ import {MultiSelect} from 'primeng/multiselect';
import {TableColumnPreferenceService} from './table-column-preference-service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BookMenuService} from '../../service/book-menu.service';
import {MagicShelf, MagicShelfService} from '../../../magic-shelf-service';
import {BookRuleEvaluatorService} from '../../../book-rule-evaluator.service';
import {GroupRule} from '../../../magic-shelf-component/magic-shelf-component';
export enum EntityType {
LIBRARY = 'Library',
SHELF = 'Shelf',
MAGIC_SHELF = 'Magic Shelf',
ALL_BOOKS = 'All Books',
UNSHELVED = 'Unshelved Books',
}
@@ -98,11 +102,11 @@ const SORT_DIRECTION = {
})
export class BookBrowserComponent implements OnInit, AfterViewInit {
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | null> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
entityType$: Observable<EntityType> | undefined;
searchTerm$ = new BehaviorSubject<string>('');
entity: Library | Shelf | null = null;
entity: Library | Shelf | MagicShelf | null = null;
entityType: EntityType | undefined;
bookTitle: string = '';
entityOptions: MenuItem[] | undefined;
@@ -143,6 +147,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
private libraryShelfMenuService = inject(LibraryShelfMenuService);
protected seriesCollapseFilter = inject(SeriesCollapseFilter);
protected confirmationService = inject(ConfirmationService);
protected magicShelfService = inject(MagicShelfService);
protected bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
private sideBarFilter = new SideBarFilter(this.selectedFilter, this.selectedFilterMode);
private headerFilter = new HeaderFilter(this.searchTerm$);
@@ -203,7 +209,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
this.entityOptions = entity
? this.isLibrary(entity)
? this.libraryShelfMenuService.initializeLibraryMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: this.isMagicShelf(entity)
? this.libraryShelfMenuService.initializeMagicShelfMenuItems(entity)
: this.libraryShelfMenuService.initializeShelfMenuItems(entity)
: [];
});
}
@@ -238,6 +246,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
const sortParam = paramMap.get(QUERY_PARAMS.SORT);
const directionParam = paramMap.get(QUERY_PARAMS.DIRECTION);
const filterParams = paramMap.get(QUERY_PARAMS.FILTER);
const sidebarParam = paramMap.get(QUERY_PARAMS.SIDEBAR);
const parsedFilters: Record<string, string[]> = {};
@@ -320,7 +329,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
: VIEW_MODES.GRID)
: (effectivePrefs.view?.toLowerCase() ?? VIEW_MODES.GRID);
//this.showFilter = sidebarParam === 'true' || (sidebarParam === null && this.filterVisibility);
//this.showFilter = sidebarParam === 'true' || (sidebarParam === null && filterParams !== filterParams);
this.bookSorter.updateSortOptions();
@@ -369,10 +378,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
});
}
private isLibrary(entity: Library | Shelf): entity is Library {
private isLibrary(entity: Library | Shelf | MagicShelf): entity is Library {
return (entity as Library).paths !== undefined;
}
private isMagicShelf(entity: any): entity is MagicShelf {
return entity && 'filterJson' in entity;
}
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.GRID ? 'pi pi-objects-column' : 'pi pi-table';
}
@@ -382,6 +395,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
map(params => {
const libraryId = Number(params.get('libraryId') || NaN);
const shelfId = Number(params.get('shelfId') || NaN);
const magicShelfId = Number(params.get('magicShelfId') || NaN);
if (!isNaN(libraryId)) {
this.entityType = EntityType.LIBRARY;
@@ -389,6 +403,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
} else if (!isNaN(shelfId)) {
this.entityType = EntityType.SHELF;
return {entityId: shelfId, entityType: EntityType.SHELF};
} else if (!isNaN(magicShelfId)) {
this.entityType = EntityType.MAGIC_SHELF;
return {entityId: magicShelfId, entityType: EntityType.MAGIC_SHELF};
} else {
this.entityType = EntityType.ALL_BOOKS;
return {entityId: NaN, entityType: EntityType.ALL_BOOKS};
@@ -397,12 +414,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
);
}
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | null> {
private fetchEntity(entityId: number, entityType: EntityType): Observable<Library | Shelf | MagicShelf | null> {
switch (entityType) {
case EntityType.LIBRARY:
return this.fetchLibrary(entityId);
case EntityType.SHELF:
return this.fetchShelf(entityId);
case EntityType.MAGIC_SHELF:
return this.fetchMagicShelf(entityId);
default:
return of(null);
}
@@ -416,6 +435,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
return this.fetchBooks(book =>
book.shelves?.some(shelf => shelf.id === entityId) ?? false
);
case EntityType.MAGIC_SHELF:
return this.fetchBooksMagicShelfBooks(entityId);
case EntityType.ALL_BOOKS:
default:
return this.fetchAllBooks();
@@ -440,6 +461,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
);
}
private fetchBooksMagicShelfBooks(magicShelfId: number): Observable<BookState> {
return combineLatest([
this.bookService.bookState$,
this.magicShelfService.getShelf(magicShelfId)
]).pipe(
map(([bookState, magicShelf]) => {
if (!bookState.loaded || bookState.error || !magicShelf?.filterJson) {
return bookState;
}
const filteredBooks: Book[] | undefined = bookState.books?.filter(book =>
this.bookRuleEvaluatorService.evaluateGroup(book, JSON.parse(magicShelf.filterJson!) as GroupRule)
);
const sortedBooks = this.sortService.applySort(filteredBooks ?? [], this.bookSorter.selectedSort!);
return {...bookState, books: sortedBooks};
}),
switchMap(bookState => this.applyBookFilters(bookState))
);
}
private fetchBooks(bookFilter: (book: Book) => boolean): Observable<BookState> {
return this.bookService.bookState$.pipe(
map(bookState => {
@@ -491,6 +531,22 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
);
}
private fetchMagicShelf(magicShelfId: number): Observable<MagicShelf | null> {
return this.magicShelfService.shelvesState$.pipe(
take(1),
switchMap((state) => {
const cached = state.shelves?.find(s => s.id === magicShelfId) ?? null;
if (cached) {
return of(cached);
}
return this.magicShelfService.getShelf(magicShelfId).pipe(
map(shelf => shelf ?? null),
catchError(() => of(null))
);
})
);
}
onCheckboxClicked(event: { index: number; bookId: number; selected: boolean; shiftKey: boolean }) {
const {index, bookId, selected, shiftKey} = event;
if (!shiftKey || this.lastSelectedIndex === null) {
@@ -12,7 +12,6 @@
styleClass="h-8"></p-selectButton>
</div>
<!-- Outer scroll -->
<div class="flex-1 overflow-y-auto pb-4 pr-1" style="overscroll-behavior: contain;">
<p-accordion [value]="expandedPanels">
@for (filterType of filterTypes; track filterType; let i = $index) {
@@ -30,7 +29,6 @@
<p-accordion-content>
@if (filterStreams[filterType] | async; as filters) {
<!-- Inner scrollable content with nested scroll behavior -->
<div
class="max-h-[27.5rem] overflow-y-auto overscroll-contain pr-1"
style="overscroll-behavior: contain;">
@@ -38,8 +36,7 @@
<div
class="cursor-pointer transition-colors duration-200 ease-in-out pb-1 flex items-center gap-2"
[ngClass]="{
'text-[var(--primary-color)]':
activeFilters[filterType]?.includes(filter.value?.id || filter.value)
'text-[var(--primary-color)]': activeFilters[filterType]?.includes(filter.value?.id || filter.value)
}"
(click)="handleFilterClick(filterType, filter.value?.id || filter.value)">
<p-badge [value]="filter.bookCount"></p-badge>
@@ -13,6 +13,9 @@ import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
import {UserService} from '../../../../settings/user-management/user.service';
import {FilterSortPreferenceService} from '../filters/filter-sorting-preferences.service';
import {MagicShelf} from '../../../../magic-shelf-service';
import {GroupRule} from '../../../../magic-shelf-component/magic-shelf-component';
import {BookRuleEvaluatorService} from '../../../../book-rule-evaluator.service';
type Filter<T> = { value: T; bookCount: number };
@@ -148,7 +151,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
@Output() filterSelected = new EventEmitter<Record<string, any> | null>();
@Output() filterModeChanged = new EventEmitter<'and' | 'or'>();
@Input() entity$!: Observable<Library | Shelf | null> | undefined;
@Input() entity$!: Observable<Library | Shelf | MagicShelf | null> | undefined;
@Input() entityType$!: Observable<EntityType> | undefined;
@Input() resetFilter$!: Subject<void>;
@Input() showFilter: boolean = false;
@@ -185,6 +188,7 @@ export class BookFilterComponent implements OnInit, OnDestroy {
bookService = inject(BookService);
userService = inject(UserService);
filterSortPreferenceService = inject(FilterSortPreferenceService);
bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
ngOnInit(): void {
combineLatest([
@@ -283,9 +287,21 @@ export class BookFilterComponent implements OnInit, OnDestroy {
if (entityType === EntityType.LIBRARY && entity && 'id' in entity) {
return books.filter((book) => book.libraryId === entity.id);
}
if (entityType === EntityType.SHELF && entity && 'id' in entity) {
return books.filter((book) => book.shelves?.some((shelf) => shelf.id === entity.id));
}
if (entityType === EntityType.MAGIC_SHELF && entity && 'filterJson' in entity) {
try {
const groupRule = JSON.parse(entity.filterJson) as GroupRule;
return books.filter((book) => this.bookRuleEvaluatorService.evaluateGroup(book, groupRule));
} catch (e) {
console.warn('Invalid filterJson for MagicShelf:', e);
return [];
}
}
return books;
}
@@ -63,7 +63,7 @@ export class BookService {
return currentState.books.filter(book => idSet.has(+book.id));
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | undefined>, shelvesToUnassign: Set<number | undefined>): Observable<Book[]> {
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
const requestPayload = {
bookIds: Array.from(bookIds),
shelvesToAssign: Array.from(shelvesToAssign),
@@ -422,6 +422,10 @@ export class BookService {
);
}
getMagicShelfBookCount(number: number) {
}
/*------------------ All the websocket handlers go below ------------------*/
@@ -10,6 +10,8 @@ import {MetadataFetchOptionsComponent} from '../../metadata/metadata-options-dia
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {LibraryCreatorComponent} from '../components/library-creator/library-creator.component';
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
import {MagicShelf, MagicShelfService} from '../../magic-shelf-service';
import {MagicShelfComponent} from '../../magic-shelf-component/magic-shelf-component';
@Injectable({
providedIn: 'root',
@@ -22,8 +24,9 @@ export class LibraryShelfMenuService {
private shelfService = inject(ShelfService);
private router = inject(Router);
private dialogService = inject(DialogService);
private magicShelfService = inject(MagicShelfService);
initializeLibraryMenuItems(entity: Library | Shelf | null): MenuItem[] {
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
return [
{
label: 'Options',
@@ -184,4 +187,53 @@ export class LibraryShelfMenuService {
}
];
}
initializeMagicShelfMenuItems(entity: any): MenuItem[] {
return [
{
label: 'Options',
items: [
{
label: 'Edit Magic Shelf',
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogService.open(MagicShelfComponent, {
header: 'Edit Magic Shelf',
modal: true,
closable: true,
data: {
id: entity?.id
}
})
}
},
{
label: 'Delete Magic Shelf',
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to delete magic shelf: ${entity?.name}?`,
header: 'Confirmation',
accept: () => {
this.magicShelfService.deleteShelf(entity?.id!).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Magic shelf was deleted'});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete shelf',
});
}
});
}
});
}
}
]
}
];
}
}
@@ -0,0 +1,80 @@
import {inject, Injectable} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {GithubSupportDialog} from './utilities/component/github-support-dialog/github-support-dialog';
import {LibraryCreatorComponent} from './book/components/library-creator/library-creator.component';
import {BookUploaderComponent} from './utilities/component/book-uploader/book-uploader.component';
import {UserProfileDialogComponent} from './settings/global-preferences/user-profile-dialog/user-profile-dialog.component';
import {MagicShelfComponent} from './magic-shelf-component/magic-shelf-component';
@Injectable({
providedIn: 'root',
})
export class DialogLauncherService {
dialogService = inject(DialogService);
open(options: { component: any; header: string; top?: string; width?: string }): DynamicDialogRef {
const isMobile = window.innerWidth <= 768;
const {component, header, top, width} = options;
return this.dialogService.open(component, {
header,
modal: true,
closable: true,
contentStyle: {
overflowY: 'hidden',
},
style: {
position: 'absolute',
...(top ? {top} : {}),
...(isMobile
? {
width: '90vw',
maxWidth: '90vw',
minWidth: '90vw',
}
: width
? {width}
: {}),
},
});
}
openGithubSupportDialog(): void {
this.open({
component: GithubSupportDialog,
header: 'Support BookLore on GitHub',
top: '25%'
});
}
openLibraryCreatorDialog(): void {
this.open({
component: LibraryCreatorComponent,
header: 'Create New Library',
top: '15%'
});
}
openFileUploadDialog(): void {
this.open({
component: BookUploaderComponent,
header: 'Book Uploader',
top: '10%'
});
}
openUserProfileDialog(): void {
this.open({
component: UserProfileDialogComponent,
header: 'User Profile Information',
top: '10%'
});
}
openMagicShelfDialog(): void {
this.open({
component: MagicShelfComponent,
header: 'Magic Shelf Creator'
});
}
}
@@ -0,0 +1,12 @@
<input type="text" placeholder="Search icons..." [(ngModel)]="searchText" class="icon-search"/>
<div class="icon-grid">
@for (icon of filteredIcons(); track icon) {
<div
class="icon-item"
(click)="selectIcon(icon)"
[class.selected]="icon === selectedIcon">
<i [class]="icon"></i>
</div>
}
</div>
@@ -0,0 +1,32 @@
.icon-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(25px, 1fr));
gap: 30px;
}
.icon-item {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.icon-search {
width: 100%;
padding: 8px 12px;
font-size: 16px;
border: 1px solid var(--text-color-secondary);
border-radius: 4px;
margin-bottom: 15px;
box-sizing: border-box;
}
.icon-search:focus {
border-color: var(--primary-color);
outline: none;
}
.icon-search::placeholder {
color: var(--text-color-secondary);
opacity: 1;
}
@@ -0,0 +1,71 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-icon-picker-v2-component',
imports: [
FormsModule
],
templateUrl: './icon-picker-v2-component.html',
styleUrl: './icon-picker-v2-component.scss'
})
export class IconPickerV2Component {
iconCategories: string[] = [
"address-book", "align-center", "align-justify", "align-left", "align-right", "android",
"angle-double-down", "angle-double-left", "angle-double-right", "angle-double-up", "angle-down", "angle-left",
"angle-right", "angle-up", "apple", "arrow-circle-down", "arrow-circle-left", "arrow-circle-right",
"arrow-circle-up", "arrow-down-left-and-arrow-up-right-to-center", "arrow-down-left", "arrow-down-right", "arrow-down", "arrow-left",
"arrow-right-arrow-left", "arrow-right", "arrow-up-left", "arrow-up-right-and-arrow-down-left-from-center", "arrow-up-right", "arrow-up",
"arrows-alt", "arrows-h", "arrows-v", "asterisks", "at", "backward", "ban", "barcode", "bars", "bell-slash", "bell", "bitcoin",
"bolt", "book", "bookmark-fill", "bookmark", "box", "briefcase", "building-columns", "building", "bullseye", "calculator", "calendar-clock", "calendar-minus",
"calendar-plus", "calendar-times", "calendar", "camera", "car", "caret-down", "caret-left", "caret-right", "caret-up", "cart-arrow-down", "cart-minus", "cart-plus",
"chart-bar", "chart-line", "chart-pie", "chart-scatter", "check-circle", "check-square", "check", "chevron-circle-down", "chevron-circle-left", "chevron-circle-right",
"chevron-circle-up", "chevron-down", "chevron-left", "chevron-right", "chevron-up", "circle-fill", "circle-off", "circle-on", "circle", "clipboard", "clock", "clone", "cloud-download", "cloud-upload",
"cloud", "code", "cog", "comment", "comments", "compass", "copy", "credit-card", "crown", "database", "delete-left", "desktop",
"directions-alt", "directions", "discord", "dollar", "download", "eject", "ellipsis-h", "ellipsis-v", "envelope", "equals", "eraser", "ethereum",
"euro", "exclamation-circle", "exclamation-triangle", "expand", "external-link", "eye-slash", "eye", "face-smile", "facebook", "fast-backward", "fast-forward", "file-arrow-up",
"file-check", "file-edit", "file-excel", "file-export", "file-import", "file-o", "file-pdf", "file-plus", "file-word", "file", "filter-fill", "filter-slash",
"filter", "flag-fill", "flag", "folder-open", "folder-plus", "folder", "forward", "gauge", "gift", "github", "globe", "google",
"graduation-cap", "hammer", "hashtag", "headphones", "heart-fill", "heart", "history", "home", "hourglass", "id-card", "image", "images",
"inbox", "indian-rupee", "info-circle", "info", "instagram", "key", "language", "lightbulb", "link", "linkedin", "list-check", "list",
"lock-open", "lock", "map-marker", "map", "mars", "megaphone", "microchip-ai", "microchip", "microphone", "microsoft", "minus-circle", "minus",
"mobile", "money-bill", "moon", "objects-column", "palette", "paperclip", "pause-circle", "pause", "paypal", "pen-to-square", "pencil", "percentage",
"phone", "pinterest", "play-circle", "play", "plus-circle", "plus", "pound", "power-off", "prime", "print", "qrcode", "question-circle",
"question", "receipt", "reddit", "refresh", "replay", "reply", "save", "search-minus", "search-plus", "search", "send", "server",
"share-alt", "shield", "shop", "shopping-bag", "shopping-cart", "sign-in", "sign-out", "sitemap", "slack", "sliders-h", "sliders-v", "sort-alpha-alt-down",
"sort-alpha-alt-up", "sort-alpha-down", "sort-alpha-up", "sort-alt-slash", "sort-alt", "sort-amount-down-alt", "sort-amount-down", "sort-amount-up-alt",
"sort-amount-up", "sort-down-fill", "sort-down", "sort-numeric-alt-down",
"sort-numeric-alt-up", "sort-numeric-down", "sort-numeric-up", "sort-up-fill", "sort-up", "sort", "sparkles", "spinner-dotted", "spinner", "star-fill", "star-half-fill", "star-half",
"star", "step-backward-alt", "step-backward", "step-forward-alt", "step-forward", "stop-circle", "stop", "stopwatch", "sun", "sync", "table", "tablet",
"tag", "tags", "telegram", "th-large", "thumbs-down-fill", "thumbs-down", "thumbs-up-fill", "thumbs-up", "thumbtack", "ticket", "tiktok", "times-circle",
"times", "trash", "trophy", "truck", "turkish-lira", "twitch", "twitter", "undo", "unlock", "upload", "user-edit", "user-minus",
"user-plus", "user", "users", "venus", "verified", "video", "vimeo", "volume-down", "volume-off", "volume-up", "wallet", "warehouse",
"wave-pulse", "whatsapp", "wifi", "window-maximize", "window-minimize", "wrench", "youtube"
];
searchText: string = '';
selectedIcon: string | null = null;
icons: string[] = this.createIconList(this.iconCategories);
ref = inject(DynamicDialogRef);
createIconList(categories: string[]): string[] {
return categories.map(iconName => `pi pi-${iconName}`);
}
filteredIcons(): string[] {
if (!this.searchText) return this.icons;
return this.icons.filter(icon => icon.toLowerCase().includes(this.searchText.toLowerCase()));
}
selectIcon(icon: string) {
this.selectedIcon = icon;
this.ref.close(icon);
}
cancel() {
this.ref.close();
}
}
@@ -6,9 +6,6 @@
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
@if (item.separator) {
<li class="menu-separator"></li>
}
}
}
</ul>
@@ -19,9 +16,6 @@
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
@if (item.separator) {
<li class="menu-separator"></li>
}
}
}
</ul>
@@ -32,8 +26,15 @@
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
@if (item.separator) {
<li class="menu-separator"></li>
}
}
</ul>
<ul class="layout-menu">
@if (magicShelfMenu$ | async; as shelfMenu) {
@for (item of shelfMenu; track item; let i = $index) {
@if (!item.separator) {
<li app-menuitem [item]="item" [index]="i" [root]="true"></li>
}
}
}
@@ -11,8 +11,8 @@ import {LibraryShelfMenuService} from '../../../book/service/library-shelf-menu.
import {AppVersion, VersionService} from '../../../core/service/version.service';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {VersionChangelogDialogComponent} from './version-changelog-dialog/version-changelog-dialog.component';
import {AppSettingsService} from '../../../core/service/app-settings.service';
import {UserService} from '../../../settings/user-management/user.service';
import {MagicShelf, MagicShelfService, MagicShelfState} from '../../../magic-shelf-service';
@Component({
selector: 'app-menu',
@@ -24,6 +24,7 @@ export class AppMenuComponent implements OnInit {
libraryMenu$: Observable<any> | undefined;
shelfMenu$: Observable<any> | undefined;
homeMenu$: Observable<any> | undefined;
magicShelfMenu$: Observable<any> | undefined;
versionInfo: AppVersion | null = null;
dynamicDialogRef: DynamicDialogRef | undefined;
@@ -35,12 +36,14 @@ export class AppMenuComponent implements OnInit {
private libraryShelfMenuService = inject(LibraryShelfMenuService);
private dialogService = inject(DialogService);
private userService = inject(UserService);
private magicShelfService = inject(MagicShelfService);
librarySortField: 'name' | 'id' = 'name';
librarySortOrder: 'asc' | 'desc' = 'desc';
shelfSortField: 'name' | 'id' = 'name';
shelfSortOrder: 'asc' | 'desc' = 'asc';
ngOnInit(): void {
this.versionService.getVersion().subscribe((data) => {
this.versionInfo = data;
@@ -64,7 +67,6 @@ export class AppMenuComponent implements OnInit {
map((bookState) => [
{
label: 'Home',
separator: false,
items: [
{
label: 'Dashboard',
@@ -89,11 +91,12 @@ export class AppMenuComponent implements OnInit {
map((state) => {
const libraries = state.libraries ?? [];
const sortedLibraries = this.sortArray(libraries, this.librarySortField, this.librarySortOrder);
return [
{
label: 'Library',
separator: false,
label: 'Libraries',
type: 'library',
hasDropDown: true,
hasCreate: true,
items: sortedLibraries.map((library) => ({
menu: this.libraryShelfMenuService.initializeLibraryMenuItems(library),
label: library.name,
@@ -107,6 +110,29 @@ export class AppMenuComponent implements OnInit {
})
);
this.magicShelfMenu$ = this.magicShelfService.shelvesState$.pipe(
map((state: MagicShelfState) => {
const shelves = state.shelves ?? [];
const sortedShelves = this.sortArray(shelves, 'name', 'asc');
return [
{
label: 'Magic Shelves',
type: 'magicShelf',
hasDropDown: true,
hasCreate: true,
items: sortedShelves.map((shelf) => ({
label: shelf.name,
type: 'magicShelfItem',
icon: 'pi pi-' + shelf.icon,
menu: this.libraryShelfMenuService.initializeMagicShelfMenuItems(shelf),
routerLink: [`/magic-shelf/${shelf.id}/books`],
bookCount$: this.magicShelfService.getBookCount(shelf.id ?? 0),
})),
},
];
})
);
this.shelfMenu$ = this.shelfService.shelfState$.pipe(
map((state) => {
const shelves = state.shelves ?? [];
@@ -131,8 +157,10 @@ export class AppMenuComponent implements OnInit {
return [
{
type: 'shelf',
label: 'Shelves',
separator: false,
hasDropDown: true,
hasCreate: false,
items: [unshelvedItem, ...shelfItems],
},
];
@@ -1,45 +1,56 @@
<ng-container>
@if (root && item.visible !== false) {
<div class="layout-menuitem-root-text">{{ item.label }}</div>
}
@if ((!item.routerLink || item.items) && item.visible !== false) {
<a [attr.href]="item.url"
(click)="itemClick($event)"
[ngClass]="item.class" [attr.target]="item.target" tabindex="0" pRipple>
<i [ngClass]="item.icon" class="layout-menuitem-icon"></i>
<span class="layout-menuitem-text">
{{ item.label }}
</span>
@if (item.items) {
<i class="pi pi-fw pi-angle-down layout-submenu-toggler"></i>
}
</a>
}
<div class="flex flex-row items-center justify-between">
@if ((item.routerLink && !item.items) && item.visible !== false) {
<a (click)="itemClick($event)"
[ngClass]="item.class"
[routerLink]="item.routerLink" routerLinkActive="active-route"
[routerLinkActiveOptions]="item.routerLinkActiveOptions || { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
[fragment]="item.fragment" [queryParamsHandling]="item.queryParamsHandling"
[preserveFragment]="item.preserveFragment"
[skipLocationChange]="item.skipLocationChange" [replaceUrl]="item.replaceUrl" [state]="item.state"
[queryParams]="item.queryParams"
[attr.target]="item.target" tabindex="0" pRipple>
<i [ngClass]="item.icon" class="layout-menuitem-icon"></i>
<span class="layout-menuitem-text w-full truncate">
{{ item.label }}
</span>
@if (item.items) {
<i class="pi pi-fw pi-angle-down layout-submenu-toggler"></i>
}
</a>
@if (root) {
@if (item.hasDropDown) {
<div class=" flex items-center justify-between layout-menuitem-root-text cursor-pointer pt-4">
<div class="flex items-center justify-between gap-2 cursor-pointer">
<div>{{ item.label }}</div>
@if (item.hasCreate) {
<i
class="pi pi-plus text-surface-500 hover:text-surface-200"
style="font-size: 0.8rem"
(click)="openDialog(item)"
></i>
}
</div>
<i
(click)="toggleExpand(key)"
[ngClass]="{
'pi': true,
'pi-angle-up': isExpanded(key),
'pi-angle-down': !isExpanded(key),
'text-surface-500': true,
'hover:text-surface-200': true,
'pr-3': true
}"></i>
</div>
} @else {
<div class="flex items-center justify-between layout-menuitem-root-text">
<div>{{ item.label }}</div>
</div>
}
@if ((item.routerLink && !item.items) && item.visible !== false) {
}
<div>
<div class="flex flex-row items-center justify-between hover:bg-surface-800 rounded-md">
@if ((item.routerLink && !item.items)) {
<a
(click)="itemClick($event)"
[ngClass]="item.class"
[routerLink]="item.routerLink" routerLinkActive="active-route"
[routerLinkActiveOptions]="item.routerLinkActiveOptions || { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' }"
[fragment]="item.fragment" [queryParamsHandling]="item.queryParamsHandling"
[preserveFragment]="item.preserveFragment"
[skipLocationChange]="item.skipLocationChange" [replaceUrl]="item.replaceUrl" [state]="item.state"
[queryParams]="item.queryParams"
[attr.target]="item.target" tabindex="0" pRipple>
<i [ngClass]="item.icon" class="layout-menuitem-icon"></i>
<span class="layout-menuitem-text w-full truncate">
{{ item.label }}
</span>
</a>
}
<span>
@if (item.type === 'Library' || item.type === 'Shelf') {
@if (item.type === 'Library' || item.type === 'Shelf' || item.type === 'magicShelfItem') {
@if ((item.type !== 'Library' || (admin || canManipulateLibrary)) && item.label !== 'Unshelved') {
<p-button
(click)="entitymenu.toggle($event)"
@@ -56,20 +67,23 @@
}
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
}
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.label === 'Unshelved') {
<p class="text-[var(--primary-color)] pr-3">
{{ (item.bookCount$ | async)?.toString() || '0' }}
</p>
}
</span>
}
</div>
</div>
@if (item.items && item.visible !== false) {
<ul [@children]="submenuAnimation">
@for (child of item.items; track child; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key" [class]="child.badgeClass"></li>
<div [@children]="isExpanded(key) ? 'expanded' : 'collapsed'" style="overflow: hidden;">
@if (item.items) {
<ul>
@for (child of item.items; track child; let i = $index) {
<li app-menuitem [item]="child" [index]="i" [parentKey]="key" [class]="child.badgeClass"></li>
}
</ul>
}
</ul>
}
</div>
</div>
</ng-container>
@@ -4,12 +4,12 @@ import {animate, state, style, transition, trigger} from '@angular/animations';
import {Subscription} from 'rxjs';
import {filter} from 'rxjs/operators';
import {MenuService} from './service/app.menu.service';
import { AsyncPipe, NgClass } from '@angular/common';
import {AsyncPipe, NgClass} from '@angular/common';
import {Ripple} from 'primeng/ripple';
import {Button} from 'primeng/button';
import {Menu} from 'primeng/menu';
import {MenuItem} from 'primeng/api';
import {UserService} from '../../../settings/user-management/user.service';
import {DialogLauncherService} from '../../../dialog-launcher.service';
@Component({
selector: '[app-menuitem]',
@@ -23,7 +23,7 @@ import {UserService} from '../../../settings/user-management/user.service';
AsyncPipe,
Button,
Menu
],
],
animations: [
trigger('children', [
state('collapsed', style({
@@ -52,7 +52,21 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
menuSourceSubscription: Subscription;
menuResetSubscription: Subscription;
constructor(public router: Router, private menuService: MenuService, private userService: UserService) {
expandedItems = new Set<string>();
toggleExpand(key: string) {
if (this.expandedItems.has(key)) {
this.expandedItems.delete(key);
} else {
this.expandedItems.add(key);
}
}
isExpanded(key: string): boolean {
return this.expandedItems.has(key);
}
constructor(public router: Router, private menuService: MenuService, private userService: UserService, private dialogLauncher: DialogLauncherService) {
this.userService.userState$.subscribe(userData => {
if (userData) {
this.canManipulateLibrary = userData.permissions.canManipulateLibrary;
@@ -85,6 +99,7 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
ngOnInit() {
this.key = this.parentKey ? this.parentKey + '-' + this.index : String(this.index);
this.expandedItems.add(this.key);
if (this.item.routerLink) {
this.updateActiveStateFromRoute();
}
@@ -116,10 +131,6 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
this.menuService.onMenuStateChange({key: this.key});
}
get submenuAnimation() {
return this.root ? 'expanded' : (this.active ? 'expanded' : 'collapsed');
}
@HostBinding('class.active-menuitem')
get activeClass() {
return this.active && !this.root;
@@ -133,4 +144,13 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
this.menuResetSubscription.unsubscribe();
}
}
openDialog(item: any) {
if (item.type === 'library' && this.canManipulateLibrary) {
this.dialogLauncher.openLibraryCreatorDialog();
}
if (item.type === 'magicShelf') {
this.dialogLauncher.openMagicShelfDialog();
}
}
}
@@ -3,7 +3,6 @@ import {MenuItem} from 'primeng/api';
import {LayoutService} from '../layout-main/service/app.layout.service';
import {Router, RouterLink} from '@angular/router';
import {DialogService as PrimeDialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {LibraryCreatorComponent} from '../../../book/components/library-creator/library-creator.component';
import {TooltipModule} from 'primeng/tooltip';
import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext';
@@ -14,11 +13,8 @@ import {Button} from 'primeng/button';
import {StyleClass} from 'primeng/styleclass';
import {Divider} from 'primeng/divider';
import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component';
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
import {AuthService} from '../../../core/service/auth.service';
import {UserService} from '../../../settings/user-management/user.service';
import {UserProfileDialogComponent} from '../../../settings/global-preferences/user-profile-dialog/user-profile-dialog.component';
import {GithubSupportDialog} from '../../../utilities/component/github-support-dialog/github-support-dialog';
import {Popover} from 'primeng/popover';
import {MetadataProgressService} from '../../../core/service/metadata-progress-service';
import {takeUntil} from 'rxjs/operators';
@@ -26,6 +22,7 @@ import {Subject} from 'rxjs';
import {MetadataBatchProgressNotification} from '../../../core/model/metadata-batch-progress.model';
import {UnifiedNotificationBoxComponent} from '../../../core/component/unified-notification-popover-component/unified-notification-popover-component';
import {BookdropFileService} from '../../../bookdrop/bookdrop-file.service';
import {DialogLauncherService} from '../../../dialog-launcher.service';
@Component({
selector: 'app-topbar',
@@ -79,7 +76,8 @@ export class AppTopBarComponent implements OnDestroy {
private authService: AuthService,
protected userService: UserService,
private metadataProgressService: MetadataProgressService,
private bookdropFileService: BookdropFileService
private bookdropFileService: BookdropFileService,
private dialogLauncher: DialogLauncherService
) {
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
@@ -116,19 +114,19 @@ export class AppTopBarComponent implements OnDestroy {
}
openGithubSupportDialog(): void {
this.openDialog(GithubSupportDialog, 'Support BookLore on GitHub', '25%');
this.dialogLauncher.openGithubSupportDialog();
}
openLibraryCreatorDialog(): void {
this.openDialog(LibraryCreatorComponent, 'Create New Library', '15%');
this.dialogLauncher.openLibraryCreatorDialog();
}
openFileUploadDialog(): void {
this.openDialog(BookUploaderComponent, 'Book Uploader', '10%');
this.dialogLauncher.openFileUploadDialog();
}
openUserProfileDialog(): void {
this.openDialog(UserProfileDialogComponent, 'User Profile Information', '10%');
this.dialogLauncher.openUserProfileDialog();
}
navigateToSettings() {
@@ -139,24 +137,6 @@ export class AppTopBarComponent implements OnDestroy {
this.authService.logout();
}
private openDialog(component: any, header: string, top: string) {
const isMobile = window.innerWidth <= 768;
this.ref = this.dialogService.open(component, {
header,
modal: true,
closable: true,
style: {
position: 'absolute',
top,
...(isMobile && {
width: '90vw',
maxWidth: '90vw',
minWidth: '90vw',
}),
},
});
}
private subscribeToMetadataProgress() {
this.metadataProgressService.progressUpdates$
.pipe(takeUntil(this.destroy$))
@@ -0,0 +1,112 @@
<div class="flex flex-col border border-[var(--border-color)] rounded-lg w-[75rem] min-h-[50rem] overflow-hidden">
<div class="px-8 pt-8 flex-grow overflow-auto" [formGroup]="form">
<div class="mb-4 flex w-full gap-4">
<div class="flex-1">
<label for="shelfName" class="block mb-1 font-semibold">Shelf Name</label>
<input pInputText id="shelfName" type="text" formControlName="name" placeholder="E.g. Rom-Zom-Coms, Fast & Furious, Missing Metadata" class="w-full"/>
</div>
<div class="flex items-end">
<div>
<label class="block mb-1 font-semibold">Shelf Icon</label>
<p-button
[icon]="form.get('icon')?.value || 'pi pi-plus'"
(click)="openIconPicker()"
[outlined]="form.get('icon')?.value"
[severity]="form.get('icon')?.value ? 'success' : 'danger'"
[label]="form.get('icon')?.value ? 'Icon Selected' : 'Select Icon'">
</p-button>
</div>
</div>
</div>
<div class="overflow-auto max-h-[40rem]">
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: form.get('group') }"></ng-container>
</div>
<div class="my-4 text-left">
<p-button
label="Save Filter"
outlined
severity="success"
(click)="submit()"
[disabled]="form.invalid"></p-button>
</div>
</div>
<ng-template #groupTemplate let-group="group">
<div class="p-3 border-l-4 border-sky-500 mt-2 w-full" [formGroup]="group">
<div class="mb-2 flex items-center gap-2">
<label class="font-semibold">Condition:</label>
<p-select [options]="conditionOptions" formControlName="join" class="w-28" appendTo="body" [showClear]="false"/>
<p-button icon="pi pi-plus" size="small" text (click)="addRule(group)" label="Add Rule"></p-button>
<p-button icon="pi pi-folder-open" size="small" text (click)="addGroup(group)" label="Add Group"></p-button>
@if (group.parent) {
<p-button icon="pi pi-trash" text (click)="deleteGroup(group)" severity="danger"></p-button>
}
</div>
<div formArrayName="rules">
@for (ruleCtrl of group.get('rules')['controls']; let i = $index; track trackByFn(ruleCtrl, i)) {
<div [formGroupName]="i" class="ml-4 mt-2 flex gap-3 items-center">
@if (isGroup(ruleCtrl)) {
<ng-container>
<ng-container *ngTemplateOutlet="groupTemplate; context: { group: ruleCtrl }"></ng-container>
</ng-container>
} @else {
<p-select [options]="fieldOptions" formControlName="field" (onChange)="onFieldChange(ruleCtrl)" placeholder="Field" appendTo="body" class="min-w-56"/>
<p-select [options]="getOperatorOptionsForField(ruleCtrl.get('field')?.value)" appendTo="body" formControlName="operator" placeholder="Operator" class="min-w-56" (onChange)="onOperatorChange(ruleCtrl)"/>
@if (!['is_empty', 'is_not_empty'].includes(ruleCtrl.get('operator')?.value)) {
@if (ruleCtrl.get('operator')?.value === 'in_between') {
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
<p-datepicker [formControl]="ruleCtrl.get('valueStart')" dateFormat="dd-M-yy" placeholder="Start Year" appendTo="body" fluid class="w-full"></p-datepicker>
<p-datepicker [formControl]="ruleCtrl.get('valueEnd')" dateFormat="dd-M-yy" placeholder="End Year" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
<p-inputNumber [formControl]="ruleCtrl.get('valueStart')" [min]="0" class="w-full" placeholder="Start Value" [showButtons]="true"></p-inputNumber>
<p-inputNumber [formControl]="ruleCtrl.get('valueEnd')" [min]="0" class="w-full" placeholder="End Value" [showButtons]="true"></p-inputNumber>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
<p-inputNumber [formControl]="ruleCtrl.get('valueStart')" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max" class="w-full" placeholder="Start Value" [showButtons]="true"></p-inputNumber>
<p-inputNumber [formControl]="ruleCtrl.get('valueEnd')" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max" class="w-full" placeholder="End Value" [showButtons]="true"></p-inputNumber>
} @else {
<input pInputText [formControl]="ruleCtrl.get('valueStart')" class="w-full" placeholder="Start Value"/>
<input pInputText [formControl]="ruleCtrl.get('valueEnd')" class="w-full" placeholder="End Value"/>
}
} @else {
@if (ruleCtrl.get('field')?.value === 'publishedDate') {
<p-datepicker formControlName="value" dateFormat="dd-M-yy" appendTo="body" fluid class="w-full"></p-datepicker>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'number') {
<p-inputNumber formControlName="value" class="w-full" mode="decimal" placeholder="Value" [showButtons]="true"></p-inputNumber>
} @else if (numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.type === 'decimal') {
<p-inputNumber formControlName="value" mode="decimal" [minFractionDigits]="1" [maxFractionDigits]="1" [min]="0" [max]="numericFieldConfigMap.get(ruleCtrl.get('field')?.value)?.max" class="w-full" placeholder="Value" [showButtons]="true"></p-inputNumber>
} @else if (['includes_any', 'includes_all', 'excludes_all'].includes(ruleCtrl.get('operator')?.value)) {
@if (ruleCtrl.get('field')?.value === 'readStatus') {
<p-multiSelect [options]="readStatusOptions" formControlName="value" display="chip" class="w-full" appendTo="body" placeholder="Select Statuses"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
<p-multiSelect [options]="fileType" formControlName="value" display="chip" class="w-full" appendTo="body" placeholder="Select File Types"></p-multiSelect>
} @else if (ruleCtrl.get('field')?.value === 'library') {
<p-multiSelect [options]="libraryOptions" formControlName="value" display="chip" class="w-full" appendTo="body" placeholder="Select Libraries"></p-multiSelect>
} @else {
<div class="w-full">
<p-chips [formControl]="ruleCtrl.get('value')" separator="," placeholder="Enter values (press Enter or comma)" class="w-full"></p-chips>
</div>
}
} @else if (ruleCtrl.get('field')?.value === 'readStatus') {
<p-select [options]="readStatusOptions" formControlName="value" placeholder="Select Status" appendTo="body" class="w-full"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'fileType') {
<p-select [options]="fileType" formControlName="value" placeholder="Select File Type" appendTo="body" class="w-full"></p-select>
} @else if (ruleCtrl.get('field')?.value === 'library') {
<p-select [options]="libraryOptions" formControlName="value" placeholder="Select Library" appendTo="body" class="w-full"></p-select>
} @else {
<input pInputText formControlName="value" class="w-full" placeholder="Value"/>
}
}
}
<p-button icon="pi pi-trash" text severity="danger" (click)="removeRule(group, i)"></p-button>
}
</div>
}
</div>
</div>
</ng-template>
</div>
@@ -0,0 +1,458 @@
import {Component, inject, OnInit} from '@angular/core';
import {AbstractControl, FormArray, FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {DropdownModule} from 'primeng/dropdown';
import {Button} from 'primeng/button';
import {NgTemplateOutlet} from '@angular/common';
import {InputText} from 'primeng/inputtext';
import {Select} from 'primeng/select';
import {DatePicker} from 'primeng/datepicker';
import {InputNumber} from 'primeng/inputnumber';
import {ReadStatus} from '../book/model/book.model';
import {LibraryService} from '../book/service/library.service';
import {Library} from '../book/model/library.model';
import {MagicShelfService} from '../magic-shelf-service';
import {MessageService} from 'primeng/api';
import {IconPickerV2Component} from '../icon-picker-v2-component/icon-picker-v2-component';
import {DialogService, DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {Chips} from 'primeng/chips';
import {MultiSelect} from 'primeng/multiselect';
import {EMPTY_CHECK_OPERATORS, MULTI_VALUE_OPERATORS, parseValue, removeNulls, serializeDateRules} from '../magic-shelf-utils';
export type RuleOperator =
| 'equals'
| 'not_equals'
| 'contains'
| 'does_not_contain'
| 'starts_with'
| 'ends_with'
| 'greater_than'
| 'greater_than_equal_to'
| 'less_than'
| 'less_than_equal_to'
| 'in_between'
| 'is_empty'
| 'is_not_empty'
| 'includes_any'
| 'excludes_all'
| 'includes_all'
export type RuleField =
| 'library'
| 'title'
| 'subtitle'
| 'authors'
| 'categories'
| 'publisher'
| 'publishedDate'
| 'seriesName'
| 'seriesNumber'
| 'seriesTotal'
| 'pageCount'
| 'language'
| 'amazonRating'
| 'amazonReviewCount'
| 'goodreadsRating'
| 'goodreadsReviewCount'
| 'hardcoverRating'
| 'hardcoverReviewCount'
| 'personalRating'
| 'fileType'
| 'fileSize'
| 'readStatus'
| 'metadataScore';
interface FullFieldConfig {
label: string;
type?: FieldType;
max?: number;
}
type FieldType = 'number' | 'decimal' | 'date' | undefined;
export interface Rule {
field: RuleField;
operator: RuleOperator;
value: any;
valueStart?: any;
valueEnd?: any;
}
export interface FieldConfig {
type: FieldType;
max?: number;
}
export interface GroupRule {
name: string;
type: 'group';
join: 'and' | 'or';
rules: Array<Rule | GroupRule>;
}
export type RuleFormGroup = FormGroup<{
field: FormControl<"" | RuleField | null>;
operator: FormControl<"" | RuleOperator | null>;
value: FormControl<string | null>;
valueStart: FormControl<string | null>;
valueEnd: FormControl<string | null>;
}>;
export type GroupFormGroup = FormGroup<{
type: FormControl<'group'>;
join: FormControl<'and' | 'or'>;
rules: FormArray<GroupFormGroup | RuleFormGroup>;
}>;
const FIELD_CONFIGS: Record<RuleField, FullFieldConfig> = {
library: {label: 'Library'},
readStatus: {label: 'Read Status'},
metadataScore: {label: 'Metadata Score', type: 'decimal', max: 100},
title: {label: 'Title'},
authors: {label: 'Authors'},
categories: {label: 'Categories'},
publisher: {label: 'Publisher'},
publishedDate: {label: 'Published Date', type: 'date'},
personalRating: {label: 'Personal Rating', type: 'decimal', max: 10},
pageCount: {label: 'Page Count', type: 'number'},
language: {label: 'Language'},
seriesName: {label: 'Series Name'},
seriesNumber: {label: 'Series Number', type: 'number'},
seriesTotal: {label: 'Books in Series', type: 'number'},
fileSize: {label: 'File Size (Kb)', type: 'number'},
fileType: {label: 'File Type'},
subtitle: {label: 'Subtitle'},
amazonRating: {label: 'Amazon Rating', type: 'decimal', max: 5},
amazonReviewCount: {label: 'Amazon Review Count', type: 'number'},
goodreadsRating: {label: 'Goodreads Rating', type: 'decimal', max: 5},
goodreadsReviewCount: {label: 'Goodreads Review Count', type: 'number'},
hardcoverRating: {label: 'Hardcover Rating', type: 'decimal', max: 5},
hardcoverReviewCount: {label: 'Hardcover Review Count', type: 'number'}
};
@Component({
selector: 'app-magic-shelf',
templateUrl: './magic-shelf-component.html',
standalone: true,
imports: [
ReactiveFormsModule,
DropdownModule,
NgTemplateOutlet,
InputText,
Select,
Button,
DatePicker,
InputNumber,
Chips,
MultiSelect
]
})
export class MagicShelfComponent implements OnInit {
numericFieldConfigMap = new Map<RuleField, FieldConfig>(
Object.entries(FIELD_CONFIGS)
.filter(([_, config]) => config.type)
.map(([key, config]) => [key as RuleField, {type: config.type!, max: config.max}])
);
conditionOptions: { label: string; value: 'and' | 'or' }[] = [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'},
];
fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => ({
label: config.label,
value: key as RuleField
}));
fileType: { label: string; value: string }[] = [
{label: 'PDF', value: 'pdf'},
{label: 'EPUB', value: 'epub'},
{label: 'CBR', value: 'cbr'},
{label: 'CBZ', value: 'cbz'},
{label: 'CB7', value: 'cb7'}
];
readStatusOptions = Object.entries(ReadStatus).map(([key, value]) => ({
label: key.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase()),
value
}));
libraries: Library[] = [];
libraryOptions: { label: string; value: number }[] = [];
form = new FormGroup({
name: new FormControl<string | null>(null),
icon: new FormControl<string | null>(null),
group: this.createGroup()
});
shelfId: number | null = null;
libraryService = inject(LibraryService);
magicShelfService = inject(MagicShelfService);
messageService = inject(MessageService);
dialogService = inject(DialogService);
config = inject(DynamicDialogConfig);
trackByFn(ruleCtrl: AbstractControl, index: number): any {
return ruleCtrl;
}
ngOnInit(): void {
const id = this.config?.data?.id;
if (id) {
this.shelfId = id;
this.magicShelfService.getShelf(id).subscribe((data) => {
this.form = new FormGroup({
name: new FormControl<string | null>(data?.name ?? null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(data?.icon ?? null, {nonNullable: true, validators: [Validators.required]}),
group: data?.filterJson ? this.buildGroupFromData(JSON.parse(data.filterJson)) : this.createGroup()
});
});
} else {
this.form = new FormGroup({
name: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
icon: new FormControl<string | null>(null, {nonNullable: true, validators: [Validators.required]}),
group: this.createGroup()
});
}
this.libraries = this.libraryService.getLibrariesFromState();
this.libraryOptions = this.libraries.map(lib => ({
label: lib.name,
value: lib.id!
}));
}
buildGroupFromData(data: GroupRule): GroupFormGroup {
const rulesArray = new FormArray<FormGroup>([]);
data.rules.forEach(rule => {
if ('type' in rule && rule.type === 'group') {
rulesArray.push(this.buildGroupFromData(rule));
} else {
rulesArray.push(this.buildRuleFromData(rule as Rule));
}
});
return new FormGroup({
type: new FormControl<'group'>('group'),
join: new FormControl(data.join),
rules: rulesArray as FormArray<GroupFormGroup | RuleFormGroup>
}) as GroupFormGroup;
}
buildRuleFromData(data: Rule): RuleFormGroup {
const config = FIELD_CONFIGS[data.field];
const type = config?.type;
return new FormGroup({
field: new FormControl<RuleField>(data.field),
operator: new FormControl<RuleOperator>(data.operator),
value: new FormControl(parseValue(data.value, type)),
valueStart: new FormControl(parseValue(data.valueStart, type)),
valueEnd: new FormControl(parseValue(data.valueEnd, type)),
}) as RuleFormGroup;
}
get group(): GroupFormGroup {
return this.form.get('group') as GroupFormGroup;
}
getOperatorOptionsForField(field: RuleField | null | undefined) {
const baseOperators = [
{label: 'Equals', value: 'equals'},
{label: '≠ Not Equal', value: 'not_equals'},
{label: 'Empty', value: 'is_empty'},
{label: 'Not Empty', value: 'is_not_empty'},
];
const multiValueOperators = [
{label: 'Includes Any', value: 'includes_any'},
{label: 'Excludes All', value: 'excludes_all'},
{label: 'Includes All', value: 'includes_all'},
];
const textOperators = [
{label: 'Contains', value: 'contains'},
{label: 'Doesn\'t Contain', value: 'does_not_contain'},
{label: 'Starts With', value: 'starts_with'},
{label: 'Ends With', value: 'ends_with'},
];
const comparisonOperators = [
{label: '> Greater Than', value: 'greater_than'},
{label: '≥ Greater or Equal', value: 'greater_than_equal_to'},
{label: '< Less Than', value: 'less_than'},
{label: '≤ Less or Equal', value: 'less_than_equal_to'},
{label: 'Between', value: 'in_between'},
];
if (!field) return [...baseOperators, ...multiValueOperators];
const config = FIELD_CONFIGS[field];
const isMultiValueField = ['library', 'authors', 'categories', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName'].includes(field);
const operators = [...baseOperators];
if (isMultiValueField) {
operators.push(...multiValueOperators);
}
const isTextEligible = !['library', 'readStatus', 'fileType'].includes(field);
if (config.type === 'number' || config.type === 'decimal' || config.type === 'date') {
operators.push(...comparisonOperators);
} else if (isTextEligible) {
operators.push(...textOperators);
}
return operators;
}
createRule(): RuleFormGroup {
return new FormGroup({
field: new FormControl<RuleField | ''>(''),
operator: new FormControl<RuleOperator | ''>(''),
value: new FormControl<string | null>(null),
valueStart: new FormControl<string | null>(null),
valueEnd: new FormControl<string | null>(null),
}) as RuleFormGroup;
}
createGroup(): GroupFormGroup {
return new FormGroup({
type: new FormControl<'group'>('group' as 'group'),
join: new FormControl<'and' | 'or'>('and' as 'and' | 'or'),
rules: new FormArray([] as Array<GroupFormGroup | RuleFormGroup>),
}) as GroupFormGroup;
}
addGroup(group: GroupFormGroup) {
const rules = group.get('rules') as FormArray;
rules.push(this.createGroup());
}
addRule(group: GroupFormGroup) {
const rules = group.get('rules') as FormArray;
rules.push(this.createRule());
}
deleteGroup(group: GroupFormGroup) {
const parent = group.parent;
if (parent && parent instanceof FormArray) {
const index = parent.controls.indexOf(group);
if (index > -1) {
parent.removeAt(index);
}
}
}
removeRule(group: GroupFormGroup, index: number) {
const rules = group.get('rules') as FormArray;
rules.removeAt(index);
}
isGroup(control: AbstractControl): boolean {
return control instanceof FormGroup && control.get('rules') instanceof FormArray;
}
onOperatorChange(ruleCtrl: FormGroup) {
const operator = ruleCtrl.get('operator')?.value as RuleOperator;
const valueCtrl = ruleCtrl.get('value');
const valueStartCtrl = ruleCtrl.get('valueStart');
const valueEndCtrl = ruleCtrl.get('valueEnd');
if (MULTI_VALUE_OPERATORS.includes(operator)) {
valueCtrl?.setValue([]);
valueStartCtrl?.setValue(null);
valueEndCtrl?.setValue(null);
} else if (EMPTY_CHECK_OPERATORS.includes(operator)) {
valueCtrl?.setValue(null);
valueStartCtrl?.setValue(null);
valueEndCtrl?.setValue(null);
} else {
valueCtrl?.setValue('');
valueStartCtrl?.setValue(null);
valueEndCtrl?.setValue(null);
}
}
onFieldChange(ruleCtrl: RuleFormGroup) {
ruleCtrl.get('operator')?.setValue('');
ruleCtrl.get('value')?.setValue(null);
ruleCtrl.get('valueStart')?.setValue(null);
ruleCtrl.get('valueEnd')?.setValue(null);
}
openIconPicker() {
const isMobile = window.innerWidth <= 768;
const ref: DynamicDialogRef = this.dialogService.open(IconPickerV2Component, {
header: 'Choose an Icon',
style: {
position: 'absolute',
top: '10%',
bottom: '10%',
width: isMobile ? '90vw' : '800px',
maxWidth: isMobile ? '90vw' : '800px',
minWidth: isMobile ? '90vw' : '800px',
},
dismissableMask: true,
});
ref.onClose.subscribe((icon: string) => {
if (icon) {
this.form.get('icon')?.setValue(icon);
}
});
}
private hasAtLeastOneValidRule(group: GroupFormGroup): boolean {
const rulesArray = group.get('rules') as FormArray;
return rulesArray.controls.some(ctrl => {
const type = (ctrl.get('type') as FormControl<'group'> | null)?.value;
if (type === 'group') {
return this.hasAtLeastOneValidRule(ctrl as GroupFormGroup);
} else {
const field = ctrl.get('field')?.value;
const operator = ctrl.get('operator')?.value;
return !!field && !!operator;
}
});
}
submit() {
if (!this.hasAtLeastOneValidRule(this.group)) {
this.messageService.add({severity: 'warn', summary: 'Validation Error', detail: 'You must add at least one valid rule before saving.'});
return;
}
const value = this.form.value as { name: string | null; icon: string | null; group: GroupRule };
const cleanedGroup = removeNulls(serializeDateRules(value.group));
this.magicShelfService.saveShelf({
id: this.shelfId ?? undefined,
name: value.name,
icon: value.icon,
group: cleanedGroup
}).subscribe({
next: (savedShelf) => {
this.messageService.add({severity: 'success', summary: 'Success', detail: 'Magic shelf saved successfully.'});
if (savedShelf?.id) {
this.shelfId = savedShelf.id;
}
},
error: (err) => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: err?.error?.message || 'Failed to save magic shelf.'
});
}
});
}
}
+139
View File
@@ -0,0 +1,139 @@
import {inject, Injectable} from '@angular/core';
import {API_CONFIG} from './config/api-config';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, map, switchMap, tap} from 'rxjs/operators';
import {BookService} from './book/service/book.service';
import {GroupRule} from './magic-shelf-component/magic-shelf-component';
import {BookRuleEvaluatorService} from './book-rule-evaluator.service';
export interface MagicShelf {
id?: number | null;
name: string;
icon?: string;
filterJson: string;
}
export interface MagicShelfState {
shelves: MagicShelf[];
loaded: boolean;
error: string | null;
}
@Injectable({
providedIn: 'root',
})
export class MagicShelfService {
private readonly url = `${API_CONFIG.BASE_URL}/api/magic-shelves`;
private readonly http = inject(HttpClient);
private readonly bookService = inject(BookService);
private readonly ruleEvaluatorService = inject(BookRuleEvaluatorService);
private readonly shelvesStateSubject = new BehaviorSubject<MagicShelfState>({
shelves: [],
loaded: false,
error: null,
});
public readonly shelvesState$ = this.shelvesStateSubject.asObservable();
constructor() {
this.loadUserShelves().subscribe();
}
private get state(): MagicShelfState {
return this.shelvesStateSubject.value;
}
loadUserShelves(): Observable<MagicShelf[]> {
return this.http.get<MagicShelf[]>(this.url).pipe(
tap((shelves) => this.updateShelves(shelves)),
catchError((error) => {
this.updateError(error.message);
return of([]);
})
);
}
saveShelf(data: { id?: number; name: string | null; icon: string | null; group: any }): Observable<MagicShelf> {
const payload: MagicShelf = {
id: data.id,
name: data.name ?? '',
icon: data.icon ?? 'pi pi-book',
filterJson: JSON.stringify(data.group),
};
return this.http.post<MagicShelf>(this.url, payload).pipe(
tap((newShelf) => {
const shelves = this.state.shelves;
const updated = shelves.some((s) => s.id === newShelf.id)
? shelves.map((s) => (s.id === newShelf.id ? newShelf : s))
: [...shelves, newShelf];
this.updateShelves(updated);
}),
catchError((error) => {
this.updateError(error.message);
throw error;
})
);
}
getShelf(id: number): Observable<MagicShelf | undefined> {
return this.shelvesState$.pipe(
map(state => state.shelves.find(shelf => shelf.id === id))
);
}
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
const updated = this.state.shelves.filter((s) => s.id !== id);
this.updateShelves(updated);
}),
catchError((error) => {
this.updateError(error.message);
throw error;
})
);
}
private updateShelves(shelves: MagicShelf[]): void {
this.shelvesStateSubject.next({
shelves,
loaded: true,
error: null,
});
}
private updateError(error: string): void {
this.shelvesStateSubject.next({
...this.state,
error,
loaded: true,
});
}
getBookCount(shelfId: number): Observable<number> {
return this.getShelf(shelfId).pipe(
switchMap((shelf) => {
if (!shelf) return of(0);
let group: GroupRule;
try {
group = JSON.parse(shelf.filterJson);
} catch (e) {
console.error('Invalid filter JSON', e);
return of(0);
}
return this.bookService.bookState$.pipe(
map((state) =>
(state.books ?? []).filter((book) =>
this.ruleEvaluatorService.evaluateGroup(book, group)
).length
)
);
})
);
}
}
+61
View File
@@ -0,0 +1,61 @@
// magic-shelf-utils.ts
import {RuleOperator} from './magic-shelf-component/magic-shelf-component';
export const MULTI_VALUE_OPERATORS: RuleOperator[] = [
'includes_any',
'includes_all',
'excludes_all'
];
export const EMPTY_CHECK_OPERATORS: RuleOperator[] = [
'is_empty',
'is_not_empty'
];
export function parseValue(val: any, type: 'string' | 'number' | 'decimal' | 'date' | undefined): any {
if (val == null) return null;
if (type === 'number' || type === 'decimal') {
const num = Number(val);
return isNaN(num) ? null : num;
}
if (type === 'date') {
const d = new Date(val);
return isNaN(d.getTime()) ? null : d;
}
return val;
}
export function removeNulls(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(removeNulls);
} else if (typeof obj === 'object' && obj !== null) {
return Object.entries(obj).reduce((acc, [key, value]) => {
const cleanedValue = removeNulls(value);
if (cleanedValue !== null && cleanedValue !== undefined) {
acc[key] = cleanedValue;
}
return acc;
}, {} as any);
}
return obj;
}
export function serializeDateRules(ruleOrGroup: any): any {
if ('rules' in ruleOrGroup) {
return {
...ruleOrGroup,
rules: ruleOrGroup.rules.map(serializeDateRules)
};
}
const isDateField = ruleOrGroup.field === 'publishedDate';
const serialize = (val: any) => (val instanceof Date ? val.toISOString().split('T')[0] : val);
return {
...ruleOrGroup,
value: isDateField ? serialize(ruleOrGroup.value) : ruleOrGroup.value,
valueStart: isDateField ? serialize(ruleOrGroup.valueStart) : ruleOrGroup.valueStart,
valueEnd: isDateField ? serialize(ruleOrGroup.valueEnd) : ruleOrGroup.valueEnd
};
}
@@ -260,7 +260,7 @@
<span
class="inline-block px-2 py-0.5 rounded-lg text-xs font-bold text-gray-200 border"
[ngClass]="getMatchScoreColorClass(book?.metadataMatchScore!)">
{{ (book?.metadataMatchScore! * 100) | number:'1.0-0' }}%
{{ (book?.metadataMatchScore!) | number:'1.0-0' }}%
</span>
} @else {
<span>-</span>
@@ -40,12 +40,12 @@
<label class="capitalize w-full max-w-[150px]">
{{ labelMap[key] }}
</label>
<input
pSize="small"
type="number"
pInputText
<p-inputNumber
[formControlName]="key"
class="w-16 text-center"
[min]="0"
[max]="10"
fluid
[showButtons]="true"
/>
</div>
}
@@ -3,12 +3,12 @@ import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/
import {MessageService} from 'primeng/api';
import {MetadataMatchWeightsService} from '../../../utilities/service/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';
import {InputNumber} from 'primeng/inputnumber';
@Component({
@@ -16,8 +16,8 @@ import {AppSettingsService} from '../../../core/service/app-settings.service';
imports: [
ReactiveFormsModule,
Button,
InputText,
Tooltip
Tooltip,
InputNumber
],
templateUrl: './metadata-match-weights-component.html',
styleUrl: './metadata-match-weights-component.scss'
+112
View File
@@ -0,0 +1,112 @@
import {AbstractControl, FormArray} from '@angular/forms';
export class SqlFilterBuilder {
static toSQL(group: AbstractControl): string {
const condition: 'and' | 'or' = group.get('join')?.value ?? 'and';
const rules = group.get('rules') as FormArray;
const parts: string[] = [];
rules.controls.forEach((ctrl: AbstractControl) => {
if (this.isGroup(ctrl)) {
parts.push(`(${this.toSQL(ctrl)})`);
return;
}
const field = ctrl.get('field')?.value;
const operator = ctrl.get('operator')?.value;
const value = ctrl.get('value')?.value;
const valueStart = ctrl.get('valueStart')?.value;
const valueEnd = ctrl.get('valueEnd')?.value;
if (!field || !operator) return;
if (operator === 'in_between') {
parts.push(`${field} BETWEEN ${this.formatSQLValue(valueStart)} AND ${this.formatSQLValue(valueEnd)}`);
return;
}
if (field === 'library') {
parts.push(`${field} = ${value}`);
return;
}
let sqlOperator = '';
let sqlValue = '';
switch (operator) {
case 'equals':
sqlOperator = '=';
sqlValue = this.formatSQLValue(value);
break;
case 'not_equals':
sqlOperator = '!=';
sqlValue = this.formatSQLValue(value);
break;
case 'contains':
sqlOperator = 'LIKE';
sqlValue = `'%${String(value).replace(/'/g, "''")}%'`;
break;
case 'starts_with':
sqlOperator = 'LIKE';
sqlValue = `'${String(value).replace(/'/g, "''")}%'`;
break;
case 'ends_with':
sqlOperator = 'LIKE';
sqlValue = `'%${String(value).replace(/'/g, "''")}'`;
break;
case 'greater_than':
sqlOperator = '>';
sqlValue = this.formatSQLValue(value);
break;
case 'less_than':
sqlOperator = '<';
sqlValue = this.formatSQLValue(value);
break;
case 'is_empty':
parts.push(`(${field} IS NULL OR ${field} = '')`);
return;
case 'is_not_empty':
parts.push(`(${field} IS NOT NULL AND ${field} != '')`);
return;
case 'in_list':
sqlOperator = 'IN';
sqlValue = `(${(value as string)?.split(',').map(v => this.formatSQLValue(v.trim())).join(', ')})`;
break;
case 'not_in_list':
sqlOperator = 'NOT IN';
sqlValue = `(${(value as string)?.split(',').map(v => this.formatSQLValue(v.trim())).join(', ')})`;
break;
default:
return;
}
parts.push(`${field} ${sqlOperator} ${sqlValue}`);
});
return parts.join(` ${condition.toUpperCase()} `);
}
private static isGroup(ctrl: AbstractControl): boolean {
return ctrl.get('rules') instanceof FormArray;
}
private static formatSQLValue(val: any): string {
if (val == null || val === '') return 'NULL';
// Handle boolean
if (typeof val === 'boolean') return val ? 'true' : 'false';
// Handle numeric
if (!isNaN(val) && typeof val !== 'object') return String(val);
// Handle dates
const date = new Date(val);
if (!isNaN(date.getTime())) {
return `'${date.toISOString().slice(0, 10)}'`;
}
// Handle strings (with escaped single quotes)
return `'${String(val).replace(/'/g, "''")}'`;
}
}
@@ -76,7 +76,7 @@
outline: 0 none;
color: var(--text-color);
cursor: pointer;
padding: 0.75rem 0.5rem 0.75rem 1rem;
padding: 0.6rem 0.4rem 0.6rem 0.75rem;
border-radius: variables.$borderRadius;
transition: background-color variables.$transitionDuration, box-shadow variables.$transitionDuration;
+12
View File
@@ -15,3 +15,15 @@ html {
.p-toast {
top: 4rem !important;
}
.p-inputchips {
width: 100% !important;
}
.p-inputchips .p-inputchips-input {
width: 100% !important;
}
.p-inputchips input.p-inputtext {
width: 100% !important;
}