diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java index 71ba0c5c9..107bc59ad 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/OpdsController.java @@ -97,6 +97,16 @@ public class OpdsController { .body(feed); } + @Operation(summary = "Get OPDS authors navigation", description = "Retrieve the OPDS authors navigation feed.") + @ApiResponse(responseCode = "200", description = "Authors navigation feed returned successfully") + @GetMapping(value = "/authors", produces = OPDS_CATALOG_MEDIA_TYPE) + public ResponseEntity getAuthorsNavigation(@Parameter(hidden = true) HttpServletRequest request) { + String feed = opdsFeedService.generateAuthorsNavigation(request); + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE)) + .body(feed); + } + @Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.") @ApiResponse(responseCode = "200", description = "Catalog feed returned successfully") @GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookOpdsRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookOpdsRepository.java index fcfb2bca1..12a9cad01 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookOpdsRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookOpdsRepository.java @@ -122,4 +122,52 @@ public interface BookOpdsRepository extends JpaRepository, Jpa @Query(value = "SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false) List findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection libraryIds); + + // ============================================ + // AUTHORS - Distinct Authors List + // ============================================ + + @Query(""" + SELECT DISTINCT a FROM AuthorEntity a + JOIN a.bookMetadataEntityList m + JOIN m.book b + WHERE (b.deleted IS NULL OR b.deleted = false) + ORDER BY a.name + """) + List findDistinctAuthors(); + + @Query(""" + SELECT DISTINCT a FROM AuthorEntity a + JOIN a.bookMetadataEntityList m + JOIN m.book b + WHERE (b.deleted IS NULL OR b.deleted = false) + AND b.library.id IN :libraryIds + ORDER BY a.name + """) + List findDistinctAuthorsByLibraryIds(@Param("libraryIds") Collection libraryIds); + + // ============================================ + // BOOKS BY AUTHOR - Two Query Pattern + // ============================================ + + @Query(""" + SELECT DISTINCT b.id FROM BookEntity b + JOIN b.metadata m + JOIN m.authors a + WHERE a.name = :authorName + AND (b.deleted IS NULL OR b.deleted = false) + ORDER BY b.addedOn DESC + """) + Page findBookIdsByAuthorName(@Param("authorName") String authorName, Pageable pageable); + + @Query(""" + SELECT DISTINCT b.id FROM BookEntity b + JOIN b.metadata m + JOIN m.authors a + WHERE a.name = :authorName + AND b.library.id IN :libraryIds + AND (b.deleted IS NULL OR b.deleted = false) + ORDER BY b.addedOn DESC + """) + Page findBookIdsByAuthorNameAndLibraryIds(@Param("authorName") String authorName, @Param("libraryIds") Collection libraryIds, Pageable pageable); } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsBookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsBookService.java index 127edbc25..99246b614 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsBookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsBookService.java @@ -157,6 +157,68 @@ public class OpdsBookService { return books.stream().map(bookMapper::toBook).toList(); } + public List getDistinctAuthors(Long userId) { + if (userId == null) { + return List.of(); + } + + BookLoreUserEntity entity = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + + List authors; + + if (user.getPermissions().isAdmin()) { + authors = bookOpdsRepository.findDistinctAuthors(); + } else { + Set libraryIds = user.getAssignedLibraries().stream() + .map(Library::getId) + .collect(Collectors.toSet()); + authors = bookOpdsRepository.findDistinctAuthorsByLibraryIds(libraryIds); + } + + return authors.stream() + .map(com.adityachandel.booklore.model.entity.AuthorEntity::getName) + .filter(Objects::nonNull) + .distinct() + .sorted() + .toList(); + } + + public Page getBooksByAuthorName(Long userId, String authorName, int page, int size) { + if (userId == null) { + throw ApiError.FORBIDDEN.createException("Authentication required"); + } + + BookLoreUserEntity entity = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + BookLoreUser user = bookLoreUserTransformer.toDTO(entity); + + Pageable pageable = PageRequest.of(Math.max(page, 0), size); + + if (user.getPermissions().isAdmin()) { + Page idPage = bookOpdsRepository.findBookIdsByAuthorName(authorName, pageable); + if (idPage.isEmpty()) { + return new PageImpl<>(List.of(), pageable, 0); + } + List books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent()); + return createPageFromEntities(books, idPage, pageable); + } + + Set libraryIds = user.getAssignedLibraries().stream() + .map(Library::getId) + .collect(Collectors.toSet()); + + Page idPage = bookOpdsRepository.findBookIdsByAuthorNameAndLibraryIds(authorName, libraryIds, pageable); + if (idPage.isEmpty()) { + return new PageImpl<>(List.of(), pageable, 0); + } + + List books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds); + Page booksPage = createPageFromEntities(books, idPage, pageable); + return applyBookFilters(booksPage, userId); + } + private Page getAllBooksPageInternal(int page, int size) { Pageable pageable = PageRequest.of(Math.max(page, 0), size); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java index 0c5a15a95..80f2ed43e 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/opds/OpdsFeedService.java @@ -90,6 +90,16 @@ public class OpdsFeedService { """.formatted(now())); + feed.append(""" + + Authors + urn:booklore:navigation:authors + %s + + Browse books by author + + """.formatted(now())); + feed.append(""" Surprise Me @@ -223,11 +233,49 @@ public class OpdsFeedService { return feed.toString(); } + public String generateAuthorsNavigation(HttpServletRequest request) { + Long userId = getUserId(); + List authors = opdsBookService.getDistinctAuthors(userId); + + var feed = new StringBuilder(""" + + + urn:booklore:navigation:authors + Authors + %s + + + + """.formatted(now())); + + for (String author : authors) { + feed.append(""" + + %s + urn:booklore:author:%s + %s + + Books by %s + + """.formatted( + escapeXml(author), + escapeXml(author), + now(), + escapeXml("/api/v1/opds/catalog?author=" + java.net.URLEncoder.encode(author, java.nio.charset.StandardCharsets.UTF_8)), + escapeXml(author) + )); + } + + feed.append(""); + return feed.toString(); + } + public String generateCatalogFeed(HttpServletRequest request) { Long libraryId = parseLongParam(request, "libraryId", null); Long shelfId = parseLongParam(request, "shelfId", null); Long magicShelfId = parseLongParam(request, "magicShelfId", null); String query = request.getParameter("q"); + String author = request.getParameter("author"); int page = Math.max(1, parseLongParam(request, "page", 1L).intValue()); int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE); @@ -236,12 +284,14 @@ public class OpdsFeedService { if (magicShelfId != null) { booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, page - 1, size); + } else if (author != null && !author.isBlank()) { + booksPage = opdsBookService.getBooksByAuthorName(userId, author, page - 1, size); } else { booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfId, page - 1, size); } - String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId); - String feedId = determineFeedId(libraryId, shelfId, magicShelfId); + String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId, author); + String feedId = determineFeedId(libraryId, shelfId, magicShelfId, author); var feed = new StringBuilder(""" @@ -427,6 +477,15 @@ public class OpdsFeedService { if (meta.getIsbn10() != null) { feed.append(" urn:isbn:").append(escapeXml(meta.getIsbn10())).append("\n"); } + // Series metadata + if (meta.getSeriesName() != null) { + feed.append(" ") + .append(escapeXml(meta.getSeriesName())).append("\n"); + if (meta.getSeriesNumber() != null) { + feed.append(" ") + .append(meta.getSeriesNumber()).append("\n"); + } + } } private void appendLinks(StringBuilder feed, Book book) { @@ -443,7 +502,7 @@ public class OpdsFeedService { } } - private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId) { + private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId, String author) { if (magicShelfId != null) { return magicShelfBookService.getMagicShelfName(magicShelfId); } @@ -453,10 +512,13 @@ public class OpdsFeedService { if (libraryId != null) { return opdsBookService.getLibraryName(libraryId); } + if (author != null && !author.isBlank()) { + return "Books by " + author; + } return "Booklore Catalog"; } - private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId) { + private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId, String author) { if (magicShelfId != null) { return "urn:booklore:magic-shelf:" + magicShelfId; } @@ -466,6 +528,9 @@ public class OpdsFeedService { if (libraryId != null) { return "urn:booklore:library:" + libraryId; } + if (author != null && !author.isBlank()) { + return "urn:booklore:author:" + author; + } return "urn:booklore:catalog"; }