Expose Magic Shelves through the OPDS feed so clients can access them (#1683)
This commit is contained in:
+1
-1
@@ -24,6 +24,6 @@ public class OpdsUserDetailsService implements UserDetailsService {
|
|||||||
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
|
OpdsUserV2Entity userV2 = opdsUserV2Repository.findByUsername(username)
|
||||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(username));
|
||||||
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
|
OpdsUserV2 mappedCredential = opdsUserV2Mapper.toDto(userV2);
|
||||||
return new OpdsUserDetails(mappedCredential, null);
|
return new OpdsUserDetails(mappedCredential);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-8
@@ -1,6 +1,5 @@
|
|||||||
package com.adityachandel.booklore.config.security.userdetails;
|
package com.adityachandel.booklore.config.security.userdetails;
|
||||||
|
|
||||||
import com.adityachandel.booklore.model.dto.OpdsUser;
|
|
||||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -15,20 +14,15 @@ import java.util.List;
|
|||||||
public class OpdsUserDetails implements UserDetails {
|
public class OpdsUserDetails implements UserDetails {
|
||||||
|
|
||||||
private final OpdsUserV2 opdsUserV2;
|
private final OpdsUserV2 opdsUserV2;
|
||||||
private final OpdsUser opdsUser;
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getUsername() {
|
public String getUsername() {
|
||||||
if (opdsUserV2 != null) return opdsUserV2.getUsername();
|
return opdsUserV2.getUsername();
|
||||||
if (opdsUser != null) return opdsUser.getUsername();
|
|
||||||
throw new IllegalStateException("No username available");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getPassword() {
|
public String getPassword() {
|
||||||
if (opdsUserV2 != null) return opdsUserV2.getPasswordHash();
|
return opdsUserV2.getPasswordHash();
|
||||||
if (opdsUser != null) return opdsUser.getPassword();
|
|
||||||
throw new IllegalStateException("No password available");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
+18
-16
@@ -38,8 +38,7 @@ public class OpdsController {
|
|||||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||||
})
|
})
|
||||||
@GetMapping("/{bookId}/download")
|
@GetMapping("/{bookId}/download")
|
||||||
public ResponseEntity<Resource> downloadBook(
|
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
|
||||||
return bookService.downloadBook(bookId);
|
return bookService.downloadBook(bookId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,8 +48,7 @@ public class OpdsController {
|
|||||||
@ApiResponse(responseCode = "404", description = "Book or cover not found")
|
@ApiResponse(responseCode = "404", description = "Book or cover not found")
|
||||||
})
|
})
|
||||||
@GetMapping("/{bookId}/cover")
|
@GetMapping("/{bookId}/cover")
|
||||||
public ResponseEntity<Resource> getBookCover(
|
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
|
||||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||||
String contentType = "image/jpeg";
|
String contentType = "image/jpeg";
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
@@ -62,8 +60,7 @@ public class OpdsController {
|
|||||||
@Operation(summary = "Get OPDS root catalog", description = "Retrieve the OPDS root navigation feed.")
|
@Operation(summary = "Get OPDS root catalog", description = "Retrieve the OPDS root navigation feed.")
|
||||||
@ApiResponse(responseCode = "200", description = "Root OPDS catalog returned successfully")
|
@ApiResponse(responseCode = "200", description = "Root OPDS catalog returned successfully")
|
||||||
@GetMapping(produces = OPDS_CATALOG_MEDIA_TYPE)
|
@GetMapping(produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getRootCatalog(
|
public ResponseEntity<String> getRootCatalog(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateRootNavigation(request);
|
String feed = opdsFeedService.generateRootNavigation(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||||
@@ -73,8 +70,7 @@ public class OpdsController {
|
|||||||
@Operation(summary = "Get OPDS libraries navigation", description = "Retrieve the OPDS libraries navigation feed.")
|
@Operation(summary = "Get OPDS libraries navigation", description = "Retrieve the OPDS libraries navigation feed.")
|
||||||
@ApiResponse(responseCode = "200", description = "Libraries navigation feed returned successfully")
|
@ApiResponse(responseCode = "200", description = "Libraries navigation feed returned successfully")
|
||||||
@GetMapping(value = "/libraries", produces = OPDS_CATALOG_MEDIA_TYPE)
|
@GetMapping(value = "/libraries", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getLibrariesNavigation(
|
public ResponseEntity<String> getLibrariesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateLibrariesNavigation(request);
|
String feed = opdsFeedService.generateLibrariesNavigation(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||||
@@ -84,19 +80,27 @@ public class OpdsController {
|
|||||||
@Operation(summary = "Get OPDS shelves navigation", description = "Retrieve the OPDS shelves navigation feed.")
|
@Operation(summary = "Get OPDS shelves navigation", description = "Retrieve the OPDS shelves navigation feed.")
|
||||||
@ApiResponse(responseCode = "200", description = "Shelves navigation feed returned successfully")
|
@ApiResponse(responseCode = "200", description = "Shelves navigation feed returned successfully")
|
||||||
@GetMapping(value = "/shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
@GetMapping(value = "/shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getShelvesNavigation(
|
public ResponseEntity<String> getShelvesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateShelvesNavigation(request);
|
String feed = opdsFeedService.generateShelvesNavigation(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||||
.body(feed);
|
.body(feed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "Get OPDS magic shelves navigation", description = "Retrieve the OPDS magic shelves navigation feed.")
|
||||||
|
@ApiResponse(responseCode = "200", description = "Magic shelves navigation feed returned successfully")
|
||||||
|
@GetMapping(value = "/magic-shelves", produces = OPDS_CATALOG_MEDIA_TYPE)
|
||||||
|
public ResponseEntity<String> getMagicShelvesNavigation(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
|
String feed = opdsFeedService.generateMagicShelvesNavigation(request);
|
||||||
|
return ResponseEntity.ok()
|
||||||
|
.contentType(MediaType.parseMediaType(OPDS_CATALOG_MEDIA_TYPE))
|
||||||
|
.body(feed);
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
|
@Operation(summary = "Get OPDS catalog feed", description = "Retrieve the OPDS acquisition catalog feed.")
|
||||||
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
|
@ApiResponse(responseCode = "200", description = "Catalog feed returned successfully")
|
||||||
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
@GetMapping(value = "/catalog", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getCatalog(
|
public ResponseEntity<String> getCatalog(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateCatalogFeed(request);
|
String feed = opdsFeedService.generateCatalogFeed(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||||
@@ -106,8 +110,7 @@ public class OpdsController {
|
|||||||
@Operation(summary = "Get recent books feed", description = "Retrieve the OPDS feed for recently added books.")
|
@Operation(summary = "Get recent books feed", description = "Retrieve the OPDS feed for recently added books.")
|
||||||
@ApiResponse(responseCode = "200", description = "Recent books feed returned successfully")
|
@ApiResponse(responseCode = "200", description = "Recent books feed returned successfully")
|
||||||
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
@GetMapping(value = "/recent", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getRecentBooks(
|
public ResponseEntity<String> getRecentBooks(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateRecentFeed(request);
|
String feed = opdsFeedService.generateRecentFeed(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||||
@@ -117,8 +120,7 @@ public class OpdsController {
|
|||||||
@Operation(summary = "Get surprise feed", description = "Retrieve the OPDS feed for surprise/random books.")
|
@Operation(summary = "Get surprise feed", description = "Retrieve the OPDS feed for surprise/random books.")
|
||||||
@ApiResponse(responseCode = "200", description = "Surprise feed returned successfully")
|
@ApiResponse(responseCode = "200", description = "Surprise feed returned successfully")
|
||||||
@GetMapping(value = "/surprise", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
@GetMapping(value = "/surprise", produces = OPDS_ACQUISITION_MEDIA_TYPE)
|
||||||
public ResponseEntity<String> getSurpriseFeed(
|
public ResponseEntity<String> getSurpriseFeed(@Parameter(hidden = true) HttpServletRequest request) {
|
||||||
@Parameter(hidden = true) HttpServletRequest request) {
|
|
||||||
String feed = opdsFeedService.generateSurpriseFeed(request);
|
String feed = opdsFeedService.generateSurpriseFeed(request);
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
.contentType(MediaType.parseMediaType(OPDS_ACQUISITION_MEDIA_TYPE))
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ public enum ApiError {
|
|||||||
INVALID_QUERY_PARAMETERS(HttpStatus.BAD_REQUEST, "Query parameters are required for the search."),
|
INVALID_QUERY_PARAMETERS(HttpStatus.BAD_REQUEST, "Query parameters are required for the search."),
|
||||||
SHELF_ALREADY_EXISTS(HttpStatus.CONFLICT, "Shelf already exists: %s"),
|
SHELF_ALREADY_EXISTS(HttpStatus.CONFLICT, "Shelf already exists: %s"),
|
||||||
SHELF_NOT_FOUND(HttpStatus.NOT_FOUND, "Shelf not found with ID: %d"),
|
SHELF_NOT_FOUND(HttpStatus.NOT_FOUND, "Shelf not found with ID: %d"),
|
||||||
|
MAGIC_SHELF_NOT_FOUND(HttpStatus.NOT_FOUND, "Magic shelf not found with ID: %s"),
|
||||||
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
|
SCHEDULE_REFRESH_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to schedule metadata refresh job. Error: %s"),
|
||||||
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
|
ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."),
|
||||||
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class GroupRule {
|
||||||
|
private String name;
|
||||||
|
private String type;
|
||||||
|
private JoinType join;
|
||||||
|
private List<Object> rules; // Can be either Rule or GroupRule
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
public enum JoinType {
|
||||||
|
@JsonProperty("and")
|
||||||
|
AND,
|
||||||
|
@JsonProperty("or")
|
||||||
|
OR
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
public class Rule {
|
||||||
|
private String type;
|
||||||
|
private RuleField field;
|
||||||
|
private RuleOperator operator;
|
||||||
|
private Object value;
|
||||||
|
private Object valueStart;
|
||||||
|
private Object valueEnd;
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
public enum RuleField {
|
||||||
|
@JsonProperty("library")
|
||||||
|
LIBRARY,
|
||||||
|
@JsonProperty("title")
|
||||||
|
TITLE,
|
||||||
|
@JsonProperty("subtitle")
|
||||||
|
SUBTITLE,
|
||||||
|
@JsonProperty("authors")
|
||||||
|
AUTHORS,
|
||||||
|
@JsonProperty("categories")
|
||||||
|
CATEGORIES,
|
||||||
|
@JsonProperty("publisher")
|
||||||
|
PUBLISHER,
|
||||||
|
@JsonProperty("publishedDate")
|
||||||
|
PUBLISHED_DATE,
|
||||||
|
@JsonProperty("seriesName")
|
||||||
|
SERIES_NAME,
|
||||||
|
@JsonProperty("seriesNumber")
|
||||||
|
SERIES_NUMBER,
|
||||||
|
@JsonProperty("seriesTotal")
|
||||||
|
SERIES_TOTAL,
|
||||||
|
@JsonProperty("pageCount")
|
||||||
|
PAGE_COUNT,
|
||||||
|
@JsonProperty("language")
|
||||||
|
LANGUAGE,
|
||||||
|
@JsonProperty("amazonRating")
|
||||||
|
AMAZON_RATING,
|
||||||
|
@JsonProperty("amazonReviewCount")
|
||||||
|
AMAZON_REVIEW_COUNT,
|
||||||
|
@JsonProperty("goodreadsRating")
|
||||||
|
GOODREADS_RATING,
|
||||||
|
@JsonProperty("goodreadsReviewCount")
|
||||||
|
GOODREADS_REVIEW_COUNT,
|
||||||
|
@JsonProperty("hardcoverRating")
|
||||||
|
HARDCOVER_RATING,
|
||||||
|
@JsonProperty("hardcoverReviewCount")
|
||||||
|
HARDCOVER_REVIEW_COUNT,
|
||||||
|
@JsonProperty("personalRating")
|
||||||
|
PERSONAL_RATING,
|
||||||
|
@JsonProperty("fileType")
|
||||||
|
FILE_TYPE,
|
||||||
|
@JsonProperty("fileSize")
|
||||||
|
FILE_SIZE,
|
||||||
|
@JsonProperty("readStatus")
|
||||||
|
READ_STATUS,
|
||||||
|
@JsonProperty("dateFinished")
|
||||||
|
DATE_FINISHED,
|
||||||
|
@JsonProperty("lastReadTime")
|
||||||
|
LAST_READ_TIME,
|
||||||
|
@JsonProperty("metadataScore")
|
||||||
|
METADATA_SCORE,
|
||||||
|
@JsonProperty("moods")
|
||||||
|
MOODS,
|
||||||
|
@JsonProperty("tags")
|
||||||
|
TAGS
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
public enum RuleOperator {
|
||||||
|
@JsonProperty("equals")
|
||||||
|
EQUALS,
|
||||||
|
@JsonProperty("not_equals")
|
||||||
|
NOT_EQUALS,
|
||||||
|
@JsonProperty("contains")
|
||||||
|
CONTAINS,
|
||||||
|
@JsonProperty("does_not_contain")
|
||||||
|
DOES_NOT_CONTAIN,
|
||||||
|
@JsonProperty("starts_with")
|
||||||
|
STARTS_WITH,
|
||||||
|
@JsonProperty("ends_with")
|
||||||
|
ENDS_WITH,
|
||||||
|
@JsonProperty("greater_than")
|
||||||
|
GREATER_THAN,
|
||||||
|
@JsonProperty("greater_than_equal_to")
|
||||||
|
GREATER_THAN_EQUAL_TO,
|
||||||
|
@JsonProperty("less_than")
|
||||||
|
LESS_THAN,
|
||||||
|
@JsonProperty("less_than_equal_to")
|
||||||
|
LESS_THAN_EQUAL_TO,
|
||||||
|
@JsonProperty("in_between")
|
||||||
|
IN_BETWEEN,
|
||||||
|
@JsonProperty("is_empty")
|
||||||
|
IS_EMPTY,
|
||||||
|
@JsonProperty("is_not_empty")
|
||||||
|
IS_NOT_EMPTY,
|
||||||
|
@JsonProperty("includes_any")
|
||||||
|
INCLUDES_ANY,
|
||||||
|
@JsonProperty("excludes_all")
|
||||||
|
EXCLUDES_ALL,
|
||||||
|
@JsonProperty("includes_all")
|
||||||
|
INCLUDES_ALL
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.model.entity;
|
|||||||
import com.adityachandel.booklore.convertor.BookRecommendationIdsListConverter;
|
import com.adityachandel.booklore.convertor.BookRecommendationIdsListConverter;
|
||||||
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
||||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
@@ -83,6 +82,9 @@ public class BookEntity {
|
|||||||
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||||
private List<BookAdditionalFileEntity> additionalFiles;
|
private List<BookAdditionalFileEntity> additionalFiles;
|
||||||
|
|
||||||
|
@OneToMany(mappedBy = "book", fetch = FetchType.LAZY)
|
||||||
|
private List<UserBookProgressEntity> userBookProgress;
|
||||||
|
|
||||||
public Path getFullFilePath() {
|
public Path getFullFilePath() {
|
||||||
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
||||||
throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name");
|
throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name");
|
||||||
|
|||||||
+449
@@ -0,0 +1,449 @@
|
|||||||
|
package com.adityachandel.booklore.service;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.dto.GroupRule;
|
||||||
|
import com.adityachandel.booklore.model.dto.Rule;
|
||||||
|
import com.adityachandel.booklore.model.dto.RuleField;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import jakarta.persistence.criteria.*;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.function.BiFunction;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class BookRuleEvaluatorService {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public Specification<BookEntity> toSpecification(GroupRule groupRule, Long userId) {
|
||||||
|
return (root, query, cb) -> {
|
||||||
|
Join<BookEntity, UserBookProgressEntity> progressJoin = root.join("userBookProgress", JoinType.LEFT);
|
||||||
|
|
||||||
|
Predicate userPredicate = cb.or(
|
||||||
|
cb.isNull(progressJoin.get("user").get("id")),
|
||||||
|
cb.equal(progressJoin.get("user").get("id"), userId)
|
||||||
|
);
|
||||||
|
|
||||||
|
Predicate rulePredicate = buildPredicate(groupRule, cb, root, progressJoin);
|
||||||
|
|
||||||
|
return cb.and(userPredicate, rulePredicate);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildPredicate(GroupRule group, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
if (group.getRules() == null || group.getRules().isEmpty()) {
|
||||||
|
return cb.conjunction();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Predicate> predicates = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Object ruleObj : group.getRules()) {
|
||||||
|
if (ruleObj == null) continue;
|
||||||
|
|
||||||
|
Map<String, Object> ruleMap = objectMapper.convertValue(ruleObj, new TypeReference<>() {
|
||||||
|
});
|
||||||
|
String type = (String) ruleMap.get("type");
|
||||||
|
|
||||||
|
if ("group".equals(type)) {
|
||||||
|
GroupRule subGroup = objectMapper.convertValue(ruleObj, GroupRule.class);
|
||||||
|
predicates.add(buildPredicate(subGroup, cb, root, progressJoin));
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
Rule rule = objectMapper.convertValue(ruleObj, Rule.class);
|
||||||
|
Predicate rulePredicate = buildRulePredicate(rule, cb, root, progressJoin);
|
||||||
|
if (rulePredicate != null) {
|
||||||
|
predicates.add(rulePredicate);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to parse rule: {}, error: {}", ruleObj, e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (predicates.isEmpty()) {
|
||||||
|
return cb.conjunction();
|
||||||
|
}
|
||||||
|
|
||||||
|
return group.getJoin() == com.adityachandel.booklore.model.dto.JoinType.AND
|
||||||
|
? cb.and(predicates.toArray(new Predicate[0]))
|
||||||
|
: cb.or(predicates.toArray(new Predicate[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildRulePredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
if (rule.getField() == null || rule.getOperator() == null) return null;
|
||||||
|
|
||||||
|
return switch (rule.getOperator()) {
|
||||||
|
case EQUALS -> buildEquals(rule, cb, root, progressJoin);
|
||||||
|
case NOT_EQUALS -> buildNotEquals(rule, cb, root, progressJoin);
|
||||||
|
case CONTAINS -> buildContains(rule, cb, root, progressJoin);
|
||||||
|
case DOES_NOT_CONTAIN -> cb.not(buildContains(rule, cb, root, progressJoin));
|
||||||
|
case STARTS_WITH -> buildStartsWith(rule, cb, root, progressJoin);
|
||||||
|
case ENDS_WITH -> buildEndsWith(rule, cb, root, progressJoin);
|
||||||
|
case GREATER_THAN -> buildGreaterThan(rule, cb, root, progressJoin);
|
||||||
|
case GREATER_THAN_EQUAL_TO -> buildGreaterThanEqual(rule, cb, root, progressJoin);
|
||||||
|
case LESS_THAN -> buildLessThan(rule, cb, root, progressJoin);
|
||||||
|
case LESS_THAN_EQUAL_TO -> buildLessThanEqual(rule, cb, root, progressJoin);
|
||||||
|
case IN_BETWEEN -> buildInBetween(rule, cb, root, progressJoin);
|
||||||
|
case IS_EMPTY -> buildIsEmpty(rule, cb, root, progressJoin);
|
||||||
|
case IS_NOT_EMPTY -> cb.not(buildIsEmpty(rule, cb, root, progressJoin));
|
||||||
|
case INCLUDES_ANY -> buildIncludesAny(rule, cb, root, progressJoin);
|
||||||
|
case EXCLUDES_ALL -> buildExcludesAll(rule, cb, root, progressJoin);
|
||||||
|
case INCLUDES_ALL -> buildIncludesAll(rule, cb, root, progressJoin);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
List<String> ruleList = toStringList(rule.getValue());
|
||||||
|
|
||||||
|
if (isArrayField(rule.getField())) {
|
||||||
|
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||||
|
if (field == null) return cb.conjunction();
|
||||||
|
|
||||||
|
Object value = normalizeValue(rule.getValue(), rule.getField());
|
||||||
|
|
||||||
|
if (value instanceof LocalDateTime) {
|
||||||
|
return cb.equal(field, value);
|
||||||
|
} else if (rule.getField() == RuleField.READ_STATUS) {
|
||||||
|
if ("UNSET".equals(value.toString())) {
|
||||||
|
return cb.isNull(field);
|
||||||
|
}
|
||||||
|
return cb.equal(field, value.toString());
|
||||||
|
} else if (value instanceof Number) {
|
||||||
|
return cb.equal(field, value);
|
||||||
|
}
|
||||||
|
return cb.equal(cb.lower(field.as(String.class)), value.toString().toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildNotEquals(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return cb.not(buildEquals(rule, cb, root, progressJoin));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildContains(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||||
|
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||||
|
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal) + "%"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildStartsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||||
|
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||||
|
nameField -> cb.like(cb.lower(nameField), escapeLike(ruleVal) + "%"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildEndsWith(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
String ruleVal = rule.getValue().toString().toLowerCase();
|
||||||
|
return buildStringPredicate(rule.getField(), root, progressJoin, cb,
|
||||||
|
nameField -> cb.like(cb.lower(nameField), "%" + escapeLike(ruleVal)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildStringPredicate(RuleField field, Root<BookEntity> root,
|
||||||
|
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||||
|
CriteriaBuilder cb,
|
||||||
|
java.util.function.Function<Expression<String>, Predicate> predicateBuilder) {
|
||||||
|
if (isArrayField(field)) {
|
||||||
|
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||||
|
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||||
|
return predicateBuilder.apply(nameField);
|
||||||
|
}
|
||||||
|
|
||||||
|
Expression<?> fieldExpr = getFieldExpression(field, cb, root, progressJoin);
|
||||||
|
if (fieldExpr == null) return cb.conjunction();
|
||||||
|
|
||||||
|
return predicateBuilder.apply(fieldExpr.as(String.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildGreaterThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||||
|
(field, dateValue) -> cb.greaterThan(field.as(LocalDateTime.class), dateValue),
|
||||||
|
(field, numValue) -> cb.gt(field.as(Number.class), numValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildGreaterThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||||
|
(field, dateValue) -> cb.greaterThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||||
|
(field, numValue) -> cb.ge(field.as(Number.class), numValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildLessThan(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||||
|
(field, dateValue) -> cb.lessThan(field.as(LocalDateTime.class), dateValue),
|
||||||
|
(field, numValue) -> cb.lt(field.as(Number.class), numValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildLessThanEqual(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return buildComparisonPredicate(rule, cb, root, progressJoin,
|
||||||
|
(field, dateValue) -> cb.lessThanOrEqualTo(field.as(LocalDateTime.class), dateValue),
|
||||||
|
(field, numValue) -> cb.le(field.as(Number.class), numValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildComparisonPredicate(Rule rule, CriteriaBuilder cb, Root<BookEntity> root,
|
||||||
|
Join<BookEntity, UserBookProgressEntity> progressJoin,
|
||||||
|
BiFunction<Expression<?>, LocalDateTime, Predicate> dateComparator,
|
||||||
|
BiFunction<Expression<?>, Double, Predicate> numberComparator) {
|
||||||
|
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||||
|
if (field == null) return cb.conjunction();
|
||||||
|
|
||||||
|
Object value = normalizeValue(rule.getValue(), rule.getField());
|
||||||
|
|
||||||
|
if (value instanceof LocalDateTime) {
|
||||||
|
return dateComparator.apply(field, (LocalDateTime) value);
|
||||||
|
}
|
||||||
|
return numberComparator.apply(field, ((Number) value).doubleValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildInBetween(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||||
|
if (field == null) return cb.conjunction();
|
||||||
|
|
||||||
|
Object start = normalizeValue(rule.getValueStart(), rule.getField());
|
||||||
|
Object end = normalizeValue(rule.getValueEnd(), rule.getField());
|
||||||
|
|
||||||
|
if (start == null || end == null) return cb.conjunction();
|
||||||
|
|
||||||
|
if (start instanceof LocalDateTime && end instanceof LocalDateTime) {
|
||||||
|
return cb.between(field.as(LocalDateTime.class), (LocalDateTime) start, (LocalDateTime) end);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(start instanceof Number) || !(end instanceof Number)) {
|
||||||
|
return cb.conjunction();
|
||||||
|
}
|
||||||
|
|
||||||
|
return cb.between(field.as(Double.class), ((Number) start).doubleValue(), ((Number) end).doubleValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildIsEmpty(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
if (isArrayField(rule.getField())) {
|
||||||
|
Subquery<Long> subquery = cb.createQuery().subquery(Long.class);
|
||||||
|
Root<BookEntity> subRoot = subquery.from(BookEntity.class);
|
||||||
|
|
||||||
|
Join<Object, Object> metadataJoin = subRoot.join("metadata", JoinType.INNER);
|
||||||
|
joinArrayField(rule.getField(), metadataJoin);
|
||||||
|
|
||||||
|
subquery.select(cb.literal(1L)).where(cb.equal(subRoot.get("id"), root.get("id")));
|
||||||
|
|
||||||
|
return cb.not(cb.exists(subquery));
|
||||||
|
}
|
||||||
|
|
||||||
|
Expression<?> field = getFieldExpression(rule.getField(), cb, root, progressJoin);
|
||||||
|
if (field == null) return cb.conjunction();
|
||||||
|
|
||||||
|
return cb.or(cb.isNull(field), cb.equal(cb.trim(field.as(String.class)), ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildIncludesAny(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
List<String> ruleList = toStringList(rule.getValue());
|
||||||
|
|
||||||
|
if (isArrayField(rule.getField())) {
|
||||||
|
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildExcludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
List<String> ruleList = toStringList(rule.getValue());
|
||||||
|
|
||||||
|
if (isArrayField(rule.getField())) {
|
||||||
|
return cb.not(buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return cb.not(buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildIncludesAll(Rule rule, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
List<String> ruleList = toStringList(rule.getValue());
|
||||||
|
|
||||||
|
if (isArrayField(rule.getField())) {
|
||||||
|
return buildArrayFieldPredicate(rule.getField(), ruleList, cb, root, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildFieldInPredicate(rule.getField(), field -> field, ruleList, cb, progressJoin);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildFieldInPredicate(RuleField ruleField,
|
||||||
|
java.util.function.Function<Expression<?>, Expression<?>> fieldTransformer,
|
||||||
|
List<String> ruleList,
|
||||||
|
CriteriaBuilder cb,
|
||||||
|
Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
Expression<?> field = fieldTransformer.apply(getFieldExpression(ruleField, cb, null, progressJoin));
|
||||||
|
if (field == null) return cb.conjunction();
|
||||||
|
|
||||||
|
if (ruleField == RuleField.READ_STATUS) {
|
||||||
|
boolean hasUnset = ruleList.stream().anyMatch("UNSET"::equals);
|
||||||
|
List<String> nonUnsetValues = ruleList.stream()
|
||||||
|
.filter(v -> !"UNSET".equals(v))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (hasUnset && !nonUnsetValues.isEmpty()) {
|
||||||
|
return cb.or(
|
||||||
|
cb.isNull(field),
|
||||||
|
field.as(String.class).in(nonUnsetValues)
|
||||||
|
);
|
||||||
|
} else if (hasUnset) {
|
||||||
|
return cb.isNull(field);
|
||||||
|
} else {
|
||||||
|
return field.as(String.class).in(nonUnsetValues);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> lowerList = ruleList.stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||||
|
return cb.lower(field.as(String.class)).in(lowerList);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Expression<?> getFieldExpression(RuleField field, CriteriaBuilder cb, Root<BookEntity> root, Join<BookEntity, UserBookProgressEntity> progressJoin) {
|
||||||
|
return switch (field) {
|
||||||
|
case LIBRARY -> root.get("library").get("id");
|
||||||
|
case READ_STATUS -> progressJoin.get("readStatus");
|
||||||
|
case DATE_FINISHED -> progressJoin.get("dateFinished");
|
||||||
|
case LAST_READ_TIME -> progressJoin.get("lastReadTime");
|
||||||
|
case FILE_SIZE -> root.get("fileSizeKb");
|
||||||
|
case METADATA_SCORE -> root.get("metadataMatchScore");
|
||||||
|
case TITLE -> root.get("metadata").get("title");
|
||||||
|
case SUBTITLE -> root.get("metadata").get("subtitle");
|
||||||
|
case PUBLISHER -> root.get("metadata").get("publisher");
|
||||||
|
case PUBLISHED_DATE -> root.get("metadata").get("publishedDate");
|
||||||
|
case PERSONAL_RATING -> root.get("metadata").get("personalRating");
|
||||||
|
case PAGE_COUNT -> root.get("metadata").get("pageCount");
|
||||||
|
case LANGUAGE -> root.get("metadata").get("language");
|
||||||
|
case SERIES_NAME -> root.get("metadata").get("seriesName");
|
||||||
|
case SERIES_NUMBER -> root.get("metadata").get("seriesNumber");
|
||||||
|
case SERIES_TOTAL -> root.get("metadata").get("seriesTotal");
|
||||||
|
case AMAZON_RATING -> root.get("metadata").get("amazonRating");
|
||||||
|
case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount");
|
||||||
|
case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating");
|
||||||
|
case GOODREADS_REVIEW_COUNT -> root.get("metadata").get("goodreadsReviewCount");
|
||||||
|
case HARDCOVER_RATING -> root.get("metadata").get("hardcoverRating");
|
||||||
|
case HARDCOVER_REVIEW_COUNT -> root.get("metadata").get("hardcoverReviewCount");
|
||||||
|
case FILE_TYPE -> cb.function("SUBSTRING_INDEX", String.class,
|
||||||
|
root.get("fileName"), cb.literal("."), cb.literal(-1));
|
||||||
|
default -> null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isArrayField(RuleField field) {
|
||||||
|
return field == RuleField.AUTHORS || field == RuleField.CATEGORIES ||
|
||||||
|
field == RuleField.MOODS || field == RuleField.TAGS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Join<?, ?> createArrayFieldJoin(RuleField field, Root<BookEntity> root) {
|
||||||
|
Join<Object, Object> metadataJoin = root.join("metadata", JoinType.INNER);
|
||||||
|
return joinArrayField(field, metadataJoin);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Expression<String> getArrayFieldNameExpression(RuleField field, Join<?, ?> arrayJoin) {
|
||||||
|
return arrayJoin.get("name");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Join<?, ?> joinArrayField(RuleField field, Join<Object, Object> metadataJoin) {
|
||||||
|
return switch (field) {
|
||||||
|
case AUTHORS -> metadataJoin.join("authors", JoinType.INNER);
|
||||||
|
case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER);
|
||||||
|
case MOODS -> metadataJoin.join("moods", JoinType.INNER);
|
||||||
|
case TAGS -> metadataJoin.join("tags", JoinType.INNER);
|
||||||
|
default -> throw new IllegalArgumentException("Not an array field: " + field);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private Predicate buildArrayFieldPredicate(RuleField field, List<String> values, CriteriaBuilder cb, Root<BookEntity> root, boolean includesAll) {
|
||||||
|
if (values.isEmpty()) {
|
||||||
|
return cb.conjunction();
|
||||||
|
}
|
||||||
|
if (includesAll) {
|
||||||
|
List<Predicate> predicates = values.stream()
|
||||||
|
.map(value -> {
|
||||||
|
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||||
|
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||||
|
return cb.equal(cb.lower(nameField), value.toLowerCase());
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return cb.and(predicates.toArray(new Predicate[0]));
|
||||||
|
} else {
|
||||||
|
Join<?, ?> arrayJoin = createArrayFieldJoin(field, root);
|
||||||
|
Expression<String> nameField = getArrayFieldNameExpression(field, arrayJoin);
|
||||||
|
|
||||||
|
List<String> lowerValues = values.stream()
|
||||||
|
.map(String::toLowerCase)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
return cb.lower(nameField).in(lowerValues);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Object normalizeValue(Object value, RuleField field) {
|
||||||
|
if (value == null) return null;
|
||||||
|
|
||||||
|
if (field == RuleField.PUBLISHED_DATE) {
|
||||||
|
return parseDate(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (field == RuleField.DATE_FINISHED || field == RuleField.LAST_READ_TIME) {
|
||||||
|
LocalDateTime parsed = parseDate(value);
|
||||||
|
if (parsed != null) {
|
||||||
|
return parsed.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (field == RuleField.READ_STATUS) {
|
||||||
|
return value.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.toString().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalDateTime parseDate(Object value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
if (value instanceof LocalDateTime) return (LocalDateTime) value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
return LocalDateTime.parse(value.toString(), DateTimeFormatter.ISO_DATE_TIME);
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
return LocalDate.parse(value.toString()).atStartOfDay();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> toStringList(Object value) {
|
||||||
|
if (value == null) return Collections.emptyList();
|
||||||
|
if (value instanceof List) {
|
||||||
|
return ((List<?>) value).stream()
|
||||||
|
.map(Object::toString)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
return Collections.singletonList(value.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String escapeLike(String value) {
|
||||||
|
return value.replace("\\", "\\\\")
|
||||||
|
.replace("%", "\\%")
|
||||||
|
.replace("_", "\\_");
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
-10
@@ -15,19 +15,26 @@ import java.util.stream.Collectors;
|
|||||||
@Service
|
@Service
|
||||||
public class MagicShelfService {
|
public class MagicShelfService {
|
||||||
|
|
||||||
private final MagicShelfRepository repository;
|
private final MagicShelfRepository magicShelfRepository;
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
|
||||||
public List<MagicShelf> getUserShelves() {
|
public List<MagicShelf> getUserShelves() {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
|
return getShelvesForUser(userId);
|
||||||
|
}
|
||||||
|
|
||||||
List<MagicShelf> shelves = repository.findAllByUserId(userId).stream()
|
public List<MagicShelf> getUserShelvesForOpds(Long userId) {
|
||||||
|
return getShelvesForUser(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<MagicShelf> getShelvesForUser(Long userId) {
|
||||||
|
List<MagicShelf> shelves = magicShelfRepository.findAllByUserId(userId).stream()
|
||||||
.map(this::toDto)
|
.map(this::toDto)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList();
|
List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList();
|
||||||
|
|
||||||
List<MagicShelf> publicShelves = repository.findAllByIsPublicIsTrue().stream()
|
List<MagicShelf> publicShelves = magicShelfRepository.findAllByIsPublicIsTrue().stream()
|
||||||
.map(this::toDto)
|
.map(this::toDto)
|
||||||
.filter(shelf -> !userShelfIds.contains(shelf.getId()))
|
.filter(shelf -> !userShelfIds.contains(shelf.getId()))
|
||||||
.toList();
|
.toList();
|
||||||
@@ -40,7 +47,7 @@ public class MagicShelfService {
|
|||||||
public MagicShelf createOrUpdateShelf(MagicShelf dto) {
|
public MagicShelf createOrUpdateShelf(MagicShelf dto) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
if (dto.getId() != null) {
|
if (dto.getId() != null) {
|
||||||
MagicShelfEntity existing = repository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
MagicShelfEntity existing = magicShelfRepository.findById(dto.getId()).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||||
if (!existing.getUserId().equals(userId)) {
|
if (!existing.getUserId().equals(userId)) {
|
||||||
throw new SecurityException("You are not authorized to update this shelf");
|
throw new SecurityException("You are not authorized to update this shelf");
|
||||||
}
|
}
|
||||||
@@ -51,22 +58,22 @@ public class MagicShelfService {
|
|||||||
existing.setIcon(dto.getIcon());
|
existing.setIcon(dto.getIcon());
|
||||||
existing.setFilterJson(dto.getFilterJson());
|
existing.setFilterJson(dto.getFilterJson());
|
||||||
existing.setPublic(dto.getIsPublic());
|
existing.setPublic(dto.getIsPublic());
|
||||||
return toDto(repository.save(existing));
|
return toDto(magicShelfRepository.save(existing));
|
||||||
}
|
}
|
||||||
if (repository.existsByUserIdAndName(userId, dto.getName())) {
|
if (magicShelfRepository.existsByUserIdAndName(userId, dto.getName())) {
|
||||||
throw new IllegalArgumentException("A shelf with the same name already exists for this user.");
|
throw new IllegalArgumentException("A shelf with the same name already exists for this user.");
|
||||||
}
|
}
|
||||||
return toDto(repository.save(toEntity(dto, userId)));
|
return toDto(magicShelfRepository.save(toEntity(dto, userId)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void deleteShelf(Long id) {
|
public void deleteShelf(Long id) {
|
||||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||||
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
MagicShelfEntity shelf = magicShelfRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||||
if (!shelf.getUserId().equals(userId)) {
|
if (!shelf.getUserId().equals(userId)) {
|
||||||
throw new SecurityException("You are not authorized to delete this shelf");
|
throw new SecurityException("You are not authorized to delete this shelf");
|
||||||
}
|
}
|
||||||
repository.deleteById(id);
|
magicShelfRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
private MagicShelf toDto(MagicShelfEntity entity) {
|
private MagicShelf toDto(MagicShelfEntity entity) {
|
||||||
@@ -91,7 +98,7 @@ public class MagicShelfService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public MagicShelf getShelf(Long id) {
|
public MagicShelf getShelf(Long id) {
|
||||||
MagicShelfEntity shelf = repository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
MagicShelfEntity shelf = magicShelfRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("Shelf not found"));
|
||||||
return toDto(shelf);
|
return toDto(shelf);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+122
@@ -0,0 +1,122 @@
|
|||||||
|
package com.adityachandel.booklore.service.opds;
|
||||||
|
|
||||||
|
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.Book;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||||
|
import com.adityachandel.booklore.model.dto.GroupRule;
|
||||||
|
import com.adityachandel.booklore.model.dto.Library;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.MagicShelfEntity;
|
||||||
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
|
import com.adityachandel.booklore.repository.MagicShelfRepository;
|
||||||
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
|
import com.adityachandel.booklore.service.BookRuleEvaluatorService;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.PageRequest;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Service
|
||||||
|
public class MagicShelfBookService {
|
||||||
|
|
||||||
|
private final MagicShelfRepository magicShelfRepository;
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
private final BookMapper bookMapper;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||||
|
private final BookRuleEvaluatorService ruleEvaluatorService;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public Page<Book> getBooksByMagicShelfId(Long userId, Long magicShelfId, int page, int size) {
|
||||||
|
MagicShelfEntity shelf = validateMagicShelfAccess(userId, magicShelfId);
|
||||||
|
try {
|
||||||
|
GroupRule groupRule = objectMapper.readValue(shelf.getFilterJson(), GroupRule.class);
|
||||||
|
Specification<BookEntity> specification = ruleEvaluatorService.toSpecification(groupRule, userId);
|
||||||
|
specification = specification.and(createLibraryFilterSpecification(userId));
|
||||||
|
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||||
|
|
||||||
|
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
|
||||||
|
|
||||||
|
return booksPage.map(bookMapper::toBook).map(book -> filterBook(book, userId));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to parse or execute magic shelf rules", e);
|
||||||
|
throw new RuntimeException("Failed to parse or execute magic shelf rules: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMagicShelfName(Long magicShelfId) {
|
||||||
|
return magicShelfRepository.findById(magicShelfId)
|
||||||
|
.map(s -> s.getName() + " - Magic Shelf")
|
||||||
|
.orElse("Magic Shelf Books");
|
||||||
|
}
|
||||||
|
|
||||||
|
private MagicShelfEntity validateMagicShelfAccess(Long userId, Long magicShelfId) {
|
||||||
|
MagicShelfEntity shelf = magicShelfRepository.findById(magicShelfId)
|
||||||
|
.orElseThrow(() -> ApiError.MAGIC_SHELF_NOT_FOUND.createException(magicShelfId));
|
||||||
|
|
||||||
|
if (userId == null) {
|
||||||
|
if (!shelf.isPublic()) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
|
||||||
|
}
|
||||||
|
return shelf;
|
||||||
|
}
|
||||||
|
|
||||||
|
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||||
|
|
||||||
|
if (entity.getPermissions() == null ||
|
||||||
|
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean isOwner = shelf.getUserId().equals(userId);
|
||||||
|
boolean isPublic = shelf.isPublic();
|
||||||
|
boolean isAdmin = entity.getPermissions().isPermissionAdmin();
|
||||||
|
|
||||||
|
if (!isOwner && !isPublic && !isAdmin) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("You are not allowed to access this magic shelf");
|
||||||
|
}
|
||||||
|
|
||||||
|
return shelf;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Specification<BookEntity> createLibraryFilterSpecification(Long userId) {
|
||||||
|
return (root, query, cb) -> {
|
||||||
|
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 cb.conjunction();
|
||||||
|
}
|
||||||
|
|
||||||
|
Set<Long> userLibraryIds = user.getAssignedLibraries().stream()
|
||||||
|
.map(Library::getId)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
return root.get("library").get("id").in(userLibraryIds);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
-89
@@ -1,6 +1,5 @@
|
|||||||
package com.adityachandel.booklore.service.opds;
|
package com.adityachandel.booklore.service.opds;
|
||||||
|
|
||||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
|
||||||
import com.adityachandel.booklore.exception.ApiError;
|
import com.adityachandel.booklore.exception.ApiError;
|
||||||
import com.adityachandel.booklore.mapper.BookMapper;
|
import com.adityachandel.booklore.mapper.BookMapper;
|
||||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||||
@@ -36,17 +35,11 @@ public class OpdsBookService {
|
|||||||
private final ShelfRepository shelfRepository;
|
private final ShelfRepository shelfRepository;
|
||||||
private final LibraryService libraryService;
|
private final LibraryService libraryService;
|
||||||
|
|
||||||
public List<Library> getAccessibleLibraries(OpdsUserDetails details) {
|
public List<Library> getAccessibleLibraries(Long userId) {
|
||||||
if (details == null || details.getOpdsUserV2() == null) {
|
if (userId == null) {
|
||||||
try {
|
|
||||||
return libraryService.getAllLibraries();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Failed to get all libraries", e);
|
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
Long userId = details.getOpdsUserV2().getUserId();
|
|
||||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||||
@@ -58,24 +51,57 @@ public class OpdsBookService {
|
|||||||
return user.getAssignedLibraries();
|
return user.getAssignedLibraries();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Page<Book> getBooksPage(OpdsUserDetails details, String query, Long libraryId, Long shelfId, int page, int size) {
|
public Page<Book> getBooksPage(Long userId, String query, Long libraryId, Long shelfId, int page, int size) {
|
||||||
OpdsUser opdsUser = details.getOpdsUser();
|
if (userId == null) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("Authentication required");
|
||||||
if (opdsUser != null) {
|
|
||||||
return getBooksPageForLegacyUser(query, libraryId, shelfId, page, size);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return getBooksPageForV2User(details.getOpdsUserV2(), query, libraryId, shelfId, page, size);
|
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||||
|
|
||||||
|
if (entity.getPermissions() == null ||
|
||||||
|
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
||||||
}
|
}
|
||||||
|
|
||||||
public Page<Book> getRecentBooksPage(OpdsUserDetails details, int page, int size) {
|
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||||
if (details == null || details.getOpdsUser() != null) {
|
boolean isAdmin = user.getPermissions().isAdmin();
|
||||||
return getRecentBooksPageInternal(page, size);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
OpdsUserV2 v2 = details.getOpdsUserV2();
|
if (libraryId != null) {
|
||||||
BookLoreUserEntity entity = userRepository.findById(v2.getUserId())
|
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(v2.getUserId()));
|
Page<Book> books = query != null && !query.isBlank()
|
||||||
|
? searchByMetadataInLibrariesPageInternal(query, Set.of(libraryId), page, size)
|
||||||
|
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||||
|
return applyBookFilters(books, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
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, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<Book> getRecentBooksPage(Long userId, int page, int size) {
|
||||||
|
if (userId == null) {
|
||||||
|
throw ApiError.FORBIDDEN.createException("Authentication required");
|
||||||
|
}
|
||||||
|
|
||||||
|
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||||
|
|
||||||
if (user.getPermissions().isAdmin()) {
|
if (user.getPermissions().isAdmin()) {
|
||||||
@@ -87,7 +113,7 @@ public class OpdsBookService {
|
|||||||
.collect(Collectors.toSet());
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size);
|
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size);
|
||||||
return applyBookFilters(books, v2.getUserId());
|
return applyBookFilters(books, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getLibraryName(Long libraryId) {
|
public String getLibraryName(Long libraryId) {
|
||||||
@@ -114,58 +140,21 @@ public class OpdsBookService {
|
|||||||
return shelfRepository.findByUserId(userId);
|
return shelfRepository.findByUserId(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Page<Book> getBooksPageForLegacyUser(String query, Long libraryId, Long shelfId, int page, int size) {
|
public List<Book> getRandomBooks(Long userId, int count) {
|
||||||
if (shelfId != null) {
|
List<Library> accessibleLibraries = getAccessibleLibraries(userId);
|
||||||
return getBooksByShelfIdPageInternal(shelfId, page, size);
|
if (accessibleLibraries == null || accessibleLibraries.isEmpty()) {
|
||||||
}
|
return List.of();
|
||||||
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) {
|
List<Long> libraryIds = accessibleLibraries.stream().map(Library::getId).toList();
|
||||||
BookLoreUserEntity entity = userRepository.findById(opdsUserV2.getUserId())
|
List<Long> ids = bookOpdsRepository.findRandomBookIdsByLibraryIds(libraryIds);
|
||||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(opdsUserV2.getUserId()));
|
|
||||||
|
|
||||||
if (entity.getPermissions() == null ||
|
if (ids.isEmpty()) {
|
||||||
(!entity.getPermissions().isPermissionAccessOpds() && !entity.getPermissions().isPermissionAdmin())) {
|
return List.of();
|
||||||
throw ApiError.FORBIDDEN.createException("You are not allowed to access this resource");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||||
boolean isAdmin = user.getPermissions().isAdmin();
|
return books.stream().map(bookMapper::toBook).toList();
|
||||||
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) {
|
private Page<Book> getAllBooksPageInternal(int page, int size) {
|
||||||
@@ -294,24 +283,4 @@ public class OpdsBookService {
|
|||||||
}
|
}
|
||||||
return dto;
|
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();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-15
@@ -4,6 +4,8 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
|||||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||||
import com.adityachandel.booklore.model.dto.Book;
|
import com.adityachandel.booklore.model.dto.Book;
|
||||||
import com.adityachandel.booklore.model.dto.Library;
|
import com.adityachandel.booklore.model.dto.Library;
|
||||||
|
import com.adityachandel.booklore.model.dto.MagicShelf;
|
||||||
|
import com.adityachandel.booklore.service.MagicShelfService;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -23,6 +25,8 @@ public class OpdsFeedService {
|
|||||||
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
private final OpdsBookService opdsBookService;
|
private final OpdsBookService opdsBookService;
|
||||||
|
private final MagicShelfService magicShelfService;
|
||||||
|
private final MagicShelfBookService magicShelfBookService;
|
||||||
|
|
||||||
public String generateRootNavigation(HttpServletRequest request) {
|
public String generateRootNavigation(HttpServletRequest request) {
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
@@ -76,6 +80,16 @@ public class OpdsFeedService {
|
|||||||
</entry>
|
</entry>
|
||||||
""".formatted(now()));
|
""".formatted(now()));
|
||||||
|
|
||||||
|
feed.append("""
|
||||||
|
<entry>
|
||||||
|
<title>Magic Shelves</title>
|
||||||
|
<id>urn:booklore:navigation:magic-shelves</id>
|
||||||
|
<updated>%s</updated>
|
||||||
|
<link rel="subsection" href="/api/v1/opds/magic-shelves" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
|
||||||
|
<content type="text">Browse your smart, dynamic shelves</content>
|
||||||
|
</entry>
|
||||||
|
""".formatted(now()));
|
||||||
|
|
||||||
feed.append("""
|
feed.append("""
|
||||||
<entry>
|
<entry>
|
||||||
<title>Surprise Me</title>
|
<title>Surprise Me</title>
|
||||||
@@ -91,8 +105,8 @@ public class OpdsFeedService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String generateLibrariesNavigation(HttpServletRequest request) {
|
public String generateLibrariesNavigation(HttpServletRequest request) {
|
||||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
Long userId = getUserId();
|
||||||
List<Library> libraries = opdsBookService.getAccessibleLibraries(details);
|
List<Library> libraries = opdsBookService.getAccessibleLibraries(userId);
|
||||||
|
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -128,7 +142,7 @@ public class OpdsFeedService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String generateShelvesNavigation(HttpServletRequest request) {
|
public String generateShelvesNavigation(HttpServletRequest request) {
|
||||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
Long userId = getUserId();
|
||||||
|
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -141,8 +155,7 @@ public class OpdsFeedService {
|
|||||||
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
<link rel="search" type="application/opensearchdescription+xml" title="Search" href="/api/v1/opds/search.opds"/>
|
||||||
""".formatted(now()));
|
""".formatted(now()));
|
||||||
|
|
||||||
if (details != null && details.getOpdsUserV2() != null) {
|
if (userId != null) {
|
||||||
Long userId = details.getOpdsUserV2().getUserId();
|
|
||||||
var shelves = opdsBookService.getUserShelves(userId);
|
var shelves = opdsBookService.getUserShelves(userId);
|
||||||
|
|
||||||
if (shelves != null) {
|
if (shelves != null) {
|
||||||
@@ -169,18 +182,66 @@ public class OpdsFeedService {
|
|||||||
return feed.toString();
|
return feed.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String generateMagicShelvesNavigation(HttpServletRequest request) {
|
||||||
|
Long userId = getUserId();
|
||||||
|
|
||||||
|
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:magic-shelves</id>
|
||||||
|
<title>Magic Shelves</title>
|
||||||
|
<updated>%s</updated>
|
||||||
|
<link rel="self" href="/api/v1/opds/magic-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 (userId != null) {
|
||||||
|
var magicShelves = magicShelfService.getUserShelvesForOpds(userId);
|
||||||
|
|
||||||
|
if (magicShelves != null) {
|
||||||
|
for (var shelf : magicShelves) {
|
||||||
|
feed.append("""
|
||||||
|
<entry>
|
||||||
|
<title>%s</title>
|
||||||
|
<id>urn:booklore:magic-shelf:%d</id>
|
||||||
|
<updated>%s</updated>
|
||||||
|
<link rel="subsection" href="%s" type="application/atom+xml;profile=opds-catalog;kind=acquisition"/>
|
||||||
|
<content type="text">Smart, dynamic shelf collection</content>
|
||||||
|
</entry>
|
||||||
|
""".formatted(
|
||||||
|
escapeXml(shelf.getName()),
|
||||||
|
shelf.getId(),
|
||||||
|
now(),
|
||||||
|
escapeXml("/api/v1/opds/catalog?magicShelfId=" + shelf.getId())
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
feed.append("</feed>");
|
||||||
|
return feed.toString();
|
||||||
|
}
|
||||||
|
|
||||||
public String generateCatalogFeed(HttpServletRequest request) {
|
public String generateCatalogFeed(HttpServletRequest request) {
|
||||||
Long libraryId = parseLongParam(request, "libraryId", null);
|
Long libraryId = parseLongParam(request, "libraryId", null);
|
||||||
Long shelfId = parseLongParam(request, "shelfId", null);
|
Long shelfId = parseLongParam(request, "shelfId", null);
|
||||||
|
Long magicShelfId = parseLongParam(request, "magicShelfId", null);
|
||||||
String query = request.getParameter("q");
|
String query = request.getParameter("q");
|
||||||
int page = Math.max(1, parseLongParam(request, "page", 1L).intValue());
|
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);
|
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||||
|
|
||||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
Long userId = getUserId();
|
||||||
Page<Book> booksPage = opdsBookService.getBooksPage(details, query, libraryId, shelfId, page - 1, size);
|
Page<Book> booksPage;
|
||||||
|
|
||||||
String feedTitle = determineFeedTitle(libraryId, shelfId);
|
if (magicShelfId != null) {
|
||||||
String feedId = determineFeedId(libraryId, shelfId);
|
booksPage = magicShelfBookService.getBooksByMagicShelfId(userId, magicShelfId, page - 1, size);
|
||||||
|
} else {
|
||||||
|
booksPage = opdsBookService.getBooksPage(userId, query, libraryId, shelfId, page - 1, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
String feedTitle = determineFeedTitle(libraryId, shelfId, magicShelfId);
|
||||||
|
String feedId = determineFeedId(libraryId, shelfId, magicShelfId);
|
||||||
|
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -213,11 +274,11 @@ public class OpdsFeedService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String generateRecentFeed(HttpServletRequest request) {
|
public String generateRecentFeed(HttpServletRequest request) {
|
||||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
Long userId = getUserId();
|
||||||
int page = Math.max(1, parseLongParam(request, "page", 1L).intValue());
|
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);
|
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||||
|
|
||||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(details, page - 1, size);
|
Page<Book> booksPage = opdsBookService.getRecentBooksPage(userId, page - 1, size);
|
||||||
|
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -242,9 +303,9 @@ public class OpdsFeedService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String generateSurpriseFeed(HttpServletRequest request) {
|
public String generateSurpriseFeed(HttpServletRequest request) {
|
||||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
Long userId = getUserId();
|
||||||
int count = 25;
|
int count = 25;
|
||||||
List<Book> books = opdsBookService.getRandomBooks(details, count);
|
List<Book> books = opdsBookService.getRandomBooks(userId, count);
|
||||||
|
|
||||||
var feed = new StringBuilder("""
|
var feed = new StringBuilder("""
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -382,7 +443,10 @@ public class OpdsFeedService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String determineFeedTitle(Long libraryId, Long shelfId) {
|
private String determineFeedTitle(Long libraryId, Long shelfId, Long magicShelfId) {
|
||||||
|
if (magicShelfId != null) {
|
||||||
|
return magicShelfBookService.getMagicShelfName(magicShelfId);
|
||||||
|
}
|
||||||
if (shelfId != null) {
|
if (shelfId != null) {
|
||||||
return opdsBookService.getShelfName(shelfId);
|
return opdsBookService.getShelfName(shelfId);
|
||||||
}
|
}
|
||||||
@@ -392,7 +456,10 @@ public class OpdsFeedService {
|
|||||||
return "Booklore Catalog";
|
return "Booklore Catalog";
|
||||||
}
|
}
|
||||||
|
|
||||||
private String determineFeedId(Long libraryId, Long shelfId) {
|
private String determineFeedId(Long libraryId, Long shelfId, Long magicShelfId) {
|
||||||
|
if (magicShelfId != null) {
|
||||||
|
return "urn:booklore:magic-shelf:" + magicShelfId;
|
||||||
|
}
|
||||||
if (shelfId != null) {
|
if (shelfId != null) {
|
||||||
return "urn:booklore:shelf:" + shelfId;
|
return "urn:booklore:shelf:" + shelfId;
|
||||||
}
|
}
|
||||||
@@ -435,4 +502,11 @@ public class OpdsFeedService {
|
|||||||
return defaultValue;
|
return defaultValue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Long getUserId() {
|
||||||
|
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||||
|
return details != null && details.getOpdsUserV2() != null
|
||||||
|
? details.getOpdsUserV2().getUserId()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+48
-21
@@ -57,10 +57,8 @@ class OpdsBookServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private OpdsUserDetails legacyUserDetails() {
|
private OpdsUserDetails legacyUserDetails() {
|
||||||
OpdsUser opdsUser = new OpdsUser();
|
OpdsUserV2 v2 = OpdsUserV2.builder().userId(999L).username("legacy").build();
|
||||||
opdsUser.setUsername("legacy");
|
return new OpdsUserDetails(v2);
|
||||||
opdsUser.setPassword(null);
|
|
||||||
return new OpdsUserDetails(null, opdsUser);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private OpdsUserDetails v2UserDetails(Long userId, boolean isAdmin, Set<Long> libraryIds) {
|
private OpdsUserDetails v2UserDetails(Long userId, boolean isAdmin, Set<Long> libraryIds) {
|
||||||
@@ -81,17 +79,14 @@ class OpdsBookServiceTest {
|
|||||||
}
|
}
|
||||||
when(user.getAssignedLibraries()).thenReturn(libraries);
|
when(user.getAssignedLibraries()).thenReturn(libraries);
|
||||||
|
|
||||||
return new OpdsUserDetails(v2, null);
|
return new OpdsUserDetails(v2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void getAccessibleLibraries_returnsAllLibraries_whenNoUserDetails() {
|
void getAccessibleLibraries_returnsEmptyList_whenUserIdIsNull() {
|
||||||
List<Library> libraries = List.of(Library.builder().id(1L).name("Lib1").watch(false).build());
|
|
||||||
when(libraryService.getAllLibraries()).thenReturn(libraries);
|
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(null);
|
List<Library> result = opdsBookService.getAccessibleLibraries(null);
|
||||||
|
|
||||||
assertThat(result).isEqualTo(libraries);
|
assertThat(result).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -107,7 +102,7 @@ class OpdsBookServiceTest {
|
|||||||
List<Library> assigned = List.of(Library.builder().id(2L).watch(false).build());
|
List<Library> assigned = List.of(Library.builder().id(2L).watch(false).build());
|
||||||
when(user.getAssignedLibraries()).thenReturn(assigned);
|
when(user.getAssignedLibraries()).thenReturn(assigned);
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
List<Library> result = opdsBookService.getAccessibleLibraries(details.getOpdsUserV2().getUserId());
|
||||||
|
|
||||||
assertThat(result).isEqualTo(assigned);
|
assertThat(result).isEqualTo(assigned);
|
||||||
}
|
}
|
||||||
@@ -118,7 +113,7 @@ class OpdsBookServiceTest {
|
|||||||
List<Library> allLibs = List.of(Library.builder().id(1L).watch(false).build());
|
List<Library> allLibs = List.of(Library.builder().id(1L).watch(false).build());
|
||||||
when(libraryService.getAllLibraries()).thenReturn(allLibs);
|
when(libraryService.getAllLibraries()).thenReturn(allLibs);
|
||||||
|
|
||||||
List<Library> result = opdsBookService.getAccessibleLibraries(details);
|
List<Library> result = opdsBookService.getAccessibleLibraries(details.getOpdsUserV2().getUserId());
|
||||||
|
|
||||||
assertThat(result).isEqualTo(allLibs);
|
assertThat(result).isEqualTo(allLibs);
|
||||||
}
|
}
|
||||||
@@ -126,18 +121,41 @@ class OpdsBookServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void getBooksPage_legacyUser_delegatesToLegacyMethod() {
|
void getBooksPage_legacyUser_delegatesToLegacyMethod() {
|
||||||
OpdsUserDetails details = legacyUserDetails();
|
OpdsUserDetails details = legacyUserDetails();
|
||||||
|
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||||
|
var permissionsEntity = mock(com.adityachandel.booklore.model.entity.UserPermissionsEntity.class);
|
||||||
|
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
|
||||||
|
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||||
|
when(entity.getPermissions()).thenReturn(permissionsEntity);
|
||||||
|
when(userRepository.findById(999L)).thenReturn(Optional.of(entity));
|
||||||
|
|
||||||
|
BookLoreUser user = mock(BookLoreUser.class);
|
||||||
|
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||||
|
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
|
||||||
|
when(user.getPermissions()).thenReturn(perms);
|
||||||
|
when(perms.isAdmin()).thenReturn(false);
|
||||||
|
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
|
||||||
|
when(user.getId()).thenReturn(999L);
|
||||||
|
|
||||||
|
// Mock shelf access
|
||||||
|
ShelfEntity shelf = mock(ShelfEntity.class);
|
||||||
|
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
|
||||||
|
when(shelfUser.getId()).thenReturn(999L);
|
||||||
|
when(shelf.getUser()).thenReturn(shelfUser);
|
||||||
|
when(shelfRepository.findById(2L)).thenReturn(Optional.of(shelf));
|
||||||
|
|
||||||
when(bookOpdsRepository.findBookIds(any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findBookIds(any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findBookIdsByShelfId(anyLong(), any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findBookIdsByShelfId(anyLong(), any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findBookIdsByMetadataSearch(anyString(), any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findBookIdsByMetadataSearch(anyString(), any())).thenReturn(Page.empty());
|
||||||
|
when(bookOpdsRepository.findBookIdsByMetadataSearchAndLibraryIds(anyString(), anySet(), any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
|
||||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
|
||||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(anyList(), anyLong())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(anyList(), anyLong())).thenReturn(List.of());
|
||||||
when(bookOpdsRepository.findAllWithFullMetadataByIds(anyList())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithFullMetadataByIds(anyList())).thenReturn(List.of());
|
||||||
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of());
|
||||||
|
|
||||||
opdsBookService.getBooksPage(details, "q", 1L, 2L, 0, 10);
|
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, 2L, 0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -165,6 +183,7 @@ class OpdsBookServiceTest {
|
|||||||
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
|
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
|
||||||
when(user.getPermissions()).thenReturn(perms);
|
when(user.getPermissions()).thenReturn(perms);
|
||||||
when(perms.isAdmin()).thenReturn(true);
|
when(perms.isAdmin()).thenReturn(true);
|
||||||
|
when(user.getId()).thenReturn(1L);
|
||||||
|
|
||||||
ShelfEntity shelf = mock(ShelfEntity.class);
|
ShelfEntity shelf = mock(ShelfEntity.class);
|
||||||
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
|
BookLoreUserEntity shelfUser = mock(BookLoreUserEntity.class);
|
||||||
@@ -172,16 +191,24 @@ class OpdsBookServiceTest {
|
|||||||
when(shelf.getUser()).thenReturn(shelfUser);
|
when(shelf.getUser()).thenReturn(shelfUser);
|
||||||
when(shelfRepository.findById(anyLong())).thenReturn(Optional.of(shelf));
|
when(shelfRepository.findById(anyLong())).thenReturn(Optional.of(shelf));
|
||||||
|
|
||||||
opdsBookService.getBooksPage(details, "q", 1L, 2L, 0, 10);
|
opdsBookService.getBooksPage(details.getOpdsUserV2().getUserId(), "q", 1L, 2L, 0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void getRecentBooksPage_returnsRecentBooks_forLegacyUser() {
|
void getRecentBooksPage_returnsRecentBooks_forLegacyUser() {
|
||||||
OpdsUserDetails details = legacyUserDetails();
|
OpdsUserDetails details = legacyUserDetails();
|
||||||
|
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||||
|
when(userRepository.findById(999L)).thenReturn(Optional.of(entity));
|
||||||
|
BookLoreUser user = mock(BookLoreUser.class);
|
||||||
|
when(bookLoreUserTransformer.toDTO(entity)).thenReturn(user);
|
||||||
|
BookLoreUser.UserPermissions perms = mock(BookLoreUser.UserPermissions.class);
|
||||||
|
when(user.getPermissions()).thenReturn(perms);
|
||||||
|
when(perms.isAdmin()).thenReturn(true);
|
||||||
|
|
||||||
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
|
when(bookOpdsRepository.findRecentBookIds(any())).thenReturn(Page.empty());
|
||||||
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
|
when(bookOpdsRepository.findAllWithMetadataByIds(anyList())).thenReturn(List.of());
|
||||||
|
|
||||||
opdsBookService.getRecentBooksPage(details, 0, 10);
|
opdsBookService.getRecentBooksPage(details.getOpdsUserV2().getUserId(), 0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -205,7 +232,7 @@ class OpdsBookServiceTest {
|
|||||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of(bookEntity));
|
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet())).thenReturn(List.of(bookEntity));
|
||||||
when(bookMapper.toBook(bookEntity)).thenReturn(book);
|
when(bookMapper.toBook(bookEntity)).thenReturn(book);
|
||||||
|
|
||||||
Page<Book> result = opdsBookService.getRecentBooksPage(details, 0, 10);
|
Page<Book> result = opdsBookService.getRecentBooksPage(details.getOpdsUserV2().getUserId(), 0, 10);
|
||||||
|
|
||||||
assertThat(result.getContent()).hasSize(1);
|
assertThat(result.getContent()).hasSize(1);
|
||||||
assertThat(result.getContent().getFirst().getShelves()).allMatch(shelf -> shelf.getUserId().equals(2L));
|
assertThat(result.getContent().getFirst().getShelves()).allMatch(shelf -> shelf.getUserId().equals(2L));
|
||||||
@@ -265,7 +292,7 @@ class OpdsBookServiceTest {
|
|||||||
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
OpdsUserDetails details = v2UserDetails(1L, true, Set.of(1L));
|
||||||
OpdsBookService spy = Mockito.spy(opdsBookService);
|
OpdsBookService spy = Mockito.spy(opdsBookService);
|
||||||
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
|
List<Library> libs = List.of(Library.builder().id(1L).watch(false).build());
|
||||||
doReturn(libs).when(spy).getAccessibleLibraries(details);
|
doReturn(libs).when(spy).getAccessibleLibraries(details.getOpdsUserV2().getUserId());
|
||||||
|
|
||||||
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
||||||
BookEntity entity = mock(BookEntity.class);
|
BookEntity entity = mock(BookEntity.class);
|
||||||
@@ -273,7 +300,7 @@ class OpdsBookServiceTest {
|
|||||||
Book book = Book.builder().id(1L).build();
|
Book book = Book.builder().id(1L).build();
|
||||||
when(bookMapper.toBook(entity)).thenReturn(book);
|
when(bookMapper.toBook(entity)).thenReturn(book);
|
||||||
|
|
||||||
List<Book> result = spy.getRandomBooks(details, 1);
|
List<Book> result = spy.getRandomBooks(details.getOpdsUserV2().getUserId(), 1);
|
||||||
|
|
||||||
assertThat(result).hasSize(1);
|
assertThat(result).hasSize(1);
|
||||||
}
|
}
|
||||||
@@ -282,9 +309,9 @@ class OpdsBookServiceTest {
|
|||||||
void getRandomBooks_returnsEmpty_whenNoLibraries() {
|
void getRandomBooks_returnsEmpty_whenNoLibraries() {
|
||||||
OpdsUserDetails details = v2UserDetails(1L, false, Set.of());
|
OpdsUserDetails details = v2UserDetails(1L, false, Set.of());
|
||||||
OpdsBookService spy = Mockito.spy(opdsBookService);
|
OpdsBookService spy = Mockito.spy(opdsBookService);
|
||||||
doReturn(List.of()).when(spy).getAccessibleLibraries(details);
|
doReturn(List.of()).when(spy).getAccessibleLibraries(details.getOpdsUserV2().getUserId());
|
||||||
|
|
||||||
List<Book> result = spy.getRandomBooks(details, 1);
|
List<Book> result = spy.getRandomBooks(details.getOpdsUserV2().getUserId(), 1);
|
||||||
|
|
||||||
assertThat(result).isEmpty();
|
assertThat(result).isEmpty();
|
||||||
}
|
}
|
||||||
@@ -300,7 +327,7 @@ class OpdsBookServiceTest {
|
|||||||
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
|
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
|
||||||
|
|
||||||
assertThatThrownBy(() ->
|
assertThatThrownBy(() ->
|
||||||
opdsBookService.getBooksPage(v2UserDetails(1L, false, Set.of()), null, null, null, 0, 10)
|
opdsBookService.getBooksPage(1L, null, null, null, 0, 10)
|
||||||
).hasMessageContaining("You are not allowed to access this resource");
|
).hasMessageContaining("You are not allowed to access this resource");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+64
-40
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.dto.Library;
|
|||||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||||
|
import com.adityachandel.booklore.service.MagicShelfService;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -26,9 +27,12 @@ import static org.mockito.Mockito.*;
|
|||||||
class OpdsFeedServiceTest {
|
class OpdsFeedServiceTest {
|
||||||
|
|
||||||
private static final Instant FIXED_INSTANT = Instant.parse("2025-01-01T12:00:00Z");
|
private static final Instant FIXED_INSTANT = Instant.parse("2025-01-01T12:00:00Z");
|
||||||
|
private static final Long TEST_USER_ID = 42L;
|
||||||
|
|
||||||
private AuthenticationService authenticationService;
|
private AuthenticationService authenticationService;
|
||||||
private OpdsBookService opdsBookService;
|
private OpdsBookService opdsBookService;
|
||||||
|
private MagicShelfService magicShelfService;
|
||||||
|
private MagicShelfBookService magicShelfBookService;
|
||||||
private OpdsFeedService opdsFeedService;
|
private OpdsFeedService opdsFeedService;
|
||||||
private HttpServletRequest request;
|
private HttpServletRequest request;
|
||||||
|
|
||||||
@@ -36,10 +40,21 @@ class OpdsFeedServiceTest {
|
|||||||
void setUp() {
|
void setUp() {
|
||||||
authenticationService = mock(AuthenticationService.class);
|
authenticationService = mock(AuthenticationService.class);
|
||||||
opdsBookService = mock(OpdsBookService.class);
|
opdsBookService = mock(OpdsBookService.class);
|
||||||
opdsFeedService = new OpdsFeedService(authenticationService, opdsBookService);
|
magicShelfService = mock(MagicShelfService.class);
|
||||||
|
magicShelfBookService = mock(MagicShelfBookService.class);
|
||||||
|
opdsFeedService = new OpdsFeedService(authenticationService, opdsBookService, magicShelfService, magicShelfBookService);
|
||||||
request = mock(HttpServletRequest.class);
|
request = mock(HttpServletRequest.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private OpdsUserDetails mockAuthenticatedUser() {
|
||||||
|
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
||||||
|
OpdsUserV2 v2 = mock(OpdsUserV2.class);
|
||||||
|
when(userDetails.getOpdsUserV2()).thenReturn(v2);
|
||||||
|
when(v2.getUserId()).thenReturn(TEST_USER_ID);
|
||||||
|
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
||||||
|
return userDetails;
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateRootNavigation_shouldContainAllSections() {
|
void generateRootNavigation_shouldContainAllSections() {
|
||||||
String xml = opdsFeedService.generateRootNavigation(request);
|
String xml = opdsFeedService.generateRootNavigation(request);
|
||||||
@@ -47,6 +62,7 @@ class OpdsFeedServiceTest {
|
|||||||
assertThat(xml).contains("Recently Added");
|
assertThat(xml).contains("Recently Added");
|
||||||
assertThat(xml).contains("Libraries");
|
assertThat(xml).contains("Libraries");
|
||||||
assertThat(xml).contains("Shelves");
|
assertThat(xml).contains("Shelves");
|
||||||
|
assertThat(xml).contains("Magic Shelves");
|
||||||
assertThat(xml).contains("Surprise Me");
|
assertThat(xml).contains("Surprise Me");
|
||||||
assertThat(xml).contains("<?xml");
|
assertThat(xml).contains("<?xml");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
@@ -54,23 +70,22 @@ class OpdsFeedServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateLibrariesNavigation_shouldListLibraries() {
|
void generateLibrariesNavigation_shouldListLibraries() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
Library lib = Library.builder().id(1L).name("Test Library").watch(false).build();
|
Library lib = Library.builder().id(1L).name("Test Library").watch(false).build();
|
||||||
when(opdsBookService.getAccessibleLibraries(userDetails)).thenReturn(List.of(lib));
|
when(opdsBookService.getAccessibleLibraries(TEST_USER_ID)).thenReturn(List.of(lib));
|
||||||
|
|
||||||
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
||||||
assertThat(xml).contains("Test Library");
|
assertThat(xml).contains("Test Library");
|
||||||
assertThat(xml).contains("urn:booklore:library:1");
|
assertThat(xml).contains("urn:booklore:library:1");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService).getAccessibleLibraries(TEST_USER_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateLibrariesNavigation_shouldHandleNoLibraries() {
|
void generateLibrariesNavigation_shouldHandleNoLibraries() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
when(opdsBookService.getAccessibleLibraries(TEST_USER_ID)).thenReturn(Collections.emptyList());
|
||||||
when(opdsBookService.getAccessibleLibraries(userDetails)).thenReturn(Collections.emptyList());
|
|
||||||
|
|
||||||
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
String xml = opdsFeedService.generateLibrariesNavigation(request);
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
@@ -78,30 +93,22 @@ class OpdsFeedServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateShelvesNavigation_shouldListShelves() {
|
void generateShelvesNavigation_shouldListShelves() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
OpdsUserV2 v2 = mock(OpdsUserV2.class);
|
|
||||||
when(userDetails.getOpdsUserV2()).thenReturn(v2);
|
|
||||||
when(v2.getUserId()).thenReturn(42L);
|
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
ShelfEntity shelfEntity = ShelfEntity.builder().id(5L).name("Favorites").build();
|
ShelfEntity shelfEntity = ShelfEntity.builder().id(5L).name("Favorites").build();
|
||||||
when(opdsBookService.getUserShelves(42L)).thenReturn(Collections.singletonList(shelfEntity));
|
when(opdsBookService.getUserShelves(TEST_USER_ID)).thenReturn(Collections.singletonList(shelfEntity));
|
||||||
|
|
||||||
String xml = opdsFeedService.generateShelvesNavigation(request);
|
String xml = opdsFeedService.generateShelvesNavigation(request);
|
||||||
assertThat(xml).contains("Favorites");
|
assertThat(xml).contains("Favorites");
|
||||||
assertThat(xml).contains("urn:booklore:shelf:5");
|
assertThat(xml).contains("urn:booklore:shelf:5");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService).getUserShelves(TEST_USER_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateShelvesNavigation_shouldHandleNoShelves() {
|
void generateShelvesNavigation_shouldHandleNoShelves() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
OpdsUserV2 v2 = mock(OpdsUserV2.class);
|
when(opdsBookService.getUserShelves(TEST_USER_ID)).thenReturn(Collections.emptyList());
|
||||||
when(userDetails.getOpdsUserV2()).thenReturn(v2);
|
|
||||||
when(v2.getUserId()).thenReturn(42L);
|
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
when(opdsBookService.getUserShelves(42L)).thenReturn(Collections.emptyList());
|
|
||||||
|
|
||||||
String xml = opdsFeedService.generateShelvesNavigation(request);
|
String xml = opdsFeedService.generateShelvesNavigation(request);
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
@@ -112,15 +119,16 @@ class OpdsFeedServiceTest {
|
|||||||
when(authenticationService.getOpdsUser()).thenReturn(null);
|
when(authenticationService.getOpdsUser()).thenReturn(null);
|
||||||
String xml = opdsFeedService.generateShelvesNavigation(request);
|
String xml = opdsFeedService.generateShelvesNavigation(request);
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService, never()).getUserShelves(any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateCatalogFeed_shouldReturnFeedWithBooks() {
|
void generateCatalogFeed_shouldReturnFeedWithBooks() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
when(request.getParameter("libraryId")).thenReturn(null);
|
when(request.getParameter("libraryId")).thenReturn(null);
|
||||||
when(request.getParameter("shelfId")).thenReturn(null);
|
when(request.getParameter("shelfId")).thenReturn(null);
|
||||||
|
when(request.getParameter("magicShelfId")).thenReturn(null);
|
||||||
when(request.getParameter("q")).thenReturn(null);
|
when(request.getParameter("q")).thenReturn(null);
|
||||||
when(request.getParameter("page")).thenReturn(null);
|
when(request.getParameter("page")).thenReturn(null);
|
||||||
when(request.getParameter("size")).thenReturn(null);
|
when(request.getParameter("size")).thenReturn(null);
|
||||||
@@ -143,9 +151,7 @@ class OpdsFeedServiceTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
|
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
|
||||||
when(opdsBookService.getBooksPage(eq(userDetails), any(), any(), any(), eq(0), eq(50))).thenReturn(page);
|
when(opdsBookService.getBooksPage(eq(TEST_USER_ID), any(), any(), any(), eq(0), eq(50))).thenReturn(page);
|
||||||
when(opdsBookService.getShelfName(any())).thenReturn("Shelf Name");
|
|
||||||
when(opdsBookService.getLibraryName(any())).thenReturn("Library Name");
|
|
||||||
|
|
||||||
String xml = opdsFeedService.generateCatalogFeed(request);
|
String xml = opdsFeedService.generateCatalogFeed(request);
|
||||||
assertThat(xml).contains("Book Title");
|
assertThat(xml).contains("Book Title");
|
||||||
@@ -154,12 +160,12 @@ class OpdsFeedServiceTest {
|
|||||||
assertThat(xml).contains("urn:booklore:book:10");
|
assertThat(xml).contains("urn:booklore:book:10");
|
||||||
assertThat(xml).contains("application/epub+zip");
|
assertThat(xml).contains("application/epub+zip");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService).getBooksPage(TEST_USER_ID, null, null, null, 0, 50);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateCatalogFeed_shouldHandleEmptyPage() {
|
void generateCatalogFeed_shouldHandleEmptyPage() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
when(request.getParameter(anyString())).thenReturn(null);
|
when(request.getParameter(anyString())).thenReturn(null);
|
||||||
when(request.getRequestURI()).thenReturn("/api/v1/opds/catalog");
|
when(request.getRequestURI()).thenReturn("/api/v1/opds/catalog");
|
||||||
@@ -174,8 +180,7 @@ class OpdsFeedServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateRecentFeed_shouldReturnFeedWithBooks() {
|
void generateRecentFeed_shouldReturnFeedWithBooks() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
when(request.getParameter("page")).thenReturn(null);
|
when(request.getParameter("page")).thenReturn(null);
|
||||||
when(request.getParameter("size")).thenReturn(null);
|
when(request.getParameter("size")).thenReturn(null);
|
||||||
@@ -190,18 +195,18 @@ class OpdsFeedServiceTest {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
|
Page<Book> page = new PageImpl<>(List.of(book), PageRequest.of(0, 50), 1);
|
||||||
when(opdsBookService.getRecentBooksPage(eq(userDetails), eq(0), eq(50))).thenReturn(page);
|
when(opdsBookService.getRecentBooksPage(eq(TEST_USER_ID), eq(0), eq(50))).thenReturn(page);
|
||||||
|
|
||||||
String xml = opdsFeedService.generateRecentFeed(request);
|
String xml = opdsFeedService.generateRecentFeed(request);
|
||||||
assertThat(xml).contains("Recent Book");
|
assertThat(xml).contains("Recent Book");
|
||||||
assertThat(xml).contains("application/pdf");
|
assertThat(xml).contains("application/pdf");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService).getRecentBooksPage(TEST_USER_ID, 0, 50);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateRecentFeed_shouldHandleEmptyPage() {
|
void generateRecentFeed_shouldHandleEmptyPage() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
when(request.getParameter(anyString())).thenReturn(null);
|
when(request.getParameter(anyString())).thenReturn(null);
|
||||||
when(request.getRequestURI()).thenReturn("/api/v1/opds/recent");
|
when(request.getRequestURI()).thenReturn("/api/v1/opds/recent");
|
||||||
@@ -216,8 +221,7 @@ class OpdsFeedServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateSurpriseFeed_shouldReturnFeedWithBooks() {
|
void generateSurpriseFeed_shouldReturnFeedWithBooks() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
|
||||||
|
|
||||||
Book book = Book.builder()
|
Book book = Book.builder()
|
||||||
.id(12L)
|
.id(12L)
|
||||||
@@ -226,20 +230,19 @@ class OpdsFeedServiceTest {
|
|||||||
.metadata(BookMetadata.builder().title("Surprise Book").build())
|
.metadata(BookMetadata.builder().title("Surprise Book").build())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
when(opdsBookService.getRandomBooks(userDetails, 25)).thenReturn(List.of(book));
|
when(opdsBookService.getRandomBooks(TEST_USER_ID, 25)).thenReturn(List.of(book));
|
||||||
|
|
||||||
String xml = opdsFeedService.generateSurpriseFeed(request);
|
String xml = opdsFeedService.generateSurpriseFeed(request);
|
||||||
assertThat(xml).contains("Surprise Book");
|
assertThat(xml).contains("Surprise Book");
|
||||||
assertThat(xml).contains("urn:booklore:book:12");
|
assertThat(xml).contains("urn:booklore:book:12");
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
|
verify(opdsBookService).getRandomBooks(TEST_USER_ID, 25);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void generateSurpriseFeed_shouldHandleNoBooks() {
|
void generateSurpriseFeed_shouldHandleNoBooks() {
|
||||||
OpdsUserDetails userDetails = mock(OpdsUserDetails.class);
|
mockAuthenticatedUser();
|
||||||
when(authenticationService.getOpdsUser()).thenReturn(userDetails);
|
when(opdsBookService.getRandomBooks(TEST_USER_ID, 25)).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
when(opdsBookService.getRandomBooks(userDetails, 25)).thenReturn(Collections.emptyList());
|
|
||||||
|
|
||||||
String xml = opdsFeedService.generateSurpriseFeed(request);
|
String xml = opdsFeedService.generateSurpriseFeed(request);
|
||||||
assertThat(xml).contains("</feed>");
|
assertThat(xml).contains("</feed>");
|
||||||
@@ -255,7 +258,6 @@ class OpdsFeedServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void escapeXml_shouldEscapeSpecialCharacters() throws Exception {
|
void escapeXml_shouldEscapeSpecialCharacters() throws Exception {
|
||||||
// Use reflection to access private method
|
|
||||||
var method = OpdsFeedService.class.getDeclaredMethod("escapeXml", String.class);
|
var method = OpdsFeedService.class.getDeclaredMethod("escapeXml", String.class);
|
||||||
method.setAccessible(true);
|
method.setAccessible(true);
|
||||||
String input = "a&b<c>d\"e'f";
|
String input = "a&b<c>d\"e'f";
|
||||||
@@ -281,4 +283,26 @@ class OpdsFeedServiceTest {
|
|||||||
assertThat(invalid).isEqualTo(42L);
|
assertThat(invalid).isEqualTo(42L);
|
||||||
assertThat(missing).isEqualTo(42L);
|
assertThat(missing).isEqualTo(42L);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getUserId_shouldReturnUserId() throws Exception {
|
||||||
|
mockAuthenticatedUser();
|
||||||
|
|
||||||
|
var method = OpdsFeedService.class.getDeclaredMethod("getUserId");
|
||||||
|
method.setAccessible(true);
|
||||||
|
Long userId = (Long) method.invoke(opdsFeedService);
|
||||||
|
|
||||||
|
assertThat(userId).isEqualTo(TEST_USER_ID);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getUserId_shouldReturnNullWhenNotAuthenticated() throws Exception {
|
||||||
|
when(authenticationService.getOpdsUser()).thenReturn(null);
|
||||||
|
|
||||||
|
var method = OpdsFeedService.class.getDeclaredMethod("getUserId");
|
||||||
|
method.setAccessible(true);
|
||||||
|
Long userId = (Long) method.invoke(opdsFeedService);
|
||||||
|
|
||||||
|
assertThat(userId).isNull();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user