Consolidate OPDS endpoints and implement structured navigation feeds (#1375)
This commit is contained in:
@@ -1,118 +0,0 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.opds.OpdsService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping({"/api/v1/opds", "/api/v2/opds"})
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsController {
|
||||
|
||||
private final OpdsService opdsService;
|
||||
private final BookService bookService;
|
||||
|
||||
@GetMapping(produces = {"application/opds+json"})
|
||||
public ResponseEntity<String> getRootNavigation(HttpServletRequest request) {
|
||||
// Only OPDS 2 navigation is defined for root
|
||||
String nav = opdsService.generateOpdsV2Navigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opds+json;profile=navigation"))
|
||||
.body(nav);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/libraries", produces = {"application/opds+json"})
|
||||
public ResponseEntity<String> getLibrariesNavigation(HttpServletRequest request) {
|
||||
String nav = opdsService.generateOpdsV2LibrariesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opds+json;profile=navigation"))
|
||||
.body(nav);
|
||||
}
|
||||
|
||||
|
||||
@GetMapping(value = "/shelves", produces = {"application/opds+json"})
|
||||
public ResponseEntity<String> getShelvesNavigation(HttpServletRequest request) {
|
||||
String nav = opdsService.generateOpdsV2ShelvesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opds+json;profile=navigation"))
|
||||
.body(nav);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/catalog", produces = {"application/opds+json", "application/atom+xml;profile=opds-catalog"})
|
||||
public ResponseEntity<String> getCatalogFeed(HttpServletRequest request) {
|
||||
String feed = opdsService.generateCatalogFeed(request);
|
||||
MediaType contentType = selectContentType(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(contentType)
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/search", produces = {"application/opds+json", "application/atom+xml;profile=opds-catalog"})
|
||||
public ResponseEntity<String> search(HttpServletRequest request) {
|
||||
String feed = opdsService.generateSearchResults(request, request.getParameter("q"));
|
||||
MediaType contentType = selectContentType(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(contentType)
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/recent", produces = {"application/opds+json"})
|
||||
public ResponseEntity<String> recent(HttpServletRequest request) {
|
||||
String feed = opdsService.generateRecentFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opds+json;profile=acquisition"))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/search.opds", produces = "application/opensearchdescription+xml")
|
||||
public ResponseEntity<String> searchDescription(HttpServletRequest request) {
|
||||
String feed = opdsService.generateSearchDescription(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opensearchdescription+xml"))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + coverImage.getFilename() + "\"")
|
||||
.body(coverImage);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/publications/{bookId}", produces = "application/opds-publication+json")
|
||||
public ResponseEntity<String> getPublication(HttpServletRequest request, @PathVariable long bookId) {
|
||||
String publication = opdsService.generateOpdsV2Publication(request, bookId);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opds-publication+json"))
|
||||
.body(publication);
|
||||
}
|
||||
|
||||
private MediaType selectContentType(HttpServletRequest request) {
|
||||
// Force OPDS 2 JSON when using v2-only filters
|
||||
if (request.getParameter("shelfId") != null || request.getParameter("libraryId") != null) {
|
||||
return MediaType.parseMediaType("application/opds+json;profile=acquisition");
|
||||
}
|
||||
String accept = request.getHeader("Accept");
|
||||
if (accept != null && (accept.contains("application/opds+json") || accept.contains("version=2.0"))) {
|
||||
return MediaType.parseMediaType("application/opds+json;profile=acquisition");
|
||||
}
|
||||
return MediaType.parseMediaType("application/atom+xml;profile=opds-catalog");
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.adityachandel.booklore.controller.opds;
|
||||
|
||||
import com.adityachandel.booklore.service.BookService;
|
||||
import com.adityachandel.booklore.service.opds.OpdsFeedService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/opds")
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsController {
|
||||
|
||||
private static final String OPDS_CATALOG_MEDIA_TYPE = "application/atom+xml;profile=opds-catalog;kind=navigation;charset=utf-8";
|
||||
private static final String OPDS_ACQUISITION_MEDIA_TYPE = "application/atom+xml;profile=opds-catalog;kind=acquisition;charset=utf-8";
|
||||
|
||||
private final OpdsFeedService opdsFeedService;
|
||||
private final BookService bookService;
|
||||
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@PathVariable("bookId") Long bookId) {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@PathVariable long bookId) {
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + coverImage.getFilename() + "\"")
|
||||
.body(coverImage);
|
||||
}
|
||||
|
||||
@GetMapping(produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getRootCatalog(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateRootNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/libraries", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getLibrariesNavigation(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateLibrariesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getShelvesNavigation(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateShelvesNavigation(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getCatalog(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateCatalogFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getRecentBooks(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateRecentFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/surprise", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||
public ResponseEntity<String> getSurpriseFeed(HttpServletRequest request) {
|
||||
String feed = opdsFeedService.generateSurpriseFeed(request);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||
.body(feed);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/search.opds", produces = "application/opensearchdescription+xml")
|
||||
public ResponseEntity<String> getSearchDescription() {
|
||||
String searchDoc = opdsFeedService.getOpenSearchDescription();
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType("application/opensearchdescription+xml;charset=utf-8"))
|
||||
.body(searchDoc);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface BookOpdsRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
|
||||
|
||||
// ============================================
|
||||
// ALL BOOKS - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false)")
|
||||
Page<Long> findBookIds(Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :ids AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadataByIds(@Param("ids") Collection<Long> ids);
|
||||
|
||||
// ============================================
|
||||
// RECENT BOOKS - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
|
||||
Page<Long> findRecentBookIds(Pageable pageable);
|
||||
|
||||
// Uses same findAllWithMetadataByIds for second query
|
||||
|
||||
// ============================================
|
||||
// BOOKS BY LIBRARY IDs - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
Page<Long> findBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
|
||||
@Query("SELECT b FROM BookEntity b WHERE b.id IN :ids AND b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadataByIdsAndLibraryIds(@Param("ids") Collection<Long> ids, @Param("libraryIds") Collection<Long> libraryIds);
|
||||
|
||||
// ============================================
|
||||
// RECENT BOOKS BY LIBRARY IDs - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false) ORDER BY b.addedOn DESC")
|
||||
Page<Long> findRecentBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||
|
||||
// Uses findAllWithMetadataByIdsAndLibraryIds for second query
|
||||
|
||||
// ============================================
|
||||
// BOOKS BY SHELF ID - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("SELECT DISTINCT b.id FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
Page<Long> findBookIdsByShelfId(@Param("shelfId") Long shelfId, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "additionalFiles", "shelves"})
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE b.id IN :ids AND s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithMetadataByIdsAndShelfId(@Param("ids") Collection<Long> ids, @Param("shelfId") Long shelfId);
|
||||
|
||||
// ============================================
|
||||
// SEARCH BY METADATA - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b.id FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
Page<Long> findBookIdsByMetadataSearch(@Param("text") String text, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "metadata.authors", "metadata.categories", "additionalFiles", "shelves"})
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b WHERE b.id IN :ids AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithFullMetadataByIds(@Param("ids") Collection<Long> ids);
|
||||
|
||||
// ============================================
|
||||
// SEARCH BY METADATA IN LIBRARIES - Two Query Pattern
|
||||
// ============================================
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b.id FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
Page<Long> findBookIdsByMetadataSearchAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "metadata.authors", "metadata.categories", "additionalFiles", "shelves"})
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b WHERE b.id IN :ids AND b.library.id IN :libraryIds AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllWithFullMetadataByIdsAndLibraryIds(@Param("ids") Collection<Long> ids, @Param("libraryIds") Collection<Long> libraryIds);
|
||||
|
||||
// ============================================
|
||||
// RANDOM BOOKS - "Surprise Me" Feed
|
||||
// ============================================
|
||||
|
||||
@Query(value = "SELECT b.id FROM BookEntity b WHERE (b.deleted IS NULL OR b.deleted = false) ORDER BY function('RAND')", nativeQuery = false)
|
||||
List<Long> findRandomBookIds();
|
||||
|
||||
@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<Long> findRandomBookIdsByLibraryIds(@Param("libraryIds") Collection<Long> libraryIds);
|
||||
}
|
||||
+34
-65
@@ -71,7 +71,7 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
|
||||
@Query(value = "SELECT DISTINCT b FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)",
|
||||
countQuery = "SELECT COUNT(DISTINCT b.id) FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
countQuery = "SELECT COUNT(DISTINCT b.id) FROM BookEntity b JOIN b.shelves s WHERE s.id = :shelfId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
Page<BookEntity> findAllWithMetadataByShelfId(@Param("shelfId") Long shelfId, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"})
|
||||
@@ -88,21 +88,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
""")
|
||||
List<BookEntity> findAllFullBooks();
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN FETCH b.metadata m
|
||||
LEFT JOIN FETCH m.authors a
|
||||
LEFT JOIN FETCH m.categories
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
ORDER BY m.title ASC
|
||||
""")
|
||||
List<BookEntity> searchByMetadata(@Param("text") String text);
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
@@ -115,58 +100,42 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
)
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false) AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.subtitle) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
Page<BookEntity> searchByMetadata(@Param("text") String text, Pageable pageable);
|
||||
|
||||
@Query("""
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN FETCH b.metadata m
|
||||
LEFT JOIN FETCH m.authors a
|
||||
LEFT JOIN FETCH m.categories
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
ORDER BY m.title ASC
|
||||
""")
|
||||
List<BookEntity> searchByMetadataAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds);
|
||||
|
||||
@Query(value = """
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
SELECT DISTINCT b FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""",
|
||||
countQuery = """
|
||||
SELECT COUNT(DISTINCT b.id) FROM BookEntity b
|
||||
LEFT JOIN b.metadata m
|
||||
LEFT JOIN m.authors a
|
||||
WHERE (b.deleted IS NULL OR b.deleted = false)
|
||||
AND b.library.id IN :libraryIds
|
||||
AND (
|
||||
LOWER(m.title) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(m.seriesName) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
OR LOWER(a.name) LIKE LOWER(CONCAT('%', :text, '%'))
|
||||
)
|
||||
""")
|
||||
Page<BookEntity> searchByMetadataAndLibraryIds(@Param("text") String text, @Param("libraryIds") Collection<Long> libraryIds, Pageable pageable);
|
||||
|
||||
@Modifying
|
||||
|
||||
+9
-53
@@ -5,14 +5,9 @@ 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.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Sort;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -35,29 +30,11 @@ public class BookQueryService {
|
||||
return createPageFromBooks(books, pageable, includeDescription, null);
|
||||
}
|
||||
|
||||
public Page<Book> getRecentBooksPage(boolean includeDescription, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size, Sort.by("addedOn").descending());
|
||||
Page<BookEntity> books = bookRepository.findAllWithMetadata(pageable);
|
||||
return createPageFromBooks(books, pageable, includeDescription, null);
|
||||
}
|
||||
|
||||
public List<Book> getAllBooksByLibraryIds(Set<Long> libraryIds, boolean includeDescription, Long userId) {
|
||||
List<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds);
|
||||
return mapBooksToDto(books, includeDescription, userId);
|
||||
}
|
||||
|
||||
public Page<Book> getAllBooksByLibraryIdsPage(Set<Long> libraryIds, boolean includeDescription, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
|
||||
Page<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds, pageable);
|
||||
return createPageFromBooks(books, pageable, includeDescription, userId);
|
||||
}
|
||||
|
||||
public Page<Book> getRecentBooksByLibraryIdsPage(Set<Long> libraryIds, boolean includeDescription, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size, Sort.by("addedOn").descending());
|
||||
Page<BookEntity> books = bookRepository.findAllWithMetadataByLibraryIds(libraryIds, pageable);
|
||||
return createPageFromBooks(books, pageable, includeDescription, userId);
|
||||
}
|
||||
|
||||
public List<BookEntity> findAllWithMetadataByIds(Set<Long> bookIds) {
|
||||
return bookRepository.findAllWithMetadataByIds(bookIds);
|
||||
}
|
||||
@@ -71,13 +48,6 @@ public class BookQueryService {
|
||||
return bookRepository.findAllFullBooks();
|
||||
}
|
||||
|
||||
public List<Book> searchBooksByMetadata(String text) {
|
||||
List<BookEntity> bookEntities = bookRepository.searchByMetadata(text);
|
||||
return bookEntities.stream()
|
||||
.map(bookMapperV2::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public Page<Book> searchBooksByMetadataPage(String text, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
|
||||
Page<BookEntity> books = bookRepository.searchByMetadata(text, pageable);
|
||||
@@ -87,32 +57,18 @@ public class BookQueryService {
|
||||
return new PageImpl<>(mapped, pageable, books.getTotalElements());
|
||||
}
|
||||
|
||||
public List<Book> searchBooksByMetadataInLibraries(String text, Set<Long> libraryIds) {
|
||||
List<BookEntity> bookEntities = bookRepository.searchByMetadataAndLibraryIds(text, libraryIds);
|
||||
return bookEntities.stream()
|
||||
.map(bookMapperV2::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public Page<Book> searchBooksByMetadataInLibrariesPage(String text, Set<Long> libraryIds, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
|
||||
Page<BookEntity> books = bookRepository.searchByMetadataAndLibraryIds(text, libraryIds, pageable);
|
||||
List<Book> mapped = books.getContent().stream()
|
||||
.map(bookMapperV2::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
return new PageImpl<>(mapped, pageable, books.getTotalElements());
|
||||
}
|
||||
|
||||
public Page<Book> getAllBooksByShelfPage(Long shelfId, boolean includeDescription, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page - 1, 0), size);
|
||||
Page<BookEntity> books = bookRepository.findAllWithMetadataByShelfId(shelfId, pageable);
|
||||
return createPageFromBooks(books, pageable, includeDescription, null);
|
||||
}
|
||||
|
||||
public void saveAll(List<BookEntity> books) {
|
||||
bookRepository.saveAll(books);
|
||||
}
|
||||
|
||||
public List<Book> searchBooksByMetadata(String text) {
|
||||
Pageable pageable = PageRequest.of(0, Integer.MAX_VALUE);
|
||||
Page<BookEntity> books = bookRepository.searchByMetadata(text, pageable);
|
||||
return books.getContent().stream()
|
||||
.map(bookMapperV2::toDTO)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId) {
|
||||
return books.stream()
|
||||
.map(book -> mapBookToDto(book, includeDescription, userId))
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
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.BookOpdsRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class OpdsBookService {
|
||||
|
||||
private final BookOpdsRepository bookOpdsRepository;
|
||||
private final BookMapper bookMapper;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final LibraryService libraryService;
|
||||
|
||||
public List<Library> getAccessibleLibraries(OpdsUserDetails details) {
|
||||
if (details == null || details.getOpdsUserV2() == null) {
|
||||
try {
|
||||
return libraryService.getAllLibraries();
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to get all libraries", e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
if (user.getPermissions() != null && user.getPermissions().isAdmin()) {
|
||||
return libraryService.getAllLibraries();
|
||||
}
|
||||
|
||||
return user.getAssignedLibraries();
|
||||
}
|
||||
|
||||
public Page<Book> getBooksPage(OpdsUserDetails details, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
OpdsUser opdsUser = details.getOpdsUser();
|
||||
|
||||
if (opdsUser != null) {
|
||||
return getBooksPageForLegacyUser(query, libraryId, shelfId, page, size);
|
||||
}
|
||||
|
||||
return getBooksPageForV2User(details.getOpdsUserV2(), query, libraryId, shelfId, page, size);
|
||||
}
|
||||
|
||||
public Page<Book> getRecentBooksPage(OpdsUserDetails details, int page, int size) {
|
||||
if (details == null || details.getOpdsUser() != null) {
|
||||
return getRecentBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
OpdsUserV2 v2 = details.getOpdsUserV2();
|
||||
BookLoreUserEntity entity = userRepository.findById(v2.getUserId())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(v2.getUserId()));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return getRecentBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size);
|
||||
return applyBookFilters(books, v2.getUserId());
|
||||
}
|
||||
|
||||
public String getLibraryName(Long libraryId) {
|
||||
try {
|
||||
List<Library> libraries = libraryService.getAllLibraries();
|
||||
return libraries.stream()
|
||||
.filter(lib -> lib.getId().equals(libraryId))
|
||||
.map(Library::getName)
|
||||
.findFirst()
|
||||
.orElse("Library Books");
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to get library name for id: {}", libraryId, e);
|
||||
return "Library Books";
|
||||
}
|
||||
}
|
||||
|
||||
public String getShelfName(Long shelfId) {
|
||||
return shelfRepository.findById(shelfId)
|
||||
.map(s -> s.getName() + " - Shelf")
|
||||
.orElse("Shelf Books");
|
||||
}
|
||||
|
||||
public List<ShelfEntity> getUserShelves(Long userId) {
|
||||
return shelfRepository.findByUserId(userId);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksPageForLegacyUser(String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
if (shelfId != null) {
|
||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
||||
}
|
||||
if (libraryId != null) {
|
||||
Page<Book> books = getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, null);
|
||||
}
|
||||
if (query != null && !query.isBlank()) {
|
||||
return searchByMetadataPageInternal(query, page, size);
|
||||
}
|
||||
return getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksPageForV2User(OpdsUserV2 opdsUserV2, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||
BookLoreUserEntity entity = userRepository.findById(opdsUserV2.getUserId())
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(opdsUserV2.getUserId()));
|
||||
|
||||
if (entity.getPermissions() == null ||
|
||||
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (shelfId != null) {
|
||||
validateShelfAccess(shelfId, user.getId(), isAdmin);
|
||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
return applyBookFilters(books, opdsUserV2.getUserId());
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return query != null && !query.isBlank()
|
||||
? searchByMetadataPageInternal(query, page, size)
|
||||
: getAllBooksPageInternal(page, size);
|
||||
}
|
||||
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(query, userLibraryIds, page, size)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
|
||||
return applyBookFilters(books, opdsUserV2.getUserId());
|
||||
}
|
||||
|
||||
private Page<Book> getAllBooksPageInternal(int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIds(pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> getRecentBooksPageInternal(int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findRecentBookIds(pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByLibraryIds(libraryIds, pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> getRecentBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findRecentBookIdsByLibraryIds(libraryIds, pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksByShelfIdPageInternal(Long shelfId, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByShelfId(shelfId, pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(idPage.getContent(), shelfId);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> searchByMetadataPageInternal(String text, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearch(text, pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private Page<Book> searchByMetadataInLibrariesPageInternal(String text, Set<Long> libraryIds, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearchAndLibraryIds(text, libraryIds, pageable);
|
||||
if (idPage.isEmpty()) {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
}
|
||||
|
||||
private void validateShelfAccess(Long shelfId, Long userId, boolean isAdmin) {
|
||||
var shelf = shelfRepository.findById(shelfId)
|
||||
.orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||
if (!shelf.getUser().getId().equals(userId) && !isAdmin) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this shelf");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateLibraryAccess(Long libraryId, Set<Long> userLibraryIds, boolean isAdmin) {
|
||||
if (!isAdmin && !userLibraryIds.contains(libraryId)) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this library");
|
||||
}
|
||||
}
|
||||
|
||||
private Page<Book> createPageFromEntities(List<BookEntity> books, Page<Long> idPage, Pageable pageable) {
|
||||
Map<Long, BookEntity> bookMap = books.stream()
|
||||
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
|
||||
|
||||
List<Book> sortedBooks = idPage.getContent().stream()
|
||||
.map(bookMap::get)
|
||||
.filter(Objects::nonNull)
|
||||
.map(bookMapper::toBook)
|
||||
.toList();
|
||||
|
||||
return new PageImpl<>(sortedBooks, pageable, idPage.getTotalElements());
|
||||
}
|
||||
|
||||
private Page<Book> applyBookFilters(Page<Book> books, Long userId) {
|
||||
List<Book> filtered = books.getContent().stream()
|
||||
.map(book -> filterBook(book, userId))
|
||||
.collect(Collectors.toList());
|
||||
return new PageImpl<>(filtered, books.getPageable(), books.getTotalElements());
|
||||
}
|
||||
|
||||
private Book filterBook(Book dto, Long userId) {
|
||||
if (dto.getShelves() != null && userId != null) {
|
||||
dto.setShelves(dto.getShelves().stream()
|
||||
.filter(shelf -> userId.equals(shelf.getUserId()))
|
||||
.collect(Collectors.toSet()));
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
public List<Book> getRandomBooks(OpdsUserDetails details, int count) {
|
||||
List<Long> ids;
|
||||
List<Library> accessibleLibraries = getAccessibleLibraries(details);
|
||||
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList();
|
||||
|
||||
if (libraryIds.size() == 1 && libraryIds.getFirst() == null) {
|
||||
ids = bookOpdsRepository.findRandomBookIds();
|
||||
} else {
|
||||
ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds);
|
||||
}
|
||||
if (ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||
return books.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
}
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.service.OpdsBookService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsFeedService {
|
||||
|
||||
private static final int DEFAULT_PAGE_SIZE = 50;
|
||||
private static final int MAX_PAGE_SIZE = 100;
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final OpdsBookService opdsBookService;
|
||||
|
||||
public String generateRootNavigation(HttpServletRequest request) {
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opds="http://opds-spec.org/2010/catalog">
|
||||
<id>urn:booklore:root</id>
|
||||
<title>Booklore Catalog</title>
|
||||
<updated>%s</updated>
|
||||
<link rel="self" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>All Books</title>
|
||||
<id>urn:booklore:catalog:all</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/catalog?page=1&size=%d" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">Browse all available books</content>
|
||||
</entry>
|
||||
""".formatted(now(), DEFAULT_PAGE_SIZE));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Recently Added</title>
|
||||
<id>urn:booklore:catalog:recent</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/recent?page=1&size=%d" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">Recently added books</content>
|
||||
</entry>
|
||||
""".formatted(now(), DEFAULT_PAGE_SIZE));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Libraries</title>
|
||||
<id>urn:booklore:navigation:libraries</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/libraries" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<content type="text">Browse books by library</content>
|
||||
</entry>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Shelves</title>
|
||||
<id>urn:booklore:navigation:shelves</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/shelves" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<content type="text">Browse your personal shelves</content>
|
||||
</entry>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>Surprise Me</title>
|
||||
<id>urn:booklore:catalog:surprise</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/surprise" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">25 random books from the catalog</content>
|
||||
</entry>
|
||||
""".formatted(now()));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateLibrariesNavigation(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
List<Library> libraries = opdsBookService.getAccessibleLibraries(details);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opds="http://opds-spec.org/2010/catalog">
|
||||
<id>urn:booklore:navigation:libraries</id>
|
||||
<title>Libraries</title>
|
||||
<updated>%s</updated>
|
||||
<link rel="self" href="/api/v1/opds/libraries" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now()));
|
||||
|
||||
for (Library library : libraries) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:library:%d</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/catalog?libraryId=%d" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">%s</content>
|
||||
</entry>
|
||||
""".formatted(
|
||||
escapeXml(library.getName()),
|
||||
library.getId(),
|
||||
now(),
|
||||
library.getId(),
|
||||
escapeXml(library.getName() != null ? library.getName() : "Library collection")
|
||||
));
|
||||
}
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateShelvesNavigation(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:opds="http://opds-spec.org/2010/catalog">
|
||||
<id>urn:booklore:navigation:shelves</id>
|
||||
<title>Shelves</title>
|
||||
<updated>%s</updated>
|
||||
<link rel="self" href="/api/v1/opds/shelves" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now()));
|
||||
|
||||
if (details != null && details.getOpdsUserV2() != null) {
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
var shelves = opdsBookService.getUserShelves(userId);
|
||||
|
||||
if (shelves != null) {
|
||||
for (var shelf : shelves) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:shelf:%d</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="subsection" href="/api/v1/opds/catalog?shelfId=%d" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<content type="text">Personal shelf collection</content>
|
||||
</entry>
|
||||
""".formatted(
|
||||
escapeXml(shelf.getName()),
|
||||
shelf.getId(),
|
||||
now(),
|
||||
shelf.getId()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
Long libraryId = parseLongParam(request, "libraryId", null);
|
||||
Long shelfId = parseLongParam(request, "shelfId", null);
|
||||
String query = request.getParameter("q");
|
||||
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);
|
||||
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
Page<Book> booksPage = opdsBookService.getBooksPage(details, query, libraryId, shelfId, page - 1, size);
|
||||
|
||||
String feedTitle = determineFeedTitle(libraryId, shelfId);
|
||||
String feedId = determineFeedId(libraryId, shelfId);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/" xmlns:opds="http://opds-spec.org/2010/catalog" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<id>%s</id>
|
||||
<title>%s</title>
|
||||
<updated>%s</updated>
|
||||
<opensearch:totalResults>%d</opensearch:totalResults>
|
||||
<opensearch:startIndex>%d</opensearch:startIndex>
|
||||
<opensearch:itemsPerPage>%d</opensearch:itemsPerPage>
|
||||
<link rel="self" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(
|
||||
feedId,
|
||||
escapeXml(feedTitle),
|
||||
now(),
|
||||
booksPage.getTotalElements(),
|
||||
((page - 1) * size) + 1,
|
||||
size,
|
||||
buildCurrentUrl(request, page, size)
|
||||
));
|
||||
|
||||
appendPaginationLinks(feed, request, page, booksPage.getTotalPages(), size);
|
||||
|
||||
booksPage.getContent().forEach(book -> appendBookEntry(feed, book));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateRecentFeed(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
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);
|
||||
|
||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(details, page - 1, size);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/" xmlns:opds="http://opds-spec.org/2010/catalog" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<id>urn:booklore:catalog:recent</id>
|
||||
<title>Recently Added Books</title>
|
||||
<updated>%s</updated>
|
||||
<opensearch:totalResults>%d</opensearch:totalResults>
|
||||
<opensearch:startIndex>%d</opensearch:startIndex>
|
||||
<opensearch:itemsPerPage>%d</opensearch:itemsPerPage>
|
||||
<link rel="self" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now(), booksPage.getTotalElements(), ((page - 1) * size) + 1, size, buildCurrentUrl(request, page, size)));
|
||||
|
||||
appendPaginationLinks(feed, request, page, booksPage.getTotalPages(), size);
|
||||
|
||||
booksPage.getContent().forEach(book -> appendBookEntry(feed, book));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String generateSurpriseFeed(HttpServletRequest request) {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
int count = 25;
|
||||
List<Book> books = opdsBookService.getRandomBooks(details, count);
|
||||
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/" xmlns:opds="http://opds-spec.org/2010/catalog" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<id>urn:booklore:catalog:surprise</id>
|
||||
<title>Surprise Me</title>
|
||||
<updated>%s</updated>
|
||||
<opensearch:totalResults>%d</opensearch:totalResults>
|
||||
<opensearch:startIndex>1</opensearch:startIndex>
|
||||
<opensearch:itemsPerPage>%d</opensearch:itemsPerPage>
|
||||
<link rel="self" href="/api/v1/opds/surprise" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||
<link rel="start" href="/api/v1/opds" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||
""".formatted(now(), books.size(), count));
|
||||
|
||||
books.forEach(book -> appendBookEntry(feed, book));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
public String getOpenSearchDescription() {
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<ShortName>Booklore</ShortName>
|
||||
<Description>Search Booklore catalog</Description>
|
||||
<Url type="application/atom+xml;profile=opds-catalog;kind=acquisition"
|
||||
template="/api/v1/opds/catalog?q={searchTerms}"/>
|
||||
</OpenSearchDescription>
|
||||
""";
|
||||
}
|
||||
|
||||
private void appendPaginationLinks(StringBuilder feed, HttpServletRequest request, int currentPage, int totalPages, int size) {
|
||||
if (totalPages > 0) {
|
||||
feed.append(" <link rel=\"first\" href=\"")
|
||||
.append(escapeXml(buildPaginationUrl(request, 1, size)))
|
||||
.append("\" type=\"application/atom+xml;profile=opds-catalog;kind=acquisition\"/>\n");
|
||||
}
|
||||
if (currentPage > 1) {
|
||||
feed.append(" <link rel=\"previous\" href=\"")
|
||||
.append(escapeXml(buildPaginationUrl(request, currentPage - 1, size)))
|
||||
.append("\" type=\"application/atom+xml;profile=opds-catalog;kind=acquisition\"/>\n");
|
||||
}
|
||||
if (currentPage < totalPages) {
|
||||
feed.append(" <link rel=\"next\" href=\"")
|
||||
.append(escapeXml(buildPaginationUrl(request, currentPage + 1, size)))
|
||||
.append("\" type=\"application/atom+xml;profile=opds-catalog;kind=acquisition\"/>\n");
|
||||
}
|
||||
if (totalPages > 0) {
|
||||
feed.append(" <link rel=\"last\" href=\"")
|
||||
.append(escapeXml(buildPaginationUrl(request, totalPages, size)))
|
||||
.append("\" type=\"application/atom+xml;profile=opds-catalog;kind=acquisition\"/>\n");
|
||||
}
|
||||
}
|
||||
|
||||
private String buildPaginationUrl(HttpServletRequest request, int page, int size) {
|
||||
String url = request.getRequestURI();
|
||||
StringBuilder result = new StringBuilder(url).append("?");
|
||||
|
||||
String queryString = request.getQueryString();
|
||||
if (queryString != null) {
|
||||
java.util.Arrays.stream(queryString.split("&"))
|
||||
.filter(param -> !param.startsWith("page=") && !param.startsWith("size="))
|
||||
.forEach(param -> result.append(param).append("&"));
|
||||
}
|
||||
|
||||
result.append("page=").append(page).append("&size=").append(size);
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String buildCurrentUrl(HttpServletRequest request, int page, int size) {
|
||||
return buildPaginationUrl(request, page, size);
|
||||
}
|
||||
|
||||
private void appendBookEntry(StringBuilder feed, Book book) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:book:%d</id>
|
||||
<updated>%s</updated>
|
||||
""".formatted(
|
||||
escapeXml(book.getMetadata().getTitle()),
|
||||
book.getId(),
|
||||
book.getAddedOn() != null ? book.getAddedOn() : now()
|
||||
));
|
||||
|
||||
if (book.getMetadata().getAuthors() != null) {
|
||||
book.getMetadata().getAuthors().forEach(author ->
|
||||
feed.append(" <author><name>").append(escapeXml(author)).append("</name></author>\n")
|
||||
);
|
||||
}
|
||||
|
||||
appendMetadata(feed, book);
|
||||
appendLinks(feed, book);
|
||||
|
||||
feed.append(" </entry>\n");
|
||||
}
|
||||
|
||||
private void appendMetadata(StringBuilder feed, Book book) {
|
||||
var meta = book.getMetadata();
|
||||
if (meta == null) return;
|
||||
|
||||
if (meta.getPublisher() != null) {
|
||||
feed.append(" <dc:publisher>").append(escapeXml(meta.getPublisher())).append("</dc:publisher>\n");
|
||||
}
|
||||
if (meta.getLanguage() != null) {
|
||||
feed.append(" <dc:language>").append(escapeXml(meta.getLanguage())).append("</dc:language>\n");
|
||||
}
|
||||
if (meta.getCategories() != null) {
|
||||
meta.getCategories().forEach(cat ->
|
||||
feed.append(" <category term=\"").append(escapeXml(cat)).append("\"/>\n")
|
||||
);
|
||||
}
|
||||
if (meta.getDescription() != null) {
|
||||
feed.append(" <summary>").append(escapeXml(meta.getDescription())).append("</summary>\n");
|
||||
}
|
||||
if (meta.getIsbn10() != null) {
|
||||
feed.append(" <dc:identifier>urn:isbn:").append(escapeXml(meta.getIsbn10())).append("</dc:identifier>\n");
|
||||
}
|
||||
}
|
||||
|
||||
private void appendLinks(StringBuilder feed, Book book) {
|
||||
String mimeType = "application/" + fileMimeType(book);
|
||||
feed.append(" <link href=\"/api/v1/opds/")
|
||||
.append(book.getId()).append("/download\" rel=\"http://opds-spec.org/acquisition\" type=\"").append(mimeType).append("\"/>\n");
|
||||
|
||||
if (book.getMetadata() != null && book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
String coverUrl = "/api/v1/opds/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
|
||||
feed.append(" <link rel=\"http://opds-spec.org/image\" href=\"")
|
||||
.append(escapeXml(coverUrl)).append("\" type=\"image/jpeg\"/>\n");
|
||||
feed.append(" <link rel=\"http://opds-spec.org/image/thumbnail\" href=\"")
|
||||
.append(escapeXml(coverUrl)).append("\" type=\"image/jpeg\"/>\n");
|
||||
}
|
||||
}
|
||||
|
||||
private String determineFeedTitle(Long libraryId, Long shelfId) {
|
||||
if (shelfId != null) {
|
||||
return opdsBookService.getShelfName(shelfId);
|
||||
}
|
||||
if (libraryId != null) {
|
||||
return opdsBookService.getLibraryName(libraryId);
|
||||
}
|
||||
return "Booklore Catalog";
|
||||
}
|
||||
|
||||
private String determineFeedId(Long libraryId, Long shelfId) {
|
||||
if (shelfId != null) {
|
||||
return "urn:booklore:shelf:" + shelfId;
|
||||
}
|
||||
if (libraryId != null) {
|
||||
return "urn:booklore:library:" + libraryId;
|
||||
}
|
||||
return "urn:booklore:catalog";
|
||||
}
|
||||
|
||||
private String now() {
|
||||
return DateTimeFormatter.ISO_INSTANT.format(java.time.Instant.now());
|
||||
}
|
||||
|
||||
private String fileMimeType(Book book) {
|
||||
if (book == null || book.getBookType() == null) {
|
||||
return "octet-stream";
|
||||
}
|
||||
return switch (book.getBookType()) {
|
||||
case PDF -> "pdf";
|
||||
case EPUB -> "epub+zip";
|
||||
default -> "octet-stream";
|
||||
};
|
||||
}
|
||||
|
||||
private String escapeXml(String input) {
|
||||
return input == null ? "" :
|
||||
input.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
|
||||
private Long parseLongParam(HttpServletRequest request, String name, Long defaultValue) {
|
||||
try {
|
||||
String v = request.getParameter(name);
|
||||
if (v == null || v.isBlank()) return defaultValue;
|
||||
return Long.parseLong(v);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,735 +0,0 @@
|
||||
package com.adityachandel.booklore.service.opds;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.service.library.LibraryService;
|
||||
import com.adityachandel.booklore.service.BookQueryService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OpdsService {
|
||||
|
||||
private final BookQueryService bookQueryService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final LibraryService libraryService;
|
||||
|
||||
|
||||
public String generateCatalogFeed(HttpServletRequest request) {
|
||||
Long libraryId = parseLongParam(request, "libraryId", null);
|
||||
Long shelfId = parseLongParam(request, "shelfId", null);
|
||||
String forceV2 = (libraryId != null || shelfId != null) ? "2.0" : null;
|
||||
String feedVersion = forceV2 != null ? forceV2 : extractVersionFromAcceptHeader(request);
|
||||
return switch (feedVersion) {
|
||||
case "2.0" -> {
|
||||
int page = parseIntParam(request, "page", 1);
|
||||
int size = parseIntParam(request, "size", 50);
|
||||
var result = getAllowedBooksPage(null, libraryId, shelfId, page, size);
|
||||
var qp = new java.util.LinkedHashMap<String,String>();
|
||||
if (libraryId != null) qp.put("libraryId", String.valueOf(libraryId));
|
||||
if (shelfId != null) qp.put("shelfId", String.valueOf(shelfId));
|
||||
yield generateOpdsV2Feed(result.getContent(), result.getTotalElements(), "/api/v2/opds/catalog", qp, page, size);
|
||||
}
|
||||
default -> {
|
||||
List<Book> books = getAllowedBooks(null);
|
||||
yield generateOpdsV1Feed(books, request);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public String generateSearchResults(HttpServletRequest request, String queryParam) {
|
||||
Long libraryId = parseLongParam(request, "libraryId", null);
|
||||
Long shelfId = parseLongParam(request, "shelfId", null);
|
||||
String forceV2 = (libraryId != null || shelfId != null) ? "2.0" : null;
|
||||
String feedVersion = forceV2 != null ? forceV2 : extractVersionFromAcceptHeader(request);
|
||||
return switch (feedVersion) {
|
||||
case "2.0" -> {
|
||||
int page = parseIntParam(request, "page", 1);
|
||||
int size = parseIntParam(request, "size", 50);
|
||||
String q = request.getParameter("q");
|
||||
var result = getAllowedBooksPage(q, libraryId, shelfId, page, size);
|
||||
var qp = new java.util.LinkedHashMap<String,String>();
|
||||
if (q != null && !q.isBlank()) qp.put("q", q);
|
||||
if (libraryId != null) qp.put("libraryId", String.valueOf(libraryId));
|
||||
if (shelfId != null) qp.put("shelfId", String.valueOf(shelfId));
|
||||
yield generateOpdsV2Feed(result.getContent(), result.getTotalElements(), "/api/v2/opds/search", qp, page, size);
|
||||
}
|
||||
default -> {
|
||||
List<Book> books = getAllowedBooks(queryParam);
|
||||
yield generateOpdsV1Feed(books, request);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public String generateRecentFeed(HttpServletRequest request) {
|
||||
int page = parseIntParam(request, "page", 1);
|
||||
int size = parseIntParam(request, "size", 50);
|
||||
|
||||
// Determine context: legacy OPDS user vs OPDS v2 user
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
OpdsUser opdsUser = details.getOpdsUser();
|
||||
|
||||
var qp = new java.util.LinkedHashMap<String, String>();
|
||||
qp.put("page", String.valueOf(page));
|
||||
qp.put("size", String.valueOf(size));
|
||||
|
||||
if (opdsUser != null) {
|
||||
var result = bookQueryService.getRecentBooksPage(true, page, size);
|
||||
return generateOpdsV2Feed(result.getContent(), result.getTotalElements(), "/api/v2/opds/recent", qp, page, size);
|
||||
}
|
||||
|
||||
OpdsUserV2 v2 = details.getOpdsUserV2();
|
||||
BookLoreUserEntity entity = userRepository.findById(v2.getUserId())
|
||||
.orElseThrow(() -> new org.springframework.security.access.AccessDeniedException("User not found"));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
if (isAdmin) {
|
||||
var result = bookQueryService.getRecentBooksPage(true, page, size);
|
||||
return generateOpdsV2Feed(result.getContent(), result.getTotalElements(), "/api/v2/opds/recent", qp, page, size);
|
||||
}
|
||||
|
||||
java.util.Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
var result = bookQueryService.getRecentBooksByLibraryIdsPage(libraryIds, true, page, size, v2.getUserId());
|
||||
return generateOpdsV2Feed(result.getContent(), result.getTotalElements(), "/api/v2/opds/recent", qp, page, size);
|
||||
}
|
||||
|
||||
public String generateOpdsV2Navigation(HttpServletRequest request) {
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
String rootPath = "/api/v2/opds";
|
||||
var root = new java.util.LinkedHashMap<String, Object>();
|
||||
|
||||
// metadata
|
||||
var meta = new java.util.LinkedHashMap<String, Object>();
|
||||
meta.put("title", "Booklore");
|
||||
root.put("metadata", meta);
|
||||
|
||||
// links: self, start, search
|
||||
var links = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "self",
|
||||
"href", rootPath,
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "start",
|
||||
"href", rootPath,
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "search",
|
||||
"href", rootPath + "/search.opds",
|
||||
"type", "application/opensearchdescription+xml"
|
||||
));
|
||||
root.put("links", links);
|
||||
|
||||
// navigation items
|
||||
var navigation = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", "All Books",
|
||||
"href", rootPath + "/catalog",
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
)));
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", "Recently Added",
|
||||
"href", rootPath + "/recent",
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
)));
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", "Libraries",
|
||||
"href", rootPath + "/libraries",
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
)));
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", "Shelves",
|
||||
"href", rootPath + "/shelves",
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
)));
|
||||
|
||||
|
||||
// Enrich with libraries and shelves for OPDS v2 users
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
if (details != null && details.getOpdsUserV2() != null) {
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new org.springframework.security.access.AccessDeniedException("User not found"));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
java.util.List<Library> libraries;
|
||||
try {
|
||||
libraries = libraryService.getLibraries();
|
||||
} catch (Exception ex) {
|
||||
libraries = user.getAssignedLibraries();
|
||||
}
|
||||
// Keep root clean: only references to collections; no inline lists
|
||||
if (libraries != null) {
|
||||
// optionally keep this empty or add a count in future
|
||||
}
|
||||
}
|
||||
root.put("navigation", navigation);
|
||||
|
||||
return mapper.writeValueAsString(root);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed generating OPDS v2 navigation collection", e);
|
||||
throw new RuntimeException("Failed generating OPDS v2 navigation collection", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String generateOpdsV2LibrariesNavigation(HttpServletRequest request) {
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
String rootPath = "/api/v2/opds";
|
||||
String selfPath = rootPath + "/libraries";
|
||||
var root = new java.util.LinkedHashMap<String, Object>();
|
||||
|
||||
// metadata
|
||||
var meta = new java.util.LinkedHashMap<String, Object>();
|
||||
meta.put("title", "Libraries");
|
||||
root.put("metadata", meta);
|
||||
|
||||
// links
|
||||
var links = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "self",
|
||||
"href", selfPath,
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "start",
|
||||
"href", rootPath,
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "search",
|
||||
"href", rootPath + "/search.opds",
|
||||
"type", "application/opensearchdescription+xml"
|
||||
));
|
||||
root.put("links", links);
|
||||
|
||||
// navigation list of libraries
|
||||
var navigation = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
if (details != null && details.getOpdsUserV2() != null) {
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new AccessDeniedException("User not found"));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
java.util.List<Library> libraries = (user.getPermissions() != null && user.getPermissions().isAdmin())
|
||||
? libraryService.getAllLibraries()
|
||||
: user.getAssignedLibraries();
|
||||
if (libraries != null) {
|
||||
for (Library lib : libraries) {
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", lib.getName(),
|
||||
"href", buildHref(rootPath + "/catalog", java.util.Map.of("libraryId", String.valueOf(lib.getId()))),
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
root.put("navigation", navigation);
|
||||
return mapper.writeValueAsString(root);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed generating OPDS v2 libraries navigation", e);
|
||||
throw new RuntimeException("Failed generating OPDS v2 libraries navigation", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String generateOpdsV2ShelvesNavigation(HttpServletRequest request) {
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
String rootPath = "/api/v2/opds";
|
||||
String selfPath = rootPath + "/shelves";
|
||||
var root = new java.util.LinkedHashMap<String, Object>();
|
||||
|
||||
var meta = new java.util.LinkedHashMap<String, Object>();
|
||||
meta.put("title", "Shelves");
|
||||
root.put("metadata", meta);
|
||||
|
||||
var links = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
links.add(java.util.Map.of("rel", "self", "href", selfPath, "type", "application/opds+json;profile=navigation"));
|
||||
links.add(java.util.Map.of("rel", "start", "href", rootPath, "type", "application/opds+json;profile=navigation"));
|
||||
links.add(java.util.Map.of("rel", "search", "href", rootPath + "/search.opds", "type", "application/opensearchdescription+xml"));
|
||||
root.put("links", links);
|
||||
|
||||
var navigation = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
if (details != null && details.getOpdsUserV2() != null) {
|
||||
Long userId = details.getOpdsUserV2().getUserId();
|
||||
var shelves = shelfRepository.findByUserId(userId);
|
||||
if (shelves != null) {
|
||||
for (var shelf : shelves) {
|
||||
navigation.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"title", shelf.getName(),
|
||||
"href", buildHref(rootPath + "/catalog", java.util.Map.of("shelfId", String.valueOf(shelf.getId()))),
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
root.put("navigation", navigation);
|
||||
return mapper.writeValueAsString(root);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed generating OPDS v2 shelves navigation", e);
|
||||
throw new RuntimeException("Failed generating OPDS v2 shelves navigation", e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Book> getAllowedBooks(String queryParam) {
|
||||
OpdsUserDetails opdsUserDetails = authenticationService.getOpdsUser();
|
||||
OpdsUser opdsUser = opdsUserDetails.getOpdsUser();
|
||||
|
||||
if (opdsUser != null) {
|
||||
return (queryParam != null)
|
||||
? bookQueryService.searchBooksByMetadata(queryParam)
|
||||
: bookQueryService.getAllBooks(true);
|
||||
}
|
||||
|
||||
OpdsUserV2 opdsUserV2 = opdsUserDetails.getOpdsUserV2();
|
||||
BookLoreUserEntity entity = userRepository.findById(opdsUserV2.getUserId())
|
||||
.orElseThrow(() -> new AccessDeniedException("User not found"));
|
||||
|
||||
if (!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin()) {
|
||||
throw new AccessDeniedException("You are not allowed to access this resource");
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (isAdmin) {
|
||||
return (queryParam != null)
|
||||
? bookQueryService.searchBooksByMetadata(queryParam)
|
||||
: bookQueryService.getAllBooks(true);
|
||||
} else {
|
||||
return (queryParam != null)
|
||||
? bookQueryService.searchBooksByMetadataInLibraries(queryParam, libraryIds)
|
||||
: bookQueryService.getAllBooksByLibraryIds(libraryIds, true, opdsUserV2.getUserId());
|
||||
}
|
||||
}
|
||||
|
||||
public String generateSearchDescription(HttpServletRequest request) {
|
||||
var feedVersion = extractVersionFromAcceptHeader(request);
|
||||
|
||||
return switch (feedVersion) {
|
||||
case "2.0" -> generateOpdsV2SearchDescription();
|
||||
default -> generateOpdsV1SearchDescription();
|
||||
};
|
||||
}
|
||||
|
||||
private String extractVersionFromAcceptHeader(HttpServletRequest request) {
|
||||
var acceptHeader = request.getHeader("Accept");
|
||||
if (acceptHeader == null) return "1.2";
|
||||
// Accept either explicit version or generic OPDS 2 media type
|
||||
if (acceptHeader.contains("version=2.0") || acceptHeader.contains("application/opds+json")) {
|
||||
return "2.0";
|
||||
}
|
||||
return "1.2";
|
||||
}
|
||||
|
||||
private String generateOpdsV1SearchDescription() {
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<LongName>Booklore catalog</LongName>
|
||||
<Description>Search the Booklore ebook catalog.</Description>
|
||||
<Url type="application/atom+xml;profile=opds-catalog" template="/api/v1/opds/search?q={searchTerms}"/>
|
||||
<Language>en-us</Language>
|
||||
<OutputEncoding>UTF-8</OutputEncoding>
|
||||
<InputEncoding>UTF-8</InputEncoding>
|
||||
</OpenSearchDescription>
|
||||
""";
|
||||
}
|
||||
|
||||
private String generateOpdsV1Feed(List<Book> books, HttpServletRequest request) {
|
||||
String version = extractVersionFromRequest(request); // v1 or v2
|
||||
var feed = new StringBuilder("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/terms/">
|
||||
<title>Booklore Catalog</title>
|
||||
<id>urn:booklore:catalog</id>
|
||||
<updated>%s</updated>
|
||||
<link rel="search" type="application/opensearchdescription+xml" title="Booklore Search" href="/api/%s/opds/search.opds"/>
|
||||
""".formatted(now(), version));
|
||||
|
||||
books.forEach(book -> appendBookEntryV1(feed, book, version));
|
||||
|
||||
feed.append("</feed>");
|
||||
return feed.toString();
|
||||
}
|
||||
|
||||
private void appendBookEntryV1(StringBuilder feed, Book book, String version) {
|
||||
feed.append("""
|
||||
<entry>
|
||||
<title>%s</title>
|
||||
<id>urn:booklore:book:%d</id>
|
||||
<updated>%s</updated>
|
||||
""".formatted(escapeXml(book.getMetadata().getTitle()), book.getId(),
|
||||
book.getAddedOn() != null ? book.getAddedOn() : now()));
|
||||
|
||||
book.getMetadata().getAuthors().forEach(author -> feed.append("""
|
||||
<author>
|
||||
<name>%s</name>
|
||||
</author>
|
||||
""".formatted(escapeXml(author))));
|
||||
|
||||
appendOptionalTags(feed, book, version);
|
||||
feed.append(" </entry>");
|
||||
}
|
||||
|
||||
private void appendOptionalTags(StringBuilder feed, Book book, String version) {
|
||||
String basePath = "/api/" + version + "/opds/";
|
||||
|
||||
if (book.getMetadata().getPublisher() != null) {
|
||||
feed.append("<dc:publisher>").append(escapeXml(book.getMetadata().getPublisher())).append("</dc:publisher>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getLanguage() != null) {
|
||||
feed.append("<dc:language>").append(escapeXml(book.getMetadata().getLanguage())).append("</dc:language>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getCategories() != null) {
|
||||
book.getMetadata().getCategories().forEach(category ->
|
||||
feed.append("<dc:subject>").append(escapeXml(category)).append("</dc:subject>")
|
||||
);
|
||||
}
|
||||
|
||||
if (book.getMetadata().getIsbn10() != null) {
|
||||
feed.append("<dc:identifier>").append(escapeXml("urn:isbn:" + book.getMetadata().getIsbn10())).append("</dc:identifier>");
|
||||
}
|
||||
|
||||
if (book.getMetadata().getPublishedDate() != null) {
|
||||
feed.append("<published>").append(book.getMetadata().getPublishedDate()).append("</published>");
|
||||
}
|
||||
|
||||
// download link
|
||||
feed.append("""
|
||||
<link href="%s%d/download" rel="http://opds-spec.org/acquisition" type="application/%s"/>
|
||||
""".formatted(basePath, book.getId(), fileMimeType(book)));
|
||||
|
||||
// cover link
|
||||
if (book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
String coverPath = basePath + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
|
||||
feed.append("""
|
||||
<link rel="http://opds-spec.org/image" href="%s" type="image/jpeg"/>
|
||||
<link rel="http://opds-spec.org/image/thumbnail" href="%s" type="image/jpeg"/>
|
||||
""".formatted(escapeXml(coverPath), escapeXml(coverPath)));
|
||||
}
|
||||
|
||||
if (book.getMetadata().getDescription() != null) {
|
||||
feed.append("<summary>").append(escapeXml(book.getMetadata().getDescription())).append("</summary>");
|
||||
}
|
||||
}
|
||||
|
||||
private String generateOpdsV2Feed(List<Book> content, long total, String basePath, java.util.Map<String,String> queryParams, int page, int size) {
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
// Root collection
|
||||
var root = new java.util.LinkedHashMap<String, Object>();
|
||||
|
||||
// metadata with pagination
|
||||
var meta = new java.util.LinkedHashMap<String, Object>();
|
||||
meta.put("title", "Booklore Catalog");
|
||||
if (page < 1) page = 1;
|
||||
if (size < 1) size = 1;
|
||||
if (size > 200) size = 200;
|
||||
meta.put("itemsPerPage", size);
|
||||
meta.put("currentPage", page);
|
||||
meta.put("numberOfItems", total);
|
||||
root.put("metadata", meta);
|
||||
|
||||
// links
|
||||
var links = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "self",
|
||||
"href", buildHref(basePath, mergeQuery(queryParams, java.util.Map.of("page", String.valueOf(page), "size", String.valueOf(size)))),
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "start",
|
||||
"href", "/api/v2/opds",
|
||||
"type", "application/opds+json;profile=navigation"
|
||||
));
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "search",
|
||||
"href", "/api/v2/opds/search.opds",
|
||||
"type", "application/opensearchdescription+xml"
|
||||
));
|
||||
if ((page - 1) > 0) {
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "previous",
|
||||
"href", buildHref(basePath, mergeQuery(queryParams, java.util.Map.of("page", String.valueOf(page - 1), "size", String.valueOf(size)))),
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
));
|
||||
}
|
||||
if ((long) page * size < total) {
|
||||
links.add(java.util.Map.of(
|
||||
"rel", "next",
|
||||
"href", buildHref(basePath, mergeQuery(queryParams, java.util.Map.of("page", String.valueOf(page + 1), "size", String.valueOf(size)))),
|
||||
"type", "application/opds+json;profile=acquisition"
|
||||
));
|
||||
}
|
||||
root.put("links", links);
|
||||
|
||||
// publications
|
||||
var pubs = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
for (Book book : content) {
|
||||
pubs.add(toPublicationMap(book));
|
||||
}
|
||||
root.put("publications", pubs);
|
||||
|
||||
return mapper.writeValueAsString(root);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed generating OPDS v2 feed", e);
|
||||
throw new RuntimeException("Failed generating OPDS v2 feed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String generateOpdsV2Publication(HttpServletRequest request, long bookId) {
|
||||
List<Book> allowed = getAllowedBooks(null);
|
||||
Book target = allowed.stream().filter(b -> b.getId() != null && b.getId() == bookId).findFirst()
|
||||
.orElseThrow(() -> new AccessDeniedException("You are not allowed to access this resource"));
|
||||
try {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
return mapper.writeValueAsString(toPublicationMap(target));
|
||||
} catch (Exception e) {
|
||||
log.error("Failed generating OPDS v2 publication", e);
|
||||
throw new RuntimeException("Failed generating OPDS v2 publication", e);
|
||||
}
|
||||
}
|
||||
|
||||
private java.util.Map<String, Object> toPublicationMap(Book book) {
|
||||
String base = "/api/v2/opds";
|
||||
var pub = new java.util.LinkedHashMap<String, Object>();
|
||||
var pm = new java.util.LinkedHashMap<String, Object>();
|
||||
String title = (book.getMetadata() != null ? book.getMetadata().getTitle() : book.getTitle());
|
||||
pm.put("title", title != null ? title : "Untitled");
|
||||
if (book.getMetadata() != null) {
|
||||
if (book.getMetadata().getLanguage() != null) {
|
||||
pm.put("language", book.getMetadata().getLanguage());
|
||||
}
|
||||
if (book.getMetadata().getIsbn13() != null) {
|
||||
pm.put("identifier", "urn:isbn:" + book.getMetadata().getIsbn13());
|
||||
} else if (book.getMetadata().getIsbn10() != null) {
|
||||
pm.put("identifier", "urn:isbn:" + book.getMetadata().getIsbn10());
|
||||
}
|
||||
if (book.getMetadata().getAuthors() != null && !book.getMetadata().getAuthors().isEmpty()) {
|
||||
var authors = book.getMetadata().getAuthors().stream()
|
||||
.map(a -> java.util.Map.of("name", a))
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
pm.put("author", authors);
|
||||
}
|
||||
if (book.getMetadata().getDescription() != null) {
|
||||
pm.put("description", book.getMetadata().getDescription());
|
||||
}
|
||||
}
|
||||
pub.put("metadata", pm);
|
||||
|
||||
var plinks = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
String type = "application/" + fileMimeType(book);
|
||||
plinks.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"rel", "http://opds-spec.org/acquisition/open-access",
|
||||
"href", base + "/" + book.getId() + "/download",
|
||||
"type", type
|
||||
)));
|
||||
plinks.add(new java.util.LinkedHashMap<>(java.util.Map.of(
|
||||
"rel", "self",
|
||||
"href", base + "/publications/" + book.getId(),
|
||||
"type", "application/opds-publication+json"
|
||||
)));
|
||||
pub.put("links", plinks);
|
||||
|
||||
if (book.getMetadata() != null && book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
var images = new java.util.ArrayList<java.util.Map<String, Object>>();
|
||||
String coverHref = base + "/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
|
||||
images.add(java.util.Map.of("href", coverHref, "type", "image/jpeg"));
|
||||
pub.put("images", images);
|
||||
}
|
||||
return pub;
|
||||
}
|
||||
|
||||
private String generateOpdsV2SearchDescription() {
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
|
||||
<LongName>Booklore catalog (OPDS 2)</LongName>
|
||||
<Description>Search the Booklore ebook catalog.</Description>
|
||||
<Url type="application/opds+json" template="/api/v2/opds/search{?q}"/>
|
||||
<Language>en-us</Language>
|
||||
<OutputEncoding>UTF-8</OutputEncoding>
|
||||
<InputEncoding>UTF-8</InputEncoding>
|
||||
</OpenSearchDescription>
|
||||
""";
|
||||
}
|
||||
|
||||
|
||||
private String now() {
|
||||
return DateTimeFormatter.ISO_INSTANT.format(java.time.Instant.now());
|
||||
}
|
||||
|
||||
private String fileMimeType(Book book) {
|
||||
if (book == null || book.getBookType() == null) {
|
||||
return "octet-stream";
|
||||
}
|
||||
return switch (book.getBookType()) {
|
||||
case PDF -> "pdf";
|
||||
case EPUB -> "epub+zip";
|
||||
default -> "octet-stream";
|
||||
};
|
||||
}
|
||||
|
||||
private String escapeXml(String input) {
|
||||
return input == null ? "" :
|
||||
input.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
|
||||
private String extractVersionFromRequest(HttpServletRequest request) {
|
||||
return (request.getRequestURI() != null && request.getRequestURI().startsWith("/api/v2/opds")) ? "v2" : "v1";
|
||||
}
|
||||
|
||||
private String urlEncode(String value) {
|
||||
try {
|
||||
return java.net.URLEncoder.encode(value, java.nio.charset.StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
private int parseIntParam(HttpServletRequest request, String name, int defaultValue) {
|
||||
try {
|
||||
String v = request.getParameter(name);
|
||||
if (v == null || v.isBlank()) return defaultValue;
|
||||
return Integer.parseInt(v);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildHref(String basePath, java.util.Map<String, String> params) {
|
||||
if (params == null || params.isEmpty()) return basePath;
|
||||
String query = params.entrySet().stream()
|
||||
.map(e -> urlEncode(e.getKey()) + "=" + urlEncode(e.getValue()))
|
||||
.collect(java.util.stream.Collectors.joining("&"));
|
||||
return basePath + (query.isEmpty() ? "" : ("?" + query));
|
||||
}
|
||||
|
||||
private java.util.Map<String, String> mergeQuery(java.util.Map<String, String> base, java.util.Map<String, String> extra) {
|
||||
var map = new java.util.LinkedHashMap<String, String>();
|
||||
if (base != null) map.putAll(base);
|
||||
if (extra != null) map.putAll(extra);
|
||||
return map;
|
||||
}
|
||||
|
||||
private Long parseLongParam(HttpServletRequest request, String name, Long defaultValue) {
|
||||
try {
|
||||
String v = request.getParameter(name);
|
||||
if (v == null || v.isBlank()) return defaultValue;
|
||||
return Long.parseLong(v);
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private org.springframework.data.domain.Page<Book> getAllowedBooksPage(String queryParam, Long libraryId, Long shelfId, int page, int size) {
|
||||
OpdsUserDetails opdsUserDetails = authenticationService.getOpdsUser();
|
||||
OpdsUser opdsUser = opdsUserDetails.getOpdsUser();
|
||||
|
||||
if (opdsUser != null) {
|
||||
if (shelfId != null) {
|
||||
return bookQueryService.getAllBooksByShelfPage(shelfId, true, page, size);
|
||||
}
|
||||
if (libraryId != null) {
|
||||
return bookQueryService.getAllBooksByLibraryIdsPage(java.util.Set.of(libraryId), true, page, size, null);
|
||||
}
|
||||
if (queryParam != null && !queryParam.isBlank()) {
|
||||
return bookQueryService.searchBooksByMetadataPage(queryParam, page, size);
|
||||
}
|
||||
return bookQueryService.getAllBooksPage(true, page, size);
|
||||
}
|
||||
|
||||
OpdsUserV2 opdsUserV2 = opdsUserDetails.getOpdsUserV2();
|
||||
BookLoreUserEntity entity = userRepository.findById(opdsUserV2.getUserId())
|
||||
.orElseThrow(() -> new AccessDeniedException("User not found"));
|
||||
|
||||
if (!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin()) {
|
||||
throw new AccessDeniedException("You are not allowed to access this resource");
|
||||
}
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
java.util.Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
|
||||
if (shelfId != null) {
|
||||
var shelf = shelfRepository.findById(shelfId).orElseThrow(() -> new AccessDeniedException("Shelf not found"));
|
||||
if (!shelf.getUser().getId().equals(user.getId()) && !isAdmin) {
|
||||
throw new AccessDeniedException("You are not allowed to access this shelf");
|
||||
}
|
||||
return bookQueryService.getAllBooksByShelfPage(shelfId, true, page, size);
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
if (!isAdmin && !libraryIds.contains(libraryId)) {
|
||||
throw new AccessDeniedException("You are not allowed to access this library");
|
||||
}
|
||||
return (queryParam != null && !queryParam.isBlank())
|
||||
? bookQueryService.searchBooksByMetadataInLibrariesPage(queryParam, java.util.Set.of(libraryId), page, size)
|
||||
: bookQueryService.getAllBooksByLibraryIdsPage(java.util.Set.of(libraryId), true, page, size, opdsUserV2.getUserId());
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return (queryParam != null && !queryParam.isBlank())
|
||||
? bookQueryService.searchBooksByMetadataPage(queryParam, page, size)
|
||||
: bookQueryService.getAllBooksPage(true, page, size);
|
||||
}
|
||||
|
||||
return (queryParam != null && !queryParam.isBlank())
|
||||
? bookQueryService.searchBooksByMetadataInLibrariesPage(queryParam, libraryIds, page, size)
|
||||
: bookQueryService.getAllBooksByLibraryIdsPage(libraryIds, true, page, size, opdsUserV2.getUserId());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user