Switch to Entity Graph
This commit is contained in:
+11
-11
@@ -6,7 +6,7 @@ import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
|
||||
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -24,53 +24,53 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
public class BookController {
|
||||
|
||||
private final BooksService booksService;
|
||||
private final BookService bookService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
|
||||
@GetMapping
|
||||
public ResponseEntity<List<Book>> getBooks(@RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
return ResponseEntity.ok(booksService.getBooks(withDescription));
|
||||
return ResponseEntity.ok(bookService.getBookDTOs(withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}")
|
||||
public ResponseEntity<Book> getBook(@PathVariable long bookId, @RequestParam(required = false, defaultValue = "false") boolean withDescription) {
|
||||
return ResponseEntity.ok(booksService.getBook(bookId, withDescription));
|
||||
return ResponseEntity.ok(bookService.getBook(bookId, withDescription));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(booksService.getBookCover(bookId));
|
||||
return ResponseEntity.ok(bookService.getBookCover(bookId));
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/content")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@PathVariable long bookId) throws IOException {
|
||||
return booksService.getBookContent(bookId);
|
||||
return bookService.getBookContent(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return booksService.downloadBook(bookId);
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/viewer-setting")
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@PathVariable long bookId) {
|
||||
return ResponseEntity.ok(booksService.getBookViewerSetting(bookId));
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
|
||||
}
|
||||
|
||||
@PutMapping("/{bookId}/viewer-setting")
|
||||
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettings bookViewerSettings, @PathVariable long bookId) {
|
||||
booksService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||
bookService.updateBookViewerSetting(bookId, bookViewerSettings);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PostMapping("/shelves")
|
||||
public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) {
|
||||
return ResponseEntity.ok(booksService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
|
||||
return ResponseEntity.ok(bookService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
|
||||
}
|
||||
|
||||
@PostMapping("/progress")
|
||||
public ResponseEntity<Void> addBookToProgress(@RequestBody @Valid ReadProgressRequest request) {
|
||||
booksService.updateReadProgress(request);
|
||||
bookService.updateReadProgress(request);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.BooksService;
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.opds.OpdsService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -19,7 +19,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class OpdsController {
|
||||
|
||||
private final OpdsService opdsService;
|
||||
private final BooksService booksService;
|
||||
private final BookService bookService;
|
||||
|
||||
@GetMapping(value = "/catalog", produces = "application/atom+xml;profile=opds-catalog")
|
||||
public ResponseEntity<String> getCatalogFeed(HttpServletRequest request) {
|
||||
@@ -31,12 +31,12 @@ public class OpdsController {
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return booksService.downloadBook(bookId);
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover.jpg")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = booksService.getBookCover(bookId);
|
||||
Resource coverImage = bookService.getBookCover(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.controller;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.Sort;
|
||||
import com.adityachandel.booklore.service.ShelfService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
+6
-5
@@ -9,9 +9,10 @@ import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Converter
|
||||
public class BookRecommendationIdsListConverter implements AttributeConverter<List<BookRecommendationLite>, String> {
|
||||
public class BookRecommendationIdsListConverter implements AttributeConverter<Set<BookRecommendationLite>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@@ -20,7 +21,7 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Li
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(List<BookRecommendationLite> recommendations) {
|
||||
public String convertToDatabaseColumn(Set<BookRecommendationLite> recommendations) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(recommendations);
|
||||
} catch (JsonProcessingException e) {
|
||||
@@ -29,12 +30,12 @@ public class BookRecommendationIdsListConverter implements AttributeConverter<Li
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookRecommendationLite> convertToEntityAttribute(String json) {
|
||||
public Set<BookRecommendationLite> convertToEntityAttribute(String json) {
|
||||
if (json == null || json.trim().isEmpty()) {
|
||||
return List.of();
|
||||
return Set.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<List<BookRecommendationLite>>() {
|
||||
return objectMapper.readValue(json, new TypeReference<Set<BookRecommendationLite>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Error converting JSON to BookRecommendation list", e);
|
||||
|
||||
@@ -8,7 +8,7 @@ import org.mapstruct.Context;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = {BookMetadataMapper.class, ShelfMapper.class})
|
||||
@@ -29,21 +29,21 @@ public interface BookMapper {
|
||||
@Mapping(target = "shelves", ignore = true)
|
||||
Book toBookWithoutMetadataAndShelves(BookEntity bookEntity);
|
||||
|
||||
default List<String> mapAuthors(List<AuthorEntity> authors) {
|
||||
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
|
||||
if (authors == null) {
|
||||
return null;
|
||||
}
|
||||
return authors.stream()
|
||||
.map(AuthorEntity::getName)
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
default List<String> mapCategories(List<CategoryEntity> categories) {
|
||||
default Set<String> mapCategories(Set<CategoryEntity> categories) {
|
||||
if (categories == null) {
|
||||
return null;
|
||||
}
|
||||
return categories.stream()
|
||||
.map(CategoryEntity::getName)
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.adityachandel.booklore.mapperv2;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import org.mapstruct.*;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface BookMapperV2 {
|
||||
|
||||
@Mapping(source = "library.id", target = "libraryId")
|
||||
@Mapping(target = "metadata", qualifiedByName = "mapMetadata")
|
||||
Book toDTO(BookEntity bookEntity);
|
||||
|
||||
@Named("mapMetadata")
|
||||
@Mapping(target = "authors", source = "authors", qualifiedByName = "mapAuthors")
|
||||
@Mapping(target = "categories", source = "categories", qualifiedByName = "mapCategories")
|
||||
BookMetadata mapMetadata(BookMetadataEntity metadataEntity);
|
||||
|
||||
@Named("mapAuthors")
|
||||
default Set<String> mapAuthors(Set<AuthorEntity> authors) {
|
||||
return authors == null ? Set.of() :
|
||||
authors.stream().map(AuthorEntity::getName).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Named("mapCategories")
|
||||
default Set<String> mapCategories(Set<CategoryEntity> categories) {
|
||||
return categories == null ? Set.of() :
|
||||
categories.stream().map(CategoryEntity::getName).collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
@@ -25,5 +25,5 @@ public class Book {
|
||||
private PdfProgress pdfProgress;
|
||||
private EpubProgress epubProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private List<Shelf> shelves;
|
||||
private Set<Shelf> shelves;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import lombok.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -45,8 +46,8 @@ public class BookMetadata {
|
||||
private String googleId;
|
||||
|
||||
private Instant coverUpdatedOn;
|
||||
private List<String> authors;
|
||||
private List<String> categories;
|
||||
private Set<String> authors;
|
||||
private Set<String> categories;
|
||||
|
||||
private MetadataProvider provider;
|
||||
private String thumbnailUrl;
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.dto.response;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -18,7 +19,7 @@ public class GoogleBooksApiResponse {
|
||||
public static class VolumeInfo {
|
||||
private String title;
|
||||
private String subtitle;
|
||||
private List<String> authors;
|
||||
private Set<String> authors;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String description;
|
||||
@@ -26,7 +27,7 @@ public class GoogleBooksApiResponse {
|
||||
private Integer pageCount;
|
||||
private ImageLinks imageLinks;
|
||||
private String language;
|
||||
private List<String> categories;
|
||||
private Set<String> categories;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@@ -56,11 +57,11 @@ public class BookEntity {
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "shelf_id")
|
||||
)
|
||||
private List<ShelfEntity> shelves;
|
||||
private Set<ShelfEntity> shelves;
|
||||
|
||||
@Convert(converter = BookRecommendationIdsListConverter.class)
|
||||
@Column(name = "similar_books_json", columnDefinition = "TEXT")
|
||||
private List<BookRecommendationLite> similarBooksJson;
|
||||
private Set<BookRecommendationLite> similarBooksJson;
|
||||
|
||||
public Path getFullFilePath() {
|
||||
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
||||
|
||||
+7
-2
@@ -3,10 +3,13 @@ package com.adityachandel.booklore.model.entity;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
import org.hibernate.annotations.Fetch;
|
||||
import org.hibernate.annotations.FetchMode;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@@ -190,7 +193,8 @@ public class BookMetadataEntity {
|
||||
name = "book_metadata_author_mapping",
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "author_id"))
|
||||
private List<AuthorEntity> authors;
|
||||
@Fetch(FetchMode.SUBSELECT)
|
||||
private Set<AuthorEntity> authors;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
@@ -198,7 +202,8 @@ public class BookMetadataEntity {
|
||||
joinColumns = @JoinColumn(name = "book_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "category_id")
|
||||
)
|
||||
private List<CategoryEntity> categories;
|
||||
@Fetch(FetchMode.SUBSELECT)
|
||||
private Set<CategoryEntity> categories;
|
||||
|
||||
public void applyLockToAllFields(boolean lock) {
|
||||
this.titleLocked = lock;
|
||||
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.model.websocket;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
+9
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
@@ -10,9 +11,17 @@ import java.util.Set;
|
||||
|
||||
public interface BookMetadataRepository extends JpaRepository<BookMetadataEntity, Long> {
|
||||
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> findAllByBookIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> getMetadataForBookIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@Query("SELECT m FROM BookMetadataEntity m WHERE m.bookId IN :bookIds")
|
||||
List<BookMetadataEntity> getMetadataForBookIds(@Param("bookIds") List<Long> bookIds);
|
||||
|
||||
|
||||
@EntityGraph(attributePaths = {"authors", "categories"})
|
||||
List<BookMetadataEntity> findAllByBookIdIn(Set<Long> bookIds);
|
||||
}
|
||||
|
||||
+28
-17
@@ -1,10 +1,7 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.jpa.repository.*;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@@ -16,16 +13,6 @@ import java.util.Set;
|
||||
@Repository
|
||||
public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
|
||||
|
||||
@Query("SELECT b FROM BookEntity b")
|
||||
List<BookEntity> getAllBooks();
|
||||
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id IN :libraryIds")
|
||||
List<BookEntity> getAllByLibraryIds(@Param("libraryIds") Set<Long> libraryIds);
|
||||
|
||||
List<BookEntity> findAllByIdIn(Collection<Long> ids);
|
||||
|
||||
List<BookEntity> findBooksByLibraryId(Long libraryId);
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.libraryPath.id IN :libraryPathIds")
|
||||
List<Long> findAllBookIdsByLibraryPathIdIn(@Param("libraryPathIds") Collection<Long> libraryPathIds);
|
||||
|
||||
@@ -33,13 +20,37 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
|
||||
Optional<BookEntity> findBookByFileNameAndLibraryId(String fileName, long libraryId);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||
List<BookEntity> findByShelfId(@Param("shelfId") Long shelfId);
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||
List<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)")
|
||||
void deleteByIdIn(Collection<Long> ids);
|
||||
|
||||
List<BookEntity> findByFileSizeKbIsNull();
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.fileSizeKb IS NULL")
|
||||
List<BookEntity> findAllWithMetadataByFileSizeKbIsNull();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b")
|
||||
List<BookEntity> findAllWithMetadata();
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :bookIds")
|
||||
List<BookEntity> findAllWithMetadataByIds(@Param("bookIds") Set<Long> bookIds);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.library.id = :libraryId")
|
||||
List<BookEntity> findAllWithMetadataByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN FETCH b.metadata m
|
||||
LEFT JOIN FETCH m.authors
|
||||
LEFT JOIN FETCH m.categories
|
||||
LEFT JOIN FETCH b.shelves
|
||||
""")
|
||||
List<BookEntity> findAllFullBooks();
|
||||
}
|
||||
|
||||
|
||||
+3
-6
@@ -12,10 +12,7 @@ import org.springframework.stereotype.Service;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -45,7 +42,7 @@ public class BookCreatorService {
|
||||
|
||||
public void addCategoriesToBook(List<String> categories, BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getCategories() == null) {
|
||||
bookEntity.getMetadata().setCategories(new ArrayList<>());
|
||||
bookEntity.getMetadata().setCategories(new HashSet<>());
|
||||
}
|
||||
categories.stream()
|
||||
.map(cat -> truncate(cat, 255))
|
||||
@@ -56,7 +53,7 @@ public class BookCreatorService {
|
||||
|
||||
public void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getAuthors() == null) {
|
||||
bookEntity.getMetadata().setAuthors(new ArrayList<>());
|
||||
bookEntity.getMetadata().setAuthors(new HashSet<>());
|
||||
}
|
||||
authors.stream()
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.mapperv2.BookMapperV2;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class BookQueryService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapperV2 bookMapperV2;
|
||||
|
||||
public List<Book> getAllBooks(boolean includeDescription) {
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadata();
|
||||
return books.stream()
|
||||
.map(book -> {
|
||||
Book dto = bookMapperV2.toDTO(book);
|
||||
if (!includeDescription && dto.getMetadata() != null) {
|
||||
dto.getMetadata().setDescription(null);
|
||||
}
|
||||
return dto;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
|
||||
return bookRepository.findAllWithMetadataByIds(bookIds);
|
||||
}
|
||||
|
||||
public List<BookEntity> getAllFullBookEntities() {
|
||||
return bookRepository.findAllFullBooks();
|
||||
}
|
||||
|
||||
public void saveAll(List<BookEntity> books) {
|
||||
bookRepository.saveAll(books);
|
||||
}
|
||||
}
|
||||
+36
-138
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.*;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
@@ -35,10 +35,9 @@ import java.util.stream.Collectors;
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BooksService {
|
||||
public class BookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@@ -49,15 +48,39 @@ public class BooksService {
|
||||
private final UserRepository userRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final BookMetadataAuthorMappingRepository bookMetadataAuthorMappingRepository;
|
||||
private final BookMetadataCategoryMappingRepository bookMetadataCategoryMappingRepository;
|
||||
private final BookShelfMappingRepository bookShelfMappingRepository;
|
||||
private final BookMetadataMapper bookMetadataMapper;
|
||||
private final AuthorMapper authorMapper;
|
||||
private final CategoryMapper categoryMapper;
|
||||
private final ShelfMapper shelfMapper;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
|
||||
public List<Book> getBookDTOs(boolean includeDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
List<Book> books = bookQueryService.getAllBooks(includeDescription);
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(user.getId(), books.stream().map(Book::getId).collect(Collectors.toSet()));
|
||||
books.forEach(book -> {
|
||||
UserBookProgressEntity progress = progressMap.get(book.getId());
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
}
|
||||
});
|
||||
return books;
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
@@ -208,131 +231,6 @@ public class BooksService {
|
||||
return book;
|
||||
}
|
||||
|
||||
public List<Book> getBooks(boolean withDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> bookIds;
|
||||
List<BookEntity> bookEntities = user.getPermissions().isAdmin()
|
||||
? bookRepository.getAllBooks()
|
||||
: bookRepository.getAllByLibraryIds(
|
||||
user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet())
|
||||
);
|
||||
|
||||
List<Book> books = bookEntities.stream()
|
||||
.map(bookMapper::toBookWithoutMetadataAndShelves)
|
||||
.toList();
|
||||
|
||||
bookIds = bookEntities.stream()
|
||||
.map(BookEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, BookMetadata> metadataByBookId = fetchMetadata(bookIds, withDescription);
|
||||
Map<Long, List<String>> authorsByBookId = fetchAuthors(bookIds);
|
||||
Map<Long, List<String>> categoriesByBookId = fetchCategories(bookIds);
|
||||
Map<Long, List<Shelf>> shelvesByBookId = fetchShelves(bookIds);
|
||||
Map<Long, UserBookProgressEntity> progressByBookId = fetchUserProgress(user.getId(), bookIds);
|
||||
|
||||
for (Book book : books) {
|
||||
Long bookId = book.getId();
|
||||
|
||||
var metadata = metadataByBookId.get(bookId);
|
||||
if (metadata != null) {
|
||||
metadata.setAuthors(authorsByBookId.getOrDefault(bookId, List.of()));
|
||||
metadata.setCategories(categoriesByBookId.getOrDefault(bookId, List.of()));
|
||||
book.setMetadata(metadata);
|
||||
}
|
||||
|
||||
book.setShelves(shelvesByBookId.getOrDefault(bookId, List.of()));
|
||||
|
||||
var progress = progressByBookId.get(bookId);
|
||||
if (progress != null) {
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
setBookProgress(book, progress);
|
||||
}
|
||||
}
|
||||
|
||||
return books;
|
||||
}
|
||||
|
||||
private Map<Long, BookMetadata> fetchMetadata(Set<Long> bookIds, boolean withDescription) {
|
||||
var metadataList = bookMetadataRepository.getMetadataForBookIds(bookIds);
|
||||
return metadataList.stream()
|
||||
.map(m -> bookMetadataMapper.toBookMetadataWithoutRelations(m, withDescription))
|
||||
.collect(Collectors.toMap(BookMetadata::getBookId, m -> m));
|
||||
}
|
||||
|
||||
private Map<Long, List<String>> fetchAuthors(Set<Long> bookIds) {
|
||||
var mappings = bookMetadataAuthorMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var authorIds = mappings.stream()
|
||||
.map(BookMetadataAuthorMapping::getAuthorId)
|
||||
.collect(Collectors.toSet());
|
||||
var authors = authorRepository.findAllByIdIn(authorIds);
|
||||
var authorNamesById = authors.stream()
|
||||
.collect(Collectors.toMap(AuthorEntity::getId, authorMapper::toAuthorEntityName));
|
||||
|
||||
return mappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookMetadataAuthorMapping::getBookId,
|
||||
Collectors.mapping(m -> authorNamesById.get(m.getAuthorId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, List<String>> fetchCategories(Set<Long> bookIds) {
|
||||
var mappings = bookMetadataCategoryMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var categoryIds = mappings.stream()
|
||||
.map(BookMetadataCategoryMapping::getCategoryId)
|
||||
.collect(Collectors.toSet());
|
||||
var categories = categoryRepository.findAllByIdIn(categoryIds);
|
||||
var categoryNamesById = categories.stream()
|
||||
.collect(Collectors.toMap(CategoryEntity::getId, categoryMapper::toCategoryName));
|
||||
|
||||
return mappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookMetadataCategoryMapping::getBookId,
|
||||
Collectors.mapping(m -> categoryNamesById.get(m.getCategoryId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, List<Shelf>> fetchShelves(Set<Long> bookIds) {
|
||||
var shelfMappings = bookShelfMappingRepository.findAllByBookIdIn(bookIds);
|
||||
var shelfIds = shelfMappings.stream()
|
||||
.map(BookShelfMapping::getShelfId)
|
||||
.collect(Collectors.toSet());
|
||||
var shelves = shelfRepository.findAllByIdIn(shelfIds);
|
||||
var shelfById = shelves.stream()
|
||||
.collect(Collectors.toMap(ShelfEntity::getId, shelfMapper::toShelf));
|
||||
|
||||
return shelfMappings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
BookShelfMapping::getBookId,
|
||||
Collectors.mapping(m -> shelfById.get(m.getShelfId()), Collectors.toList())
|
||||
));
|
||||
}
|
||||
|
||||
private Map<Long, UserBookProgressEntity> fetchUserProgress(Long userId, Set<Long> bookIds) {
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(p -> p.getBook().getId(), p -> p));
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
@@ -350,7 +248,7 @@ public class BooksService {
|
||||
throw ApiError.UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
|
||||
}
|
||||
|
||||
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
@@ -8,7 +8,6 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
@@ -69,7 +68,7 @@ public class ShelfService {
|
||||
|
||||
public List<Book> getShelfBooks(Long shelfId) {
|
||||
findShelfByIdOrThrow(shelfId);
|
||||
return bookRepository.findByShelfId(shelfId).stream()
|
||||
return bookRepository.findAllWithMetadataByShelfId(shelfId).stream()
|
||||
.map(bookMapper::toBook)
|
||||
.toList();
|
||||
}
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class UserProgressService {
|
||||
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
|
||||
public Map<Long, UserBookProgressEntity> fetchUserProgress(Long userId, Set<Long> bookIds) {
|
||||
return userBookProgressRepository.findByUserIdAndBookIdIn(userId, bookIds).stream()
|
||||
.collect(Collectors.toMap(p -> p.getBook().getId(), p -> p));
|
||||
}
|
||||
}
|
||||
-1
@@ -26,7 +26,6 @@ import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
|
||||
+1
-1
@@ -22,6 +22,7 @@ import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
@@ -31,7 +32,6 @@ import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
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.entity.BookMetadataEntity;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
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
-1
@@ -1,8 +1,8 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
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;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
|
||||
+1
-1
@@ -228,7 +228,7 @@ public class LibraryService {
|
||||
|
||||
public List<Book> getBooks(long libraryId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
List<BookEntity> bookEntities = bookRepository.findBooksByLibraryId(libraryId);
|
||||
List<BookEntity> bookEntities = bookRepository.findAllWithMetadataByLibraryId(libraryId);
|
||||
return bookEntities.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
}
|
||||
+17
-17
@@ -25,6 +25,7 @@ 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.metadata.parser.BookParser;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -32,13 +33,11 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
@@ -61,6 +60,7 @@ public class BookMetadataService {
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -264,58 +264,58 @@ public class BookMetadataService {
|
||||
return value;
|
||||
}
|
||||
|
||||
List<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> uniqueCategories = new HashSet<>();
|
||||
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP3() != null && metadataMap.containsKey(fieldProvider.getP3())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP2() != null && metadataMap.containsKey(fieldProvider.getP2())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP1() != null && metadataMap.containsKey(fieldProvider.getP1())) {
|
||||
List<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
Set<String> extracted = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
if (extracted != null) {
|
||||
uniqueCategories.addAll(extracted);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(uniqueCategories);
|
||||
return new HashSet<>(uniqueCategories);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
List<String> values = new ArrayList<>();
|
||||
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> values = new HashSet<>();
|
||||
if (fieldProvider.getP4() != null && metadataMap.containsKey(fieldProvider.getP4())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP4()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (fieldProvider.getP3() != null && metadataMap.containsKey(fieldProvider.getP3())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP3()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (values.isEmpty() && fieldProvider.getP2() != null && metadataMap.containsKey(fieldProvider.getP2())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP2()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
}
|
||||
if (values.isEmpty() && fieldProvider.getP1() != null && metadataMap.containsKey(fieldProvider.getP1())) {
|
||||
List<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
Set<String> newValues = fieldValueExtractor.extract(metadataMap.get(fieldProvider.getP1()));
|
||||
if (newValues != null && !newValues.isEmpty()) {
|
||||
values = newValues;
|
||||
}
|
||||
@@ -334,7 +334,7 @@ public class BookMetadataService {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(request.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(request.getLibraryId()));
|
||||
yield libraryEntity.getBookEntities();
|
||||
}
|
||||
case BOOKS -> bookRepository.findAllByIdIn(request.getBookIds());
|
||||
case BOOKS -> bookQueryService.findAllWithMetadataByIds(request.getBookIds());
|
||||
};
|
||||
books.sort(Comparator.comparing(BookEntity::getFileName, Comparator.nullsLast(String::compareTo)));
|
||||
return books;
|
||||
@@ -417,7 +417,7 @@ public class BookMetadataService {
|
||||
@Transactional
|
||||
public List<BookMetadata> toggleAllLock(ToggleAllLockRequest request) {
|
||||
boolean lock = request.getLock() == Lock.LOCK;
|
||||
List<BookEntity> books = bookRepository.findAllByIdIn(request.getBookIds())
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(request.getBookIds())
|
||||
.stream()
|
||||
.peek(book -> book.getMetadata().applyLockToAllFields(lock))
|
||||
.toList();
|
||||
@@ -444,7 +444,7 @@ public class BookMetadataService {
|
||||
|
||||
public void regenerateCovers() {
|
||||
Thread.startVirtualThread(() -> {
|
||||
List<BookEntity> books = bookRepository.findAll().stream()
|
||||
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
.filter(book -> book.getMetadata().getCoverLocked() == null || !book.getMetadata().getCoverLocked())
|
||||
.toList();
|
||||
int total = books.size();
|
||||
|
||||
+3
-3
@@ -85,7 +85,7 @@ public class BookMetadataUpdater {
|
||||
.filter(a -> a != null && !a.isBlank())
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.collect(Collectors.toList()));
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,13 +100,13 @@ public class BookMetadataUpdater {
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build()));
|
||||
existingCategories.add(categoryEntity);
|
||||
});
|
||||
metadata.setCategories(new ArrayList<>(existingCategories));
|
||||
metadata.setCategories(new HashSet<>(existingCategories));
|
||||
} else if (!newMetadata.getCategories().isEmpty()) {
|
||||
metadata.setCategories(newMetadata.getCategories().stream()
|
||||
.filter(c -> c != null && !c.isBlank())
|
||||
.map(categoryName -> categoryRepository.findByName(categoryName)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(categoryName).build())))
|
||||
.collect(Collectors.toList()));
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package com.adityachandel.booklore.service.metadata;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@FunctionalInterface
|
||||
interface FieldValueExtractorList {
|
||||
List<String> extract(BookMetadata metadata);
|
||||
Set<String> extract(BookMetadata metadata);
|
||||
}
|
||||
|
||||
+11
-4
@@ -51,9 +51,16 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
List<BookMetadata> fetchedBookMetadata = new ArrayList<>();
|
||||
for (String amazonBookId : amazonBookIds) {
|
||||
if (amazonBookId == null || amazonBookId.isBlank()) {
|
||||
log.debug("Skipping null or blank Amazon book ID.");
|
||||
continue;
|
||||
}
|
||||
BookMetadata metadata = getBookMetadata(amazonBookId);
|
||||
if (metadata.getTitle() == null || metadata.getTitle().isBlank() ||
|
||||
metadata.getAuthors() == null || metadata.getAuthors().isEmpty()) {
|
||||
if (metadata == null) {
|
||||
log.debug("Skipping null metadata for ID: {}", amazonBookId);
|
||||
continue;
|
||||
}
|
||||
if (metadata.getTitle() == null || metadata.getTitle().isBlank() || metadata.getAuthors() == null || metadata.getAuthors().isEmpty()) {
|
||||
log.debug("Skipping metadata with missing title or author for ID: {}", amazonBookId);
|
||||
continue;
|
||||
}
|
||||
@@ -145,8 +152,8 @@ public class AmazonBookParser implements BookParser {
|
||||
.provider(MetadataProvider.Amazon)
|
||||
.title(getTitle(doc))
|
||||
.subtitle(getSubtitle(doc))
|
||||
.authors(getAuthors(doc).stream().toList())
|
||||
.categories(getBestSellerCategories(doc).stream().toList())
|
||||
.authors(new HashSet<>(getAuthors(doc)))
|
||||
.categories(new HashSet<>(getBestSellerCategories(doc)))
|
||||
.description(cleanDescriptionHtml(getDescription(doc)))
|
||||
.seriesName(getSeriesName(doc))
|
||||
.seriesNumber(getSeriesNumber(doc))
|
||||
|
||||
+6
-6
@@ -99,7 +99,7 @@ public class GoodReadsParser implements BookParser {
|
||||
if (contributorKey != null) {
|
||||
String contributorName = getContributorName(apolloStateJson, contributorKey);
|
||||
if (contributorName != null) {
|
||||
builder.authors(List.of(contributorName));
|
||||
builder.authors(Set.of(contributorName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -255,9 +255,9 @@ public class GoodReadsParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<String> extractGenres(JSONObject bookJson) {
|
||||
private Set<String> extractGenres(JSONObject bookJson) {
|
||||
try {
|
||||
List<String> genres = new ArrayList<>();
|
||||
Set<String> genres = new HashSet<>();
|
||||
JSONArray bookGenresJsonArray = bookJson.getJSONArray("bookGenres");
|
||||
for (int i = 0; i < bookGenresJsonArray.length(); i++) {
|
||||
JSONObject genreJson = bookGenresJsonArray.getJSONObject(i).getJSONObject("genre");
|
||||
@@ -314,7 +314,7 @@ public class GoodReadsParser implements BookParser {
|
||||
FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH);
|
||||
String queryAuthor = request.getAuthor();
|
||||
for (Element previewBook : previewBooks) {
|
||||
List<String> authors = extractAuthorsPreview(previewBook);
|
||||
Set<String> authors = extractAuthorsPreview(previewBook);
|
||||
if (queryAuthor != null && !queryAuthor.isBlank()) {
|
||||
List<String> queryAuthorTokens = List.of(queryAuthor.toLowerCase().split("\\s+"));
|
||||
boolean matches = authors.stream().flatMap(a -> Arrays.stream(a.toLowerCase().split("\\s+"))).anyMatch(actual -> {
|
||||
@@ -371,8 +371,8 @@ public class GoodReadsParser implements BookParser {
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<String> extractAuthorsPreview(Element book) {
|
||||
List<String> authors = new ArrayList<>();
|
||||
private Set<String> extractAuthorsPreview(Element book) {
|
||||
Set<String> authors = new HashSet<>();
|
||||
try {
|
||||
Elements authorsElement = book.select("a.authorName");
|
||||
for (Element authorElement : authorsElement) {
|
||||
|
||||
+3
-2
@@ -22,6 +22,7 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@@ -94,8 +95,8 @@ public class GoogleParser implements BookParser {
|
||||
.publisher(volumeInfo.getPublisher())
|
||||
.publishedDate(parseDate(volumeInfo.getPublishedDate()))
|
||||
.description(volumeInfo.getDescription())
|
||||
.authors(Optional.ofNullable(volumeInfo.getAuthors()).orElse(List.of()))
|
||||
.categories(Optional.ofNullable(volumeInfo.getCategories()).orElse(List.of()))
|
||||
.authors(Optional.ofNullable(volumeInfo.getAuthors()).orElse(Set.of()))
|
||||
.categories(Optional.ofNullable(volumeInfo.getCategories()).orElse(Set.of()))
|
||||
.isbn13(isbns.get("ISBN_13"))
|
||||
.isbn10(isbns.get("ISBN_10"))
|
||||
.pageCount(volumeInfo.getPageCount())
|
||||
|
||||
+3
-2
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -43,7 +44,7 @@ public class GraphQLResponse {
|
||||
private String title;
|
||||
|
||||
@JsonProperty("author_names")
|
||||
private List<String> authorNames;
|
||||
private Set<String> authorNames;
|
||||
|
||||
private String description;
|
||||
private List<String> isbns;
|
||||
@@ -57,7 +58,7 @@ public class GraphQLResponse {
|
||||
@JsonProperty("release_date")
|
||||
private String releaseDate;
|
||||
|
||||
private List<String> genres;
|
||||
private Set<String> genres;
|
||||
|
||||
@JsonProperty("featured_series")
|
||||
private FeaturedSeries featuredSeries;
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class AppMigrationService {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookRepository.findByFileSizeKbIsNull();
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadataByFileSizeKbIsNull();
|
||||
for (BookEntity book : books) {
|
||||
Long sizeInKb = FileUtils.getFileSizeInKb(book);
|
||||
if (sizeInKb != null) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -15,10 +15,10 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
var books = bookRepository.findAll();
|
||||
var books = bookQueryService.getAllFullBookEntities();
|
||||
var feedVersion = extractVersionFromAcceptHeader(request);
|
||||
|
||||
return switch (feedVersion) {
|
||||
|
||||
+6
-5
@@ -2,8 +2,8 @@ package com.adityachandel.booklore.service.recommender;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -11,13 +11,14 @@ import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BookRecommendationScheduler {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final BookRecommendationService recommendationService;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
@@ -33,17 +34,17 @@ public class BookRecommendationScheduler {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("Scheduled task 'updateAllSimilarBooks' started at: {}. Current timestamp: {}", startTime, startTime);
|
||||
|
||||
List<BookEntity> allBooks = bookRepository.findAll();
|
||||
List<BookEntity> allBooks = bookQueryService.getAllFullBookEntities();
|
||||
|
||||
for (BookEntity book : allBooks) {
|
||||
try {
|
||||
List<BookRecommendationLite> recommendations = recommendationService.findSimilarBookIds(book.getId(), RECOMMENDATION_LIMIT);
|
||||
Set<BookRecommendationLite> recommendations = recommendationService.findSimilarBookIds(book.getId(), RECOMMENDATION_LIMIT);
|
||||
book.setSimilarBooksJson(recommendations);
|
||||
} catch (Exception e) {
|
||||
log.error("Error updating similar books for book ID {}: {}", book.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
bookRepository.saveAll(allBooks);
|
||||
bookQueryService.saveAll(allBooks);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("Completed scheduled task 'updateAllSimilarBooks' at: {}. Duration: {} ms", endTime, endTime - startTime);
|
||||
|
||||
+26
-16
@@ -8,7 +8,7 @@ import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.user.UserService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -25,16 +25,16 @@ public class BookRecommendationService {
|
||||
|
||||
private final BookSimilarityService similarityService;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final BookMapper bookMapper;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
private static final int MAX_BOOKS_PER_AUTHOR = 3;
|
||||
|
||||
public List<BookRecommendation> getRecommendations(Long bookId, int limit) {
|
||||
BookEntity book = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookEntity book = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookRecommendationLite> recommendations = book.getSimilarBooksJson();
|
||||
Set<BookRecommendationLite> recommendations = book.getSimilarBooksJson();
|
||||
if (recommendations == null || recommendations.isEmpty()) {
|
||||
log.info("Recommendations for book ID {} are missing or empty. Computing similarity...", bookId);
|
||||
recommendations = findSimilarBookIds(bookId, limit);
|
||||
@@ -42,17 +42,27 @@ public class BookRecommendationService {
|
||||
bookRepository.save(book);
|
||||
}
|
||||
|
||||
List<Long> recommendedBookIds = recommendations.stream()
|
||||
Set<Long> recommendedBookIds = recommendations.stream()
|
||||
.map(BookRecommendationLite::getB)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Map<Long, BookEntity> recommendedBooksMap = bookRepository.findAllById(recommendedBookIds).stream()
|
||||
.filter(b -> b.getLibrary() != null && accessibleLibraryIds.contains(b.getLibrary().getId()))
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Set<Long> accessibleLibraryIds;
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
accessibleLibraryIds = null;
|
||||
} else {
|
||||
accessibleLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
Map<Long, BookEntity> recommendedBooksMap = bookQueryService.findAllWithMetadataByIds(recommendedBookIds).stream()
|
||||
.filter(b -> {
|
||||
if (accessibleLibraryIds == null) {
|
||||
return true;
|
||||
}
|
||||
return b.getLibrary() != null && accessibleLibraryIds.contains(b.getLibrary().getId());
|
||||
})
|
||||
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
|
||||
|
||||
return recommendations.stream()
|
||||
@@ -66,20 +76,20 @@ public class BookRecommendationService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
protected List<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) {
|
||||
protected Set<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) {
|
||||
List<BookRecommendation> similarBooks = findSimilarBooks(bookId, limit);
|
||||
if (similarBooks == null || similarBooks.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return similarBooks.stream()
|
||||
.map(b -> new BookRecommendationLite(b.getBook().getId(), b.getSimilarityScore()))
|
||||
.collect(Collectors.toList());
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
protected List<BookRecommendation> findSimilarBooks(Long bookId, int limit) {
|
||||
BookEntity target = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookEntity> candidates = bookRepository.findAll();
|
||||
List<BookEntity> candidates = bookQueryService.getAllFullBookEntities();
|
||||
|
||||
String targetSeriesName = Optional.ofNullable(target.getMetadata())
|
||||
.map(BookMetadataEntity::getSeriesName)
|
||||
|
||||
+4
-4
@@ -58,9 +58,9 @@ public class BookSimilarityService {
|
||||
return round(score, 5);
|
||||
}
|
||||
|
||||
private List<String> extractNames(List<?> entities) {
|
||||
if (entities == null) return Collections.emptyList();
|
||||
List<String> names = new ArrayList<>();
|
||||
private Set<String> extractNames(Set<?> entities) {
|
||||
if (entities == null) return Collections.emptySet();
|
||||
Set<String> names = new HashSet<>();
|
||||
for (Object obj : entities) {
|
||||
if (obj instanceof AuthorEntity author && author.getName() != null) {
|
||||
names.add(author.getName().toLowerCase());
|
||||
@@ -75,7 +75,7 @@ public class BookSimilarityService {
|
||||
return s1 != null && s2 != null && s1.equalsIgnoreCase(s2);
|
||||
}
|
||||
|
||||
private double jaccardSimilarity(List<String> a, List<String> b) {
|
||||
private double jaccardSimilarity(Set<String> a, Set<String> b) {
|
||||
if (a.isEmpty() || b.isEmpty()) return 0.0;
|
||||
Set<String> setA = new HashSet<>(a);
|
||||
Set<String> setB = new HashSet<>(b);
|
||||
|
||||
Reference in New Issue
Block a user