@@ -6,6 +6,8 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.JacksonConfig;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import org.booklore.mapper.komga.KomgaMapper;
|
||||
import org.booklore.model.dto.komga.KomgaBookDto;
|
||||
import org.booklore.model.dto.komga.KomgaLibraryDto;
|
||||
@@ -13,6 +15,7 @@ import org.booklore.model.dto.komga.KomgaPageableDto;
|
||||
import org.booklore.model.dto.komga.KomgaSeriesDto;
|
||||
import org.booklore.service.book.BookService;
|
||||
import org.booklore.service.komga.KomgaService;
|
||||
import org.booklore.service.opds.OpdsBookService;
|
||||
import org.booklore.service.opds.OpdsUserV2Service;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -36,6 +39,8 @@ public class KomgaController {
|
||||
|
||||
private final KomgaService komgaService;
|
||||
private final BookService bookService;
|
||||
private final OpdsBookService opdsBookService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final OpdsUserV2Service opdsUserV2Service;
|
||||
private final KomgaMapper komgaMapper;
|
||||
|
||||
@@ -147,6 +152,7 @@ public class KomgaController {
|
||||
@Parameter(description = "Book ID") @PathVariable Long bookId,
|
||||
@Parameter(description = "Page number") @PathVariable Integer pageNumber,
|
||||
@Parameter(description = "Convert image format (e.g., 'png')") @RequestParam(required = false) String convert) {
|
||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||
try {
|
||||
boolean convertToPng = "png".equalsIgnoreCase(convert);
|
||||
Resource pageImage = komgaService.getBookPageImage(bookId, pageNumber, convertToPng);
|
||||
@@ -166,6 +172,7 @@ public class KomgaController {
|
||||
@GetMapping("/v1/books/{bookId}/file")
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "Book ID") @PathVariable Long bookId) {
|
||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@@ -173,6 +180,7 @@ public class KomgaController {
|
||||
@GetMapping("/v1/books/{bookId}/thumbnail")
|
||||
public ResponseEntity<Resource> getBookThumbnail(
|
||||
@Parameter(description = "Book ID") @PathVariable Long bookId) {
|
||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
return ResponseEntity.ok()
|
||||
.header("Content-Type", "image/jpeg")
|
||||
@@ -208,4 +216,11 @@ public class KomgaController {
|
||||
@Parameter(description = "Return all collections without paging") @RequestParam(defaultValue = "false") boolean unpaged) {
|
||||
return writeJson(komgaService.getCollections(page, size, unpaged));
|
||||
}
|
||||
|
||||
private Long getOpdsUserId() {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
return details != null && details.getOpdsUserV2() != null
|
||||
? details.getOpdsUserV2().getUserId()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import org.booklore.service.book.BookDownloadService;
|
||||
import org.booklore.service.book.BookService;
|
||||
import org.booklore.service.opds.OpdsBookService;
|
||||
import org.booklore.service.opds.OpdsFeedService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -34,6 +37,8 @@ public class OpdsController {
|
||||
private final OpdsFeedService opdsFeedService;
|
||||
private final BookService bookService;
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final OpdsBookService opdsBookService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@Operation(summary = "Download book file", description = "Download the book file by its ID. Optionally specify a fileId to download a specific format.")
|
||||
@ApiResponses({
|
||||
@@ -44,6 +49,7 @@ public class OpdsController {
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId,
|
||||
@Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) {
|
||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||
if (fileId != null) {
|
||||
return bookDownloadService.downloadBookFile(bookId, fileId);
|
||||
}
|
||||
@@ -57,6 +63,7 @@ public class OpdsController {
|
||||
})
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
opdsBookService.validateBookContentAccess(bookId, getOpdsUserId());
|
||||
Resource coverImage = bookService.getBookThumbnail(bookId);
|
||||
String contentType = "image/jpeg";
|
||||
return ResponseEntity.ok()
|
||||
@@ -169,4 +176,11 @@ public class OpdsController {
|
||||
.contentType(MediaType.parseMediaType("application/opensearchdescription+xml;charset=utf-8"))
|
||||
.body(searchDoc);
|
||||
}
|
||||
|
||||
private Long getOpdsUserId() {
|
||||
OpdsUserDetails details = authenticationService.getOpdsUser();
|
||||
return details != null && details.getOpdsUserV2() != null
|
||||
? details.getOpdsUserV2().getUserId()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,13 +16,16 @@ import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.MagicShelfRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.BookRuleEvaluatorService;
|
||||
import org.booklore.service.restriction.ContentRestrictionService;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -37,6 +40,7 @@ public class MagicShelfBookService {
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final BookRuleEvaluatorService ruleEvaluatorService;
|
||||
private final ContentRestrictionService contentRestrictionService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public Page<Book> getBooksByMagicShelfId(Long userId, Long magicShelfId, int page, int size) {
|
||||
@@ -49,7 +53,12 @@ public class MagicShelfBookService {
|
||||
|
||||
Page<BookEntity> booksPage = bookRepository.findAll(specification, pageable);
|
||||
|
||||
return booksPage.map(bookMapper::toBook).map(book -> filterBook(book, userId));
|
||||
List<BookEntity> filteredEntities = contentRestrictionService.applyRestrictions(booksPage.getContent(), userId);
|
||||
List<Book> books = filteredEntities.stream()
|
||||
.map(bookMapper::toBook)
|
||||
.map(book -> filterBook(book, userId))
|
||||
.toList();
|
||||
return new PageImpl<>(books, pageable, booksPage.getTotalElements());
|
||||
} 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);
|
||||
|
||||
@@ -12,8 +12,10 @@ import org.booklore.model.enums.OpdsSortOrder;
|
||||
import org.booklore.repository.BookOpdsRepository;
|
||||
import org.booklore.repository.ShelfRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.util.BookUtils;
|
||||
import org.booklore.service.library.LibraryService;
|
||||
import org.booklore.service.restriction.ContentRestrictionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -32,11 +34,13 @@ import java.util.stream.Collectors;
|
||||
public class OpdsBookService {
|
||||
|
||||
private final BookOpdsRepository bookOpdsRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookMapper bookMapper;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final LibraryService libraryService;
|
||||
private final ContentRestrictionService contentRestrictionService;
|
||||
|
||||
public List<Library> getAccessibleLibraries(Long userId) {
|
||||
if (userId == null) {
|
||||
@@ -76,28 +80,28 @@ public class OpdsBookService {
|
||||
if (shelfIds != null && !shelfIds.isEmpty()) {
|
||||
validateShelfAccess(shelfIds, user.getId(), isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInShelvesPageInternal(BookUtils.normalizeForSearch(query), shelfIds, page, size)
|
||||
: getBooksByShelfIdsPageInternal(shelfIds, page, size);
|
||||
? searchByMetadataInShelvesPageInternal(BookUtils.normalizeForSearch(query), shelfIds, page, size, userId)
|
||||
: getBooksByShelfIdsPageInternal(shelfIds, page, size, userId);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
if (libraryId != null) {
|
||||
validateLibraryAccess(libraryId, userLibraryIds, isAdmin);
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), Set.of(libraryId), page, size)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size);
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), Set.of(libraryId), page, size, userId)
|
||||
: getBooksByLibraryIdsPageInternal(Set.of(libraryId), page, size, userId);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
if (isAdmin) {
|
||||
return query != null && !query.isBlank()
|
||||
? searchByMetadataPageInternal(BookUtils.normalizeForSearch(query), page, size)
|
||||
: getAllBooksPageInternal(page, size);
|
||||
? searchByMetadataPageInternal(BookUtils.normalizeForSearch(query), page, size, null)
|
||||
: getAllBooksPageInternal(page, size, null);
|
||||
}
|
||||
|
||||
Page<Book> books = query != null && !query.isBlank()
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), userLibraryIds, page, size)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size);
|
||||
? searchByMetadataInLibrariesPageInternal(BookUtils.normalizeForSearch(query), userLibraryIds, page, size, userId)
|
||||
: getBooksByLibraryIdsPageInternal(userLibraryIds, page, size, userId);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
@@ -111,14 +115,14 @@ public class OpdsBookService {
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
if (user.getPermissions().isAdmin()) {
|
||||
return getRecentBooksPageInternal(page, size);
|
||||
return getRecentBooksPageInternal(page, size, null);
|
||||
}
|
||||
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
.map(Library::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size);
|
||||
Page<Book> books = getRecentBooksByLibraryIdsPageInternal(libraryIds, page, size, userId);
|
||||
return applyBookFilters(books, userId);
|
||||
}
|
||||
|
||||
@@ -160,6 +164,9 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(ids.stream().limit(count).toList());
|
||||
if (userId != null) {
|
||||
books = contentRestrictionService.applyRestrictions(books, userId);
|
||||
}
|
||||
return books.stream().map(bookMapper::toBook).toList();
|
||||
}
|
||||
|
||||
@@ -208,7 +215,7 @@ public class OpdsBookService {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, null);
|
||||
}
|
||||
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
@@ -221,7 +228,7 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable);
|
||||
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable, userId);
|
||||
return applyBookFilters(booksPage, userId);
|
||||
}
|
||||
|
||||
@@ -262,7 +269,7 @@ public class OpdsBookService {
|
||||
return new PageImpl<>(List.of(), pageable, 0);
|
||||
}
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, null);
|
||||
}
|
||||
|
||||
Set<Long> libraryIds = user.getAssignedLibraries().stream()
|
||||
@@ -275,11 +282,11 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable);
|
||||
Page<Book> booksPage = createPageFromEntities(books, idPage, pageable, userId);
|
||||
return applyBookFilters(booksPage, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getAllBooksPageInternal(int page, int size) {
|
||||
private Page<Book> getAllBooksPageInternal(int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIds(pageable);
|
||||
@@ -288,10 +295,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getRecentBooksPageInternal(int page, int size) {
|
||||
private Page<Book> getRecentBooksPageInternal(int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findRecentBookIds(pageable);
|
||||
@@ -300,10 +307,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size) {
|
||||
private Page<Book> getBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByLibraryIds(libraryIds, pageable);
|
||||
@@ -312,10 +319,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getRecentBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size) {
|
||||
private Page<Book> getRecentBooksByLibraryIdsPageInternal(Set<Long> libraryIds, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findRecentBookIdsByLibraryIds(libraryIds, pageable);
|
||||
@@ -324,10 +331,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksByShelfIdPageInternal(Long shelfId, int page, int size) {
|
||||
private Page<Book> getBooksByShelfIdPageInternal(Long shelfId, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByShelfId(shelfId, pageable);
|
||||
@@ -336,10 +343,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndShelfId(idPage.getContent(), shelfId);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> getBooksByShelfIdsPageInternal(Set<Long> shelfIds, int page, int size) {
|
||||
private Page<Book> getBooksByShelfIdsPageInternal(Set<Long> shelfIds, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByShelfIds(shelfIds, pageable);
|
||||
@@ -348,10 +355,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithMetadataByIdsAndShelfIds(idPage.getContent(), shelfIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> searchByMetadataPageInternal(String text, int page, int size) {
|
||||
private Page<Book> searchByMetadataPageInternal(String text, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearch(text, pageable);
|
||||
@@ -360,10 +367,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIds(idPage.getContent());
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> searchByMetadataInLibrariesPageInternal(String text, Set<Long> libraryIds, int page, int size) {
|
||||
private Page<Book> searchByMetadataInLibrariesPageInternal(String text, Set<Long> libraryIds, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearchAndLibraryIds(text, libraryIds, pageable);
|
||||
@@ -372,10 +379,10 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndLibraryIds(idPage.getContent(), libraryIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private Page<Book> searchByMetadataInShelvesPageInternal(String text, Set<Long> shelfIds, int page, int size) {
|
||||
private Page<Book> searchByMetadataInShelvesPageInternal(String text, Set<Long> shelfIds, int page, int size, Long userId) {
|
||||
Pageable pageable = PageRequest.of(Math.max(page, 0), size);
|
||||
|
||||
Page<Long> idPage = bookOpdsRepository.findBookIdsByMetadataSearchAndShelfIds(text, shelfIds, pageable);
|
||||
@@ -384,7 +391,7 @@ public class OpdsBookService {
|
||||
}
|
||||
|
||||
List<BookEntity> books = bookOpdsRepository.findAllWithFullMetadataByIdsAndShelfIds(idPage.getContent(), shelfIds);
|
||||
return createPageFromEntities(books, idPage, pageable);
|
||||
return createPageFromEntities(books, idPage, pageable, userId);
|
||||
}
|
||||
|
||||
private void validateShelfAccess(Long shelfId, Long userId, boolean isAdmin) {
|
||||
@@ -407,13 +414,49 @@ public class OpdsBookService {
|
||||
}
|
||||
}
|
||||
|
||||
private Page<Book> createPageFromEntities(List<BookEntity> books, Page<Long> idPage, Pageable pageable) {
|
||||
public void validateBookContentAccess(Long bookId, Long userId) {
|
||||
if (userId == null) {
|
||||
throw ApiError.FORBIDDEN.createException("Authentication required");
|
||||
}
|
||||
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId));
|
||||
|
||||
if (entity.getPermissions() != null && entity.getPermissions().isPermissionAdmin()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BookEntity book = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
boolean hasLibraryAccess = user.getAssignedLibraries().stream()
|
||||
.anyMatch(library -> library.getId().equals(book.getLibrary().getId()));
|
||||
|
||||
if (!hasLibraryAccess) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
||||
}
|
||||
|
||||
List<BookEntity> filtered = contentRestrictionService.applyRestrictions(List.of(book), userId);
|
||||
if (filtered.isEmpty()) {
|
||||
throw ApiError.FORBIDDEN.createException("You are not authorized to access this book.");
|
||||
}
|
||||
}
|
||||
|
||||
private Page<Book> createPageFromEntities(List<BookEntity> books, Page<Long> idPage, Pageable pageable, Long userId) {
|
||||
Map<Long, BookEntity> bookMap = books.stream()
|
||||
.collect(Collectors.toMap(BookEntity::getId, Function.identity()));
|
||||
|
||||
List<Book> sortedBooks = idPage.getContent().stream()
|
||||
List<BookEntity> orderedEntities = idPage.getContent().stream()
|
||||
.map(bookMap::get)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (userId != null) {
|
||||
orderedEntities = contentRestrictionService.applyRestrictions(orderedEntities, userId);
|
||||
}
|
||||
|
||||
List<Book> sortedBooks = orderedEntities.stream()
|
||||
.map(bookMapper::toBook)
|
||||
.toList();
|
||||
|
||||
|
||||
@@ -6,13 +6,16 @@ import org.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import org.booklore.model.dto.*;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.LibraryEntity;
|
||||
import org.booklore.model.entity.ShelfEntity;
|
||||
import org.booklore.model.entity.UserPermissionsEntity;
|
||||
import org.booklore.repository.BookOpdsRepository;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.ShelfRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.library.LibraryService;
|
||||
import org.booklore.service.opds.OpdsBookService;
|
||||
import org.booklore.service.restriction.ContentRestrictionService;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -36,11 +39,13 @@ import static org.mockito.Mockito.*;
|
||||
class OpdsBookServiceTest {
|
||||
|
||||
@Mock private BookOpdsRepository bookOpdsRepository;
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private UserRepository userRepository;
|
||||
@Mock private BookLoreUserTransformer bookLoreUserTransformer;
|
||||
@Mock private ShelfRepository shelfRepository;
|
||||
@Mock private LibraryService libraryService;
|
||||
@Mock private ContentRestrictionService contentRestrictionService;
|
||||
|
||||
@InjectMocks private OpdsBookService opdsBookService;
|
||||
|
||||
@@ -49,6 +54,8 @@ class OpdsBookServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mocks = MockitoAnnotations.openMocks(this);
|
||||
when(contentRestrictionService.applyRestrictions(anyList(), anyLong()))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -528,4 +535,276 @@ class OpdsBookServiceTest {
|
||||
verify(bookOpdsRepository).findBookIdsByShelfIds(eq(Set.of(10L)), any());
|
||||
}
|
||||
|
||||
// ==================== validateBookContentAccess ====================
|
||||
|
||||
@Test
|
||||
void validateBookContentAccess_throwsForbidden_whenUserIdIsNull() {
|
||||
assertThatThrownBy(() ->
|
||||
opdsBookService.validateBookContentAccess(1L, null)
|
||||
).hasMessageContaining("Authentication required");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateBookContentAccess_allowsAdmin() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
|
||||
when(entity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(entity));
|
||||
|
||||
opdsBookService.validateBookContentAccess(99L, 1L);
|
||||
|
||||
verify(bookRepository, never()).findById(anyLong());
|
||||
verify(contentRestrictionService, never()).applyRestrictions(anyList(), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateBookContentAccess_throwsForbidden_whenNoLibraryAccess() {
|
||||
BookLoreUserEntity userEntity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||
when(userEntity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
|
||||
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(bookLoreUserTransformer.toDTO(userEntity)).thenReturn(user);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(5L).watch(false).build()));
|
||||
|
||||
BookEntity book = mock(BookEntity.class);
|
||||
LibraryEntity library = mock(LibraryEntity.class);
|
||||
when(library.getId()).thenReturn(99L);
|
||||
when(book.getLibrary()).thenReturn(library);
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
opdsBookService.validateBookContentAccess(1L, 2L)
|
||||
).hasMessageContaining("You are not authorized to access this book.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateBookContentAccess_throwsForbidden_whenContentRestricted() {
|
||||
BookLoreUserEntity userEntity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||
when(userEntity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
|
||||
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(bookLoreUserTransformer.toDTO(userEntity)).thenReturn(user);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(5L).watch(false).build()));
|
||||
|
||||
BookEntity book = mock(BookEntity.class);
|
||||
LibraryEntity library = mock(LibraryEntity.class);
|
||||
when(library.getId()).thenReturn(5L);
|
||||
when(book.getLibrary()).thenReturn(library);
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
|
||||
|
||||
when(contentRestrictionService.applyRestrictions(eq(List.of(book)), eq(2L)))
|
||||
.thenReturn(List.of());
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
opdsBookService.validateBookContentAccess(1L, 2L)
|
||||
).hasMessageContaining("You are not authorized to access this book.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateBookContentAccess_allowsAccess_whenBookPassesRestrictions() {
|
||||
BookLoreUserEntity userEntity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||
when(userEntity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
|
||||
|
||||
BookLoreUser user = mock(BookLoreUser.class);
|
||||
when(bookLoreUserTransformer.toDTO(userEntity)).thenReturn(user);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(5L).watch(false).build()));
|
||||
|
||||
BookEntity book = mock(BookEntity.class);
|
||||
LibraryEntity library = mock(LibraryEntity.class);
|
||||
when(library.getId()).thenReturn(5L);
|
||||
when(book.getLibrary()).thenReturn(library);
|
||||
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
|
||||
|
||||
when(contentRestrictionService.applyRestrictions(eq(List.of(book)), eq(2L)))
|
||||
.thenReturn(List.of(book));
|
||||
|
||||
opdsBookService.validateBookContentAccess(1L, 2L);
|
||||
|
||||
verify(contentRestrictionService).applyRestrictions(eq(List.of(book)), eq(2L));
|
||||
}
|
||||
|
||||
// ==================== Content restriction filtering in feeds ====================
|
||||
|
||||
@Test
|
||||
void getBooksPage_appliesContentRestrictions_forNonAdmin() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||
when(entity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(1L)).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.getId()).thenReturn(1L);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
|
||||
|
||||
BookEntity allowedEntity = mock(BookEntity.class);
|
||||
BookEntity restrictedEntity = mock(BookEntity.class);
|
||||
when(allowedEntity.getId()).thenReturn(1L);
|
||||
when(restrictedEntity.getId()).thenReturn(2L);
|
||||
|
||||
Book allowedBook = Book.builder().id(1L).build();
|
||||
when(bookMapper.toBook(allowedEntity)).thenReturn(allowedBook);
|
||||
|
||||
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any()))
|
||||
.thenReturn(new PageImpl<>(List.of(1L, 2L)));
|
||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet()))
|
||||
.thenReturn(List.of(allowedEntity, restrictedEntity));
|
||||
|
||||
when(contentRestrictionService.applyRestrictions(anyList(), eq(1L)))
|
||||
.thenReturn(List.of(allowedEntity));
|
||||
|
||||
Page<Book> result = opdsBookService.getBooksPage(1L, null, null, null, 0, 10);
|
||||
|
||||
assertThat(result.getContent()).hasSize(1);
|
||||
assertThat(result.getContent().getFirst().getId()).isEqualTo(1L);
|
||||
verify(contentRestrictionService).applyRestrictions(anyList(), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBooksPage_skipsContentRestrictions_forAdmin() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(true);
|
||||
when(entity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(1L)).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(true);
|
||||
when(user.getId()).thenReturn(1L);
|
||||
|
||||
when(bookOpdsRepository.findBookIds(any())).thenReturn(Page.empty());
|
||||
|
||||
opdsBookService.getBooksPage(1L, null, null, null, 0, 10);
|
||||
|
||||
verify(contentRestrictionService, never()).applyRestrictions(anyList(), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentBooksPage_appliesContentRestrictions_forNonAdmin() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
when(userRepository.findById(2L)).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(false);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
|
||||
|
||||
BookEntity bookEntity = mock(BookEntity.class);
|
||||
when(bookEntity.getId()).thenReturn(1L);
|
||||
Book book = Book.builder().id(1L).build();
|
||||
when(bookMapper.toBook(bookEntity)).thenReturn(book);
|
||||
|
||||
when(bookOpdsRepository.findRecentBookIdsByLibraryIds(anySet(), any()))
|
||||
.thenReturn(new PageImpl<>(List.of(1L)));
|
||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet()))
|
||||
.thenReturn(List.of(bookEntity));
|
||||
|
||||
opdsBookService.getRecentBooksPage(2L, 0, 10);
|
||||
|
||||
verify(contentRestrictionService).applyRestrictions(anyList(), eq(2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRecentBooksPage_skipsContentRestrictions_forAdmin() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
when(userRepository.findById(1L)).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());
|
||||
|
||||
opdsBookService.getRecentBooksPage(1L, 0, 10);
|
||||
|
||||
verify(contentRestrictionService, never()).applyRestrictions(anyList(), eq(1L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getRandomBooks_appliesContentRestrictions() {
|
||||
OpdsBookService spy = Mockito.spy(opdsBookService);
|
||||
doReturn(List.of(Library.builder().id(1L).watch(false).build()))
|
||||
.when(spy).getAccessibleLibraries(2L);
|
||||
|
||||
BookEntity allowedEntity = mock(BookEntity.class);
|
||||
BookEntity restrictedEntity = mock(BookEntity.class);
|
||||
|
||||
when(bookOpdsRepository.findRandomBookIdsByLibraryIds(anyList())).thenReturn(List.of(1L, 2L));
|
||||
when(bookOpdsRepository.findAllWithMetadataByIds(anyList()))
|
||||
.thenReturn(List.of(allowedEntity, restrictedEntity));
|
||||
|
||||
when(contentRestrictionService.applyRestrictions(anyList(), eq(2L)))
|
||||
.thenReturn(List.of(allowedEntity));
|
||||
|
||||
Book book = Book.builder().id(1L).build();
|
||||
when(bookMapper.toBook(allowedEntity)).thenReturn(book);
|
||||
|
||||
List<Book> result = spy.getRandomBooks(2L, 5);
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
verify(contentRestrictionService).applyRestrictions(anyList(), eq(2L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBooksPage_contentRestrictions_filtersFromPage() {
|
||||
BookLoreUserEntity entity = mock(BookLoreUserEntity.class);
|
||||
var permissionsEntity = mock(UserPermissionsEntity.class);
|
||||
when(permissionsEntity.isPermissionAccessOpds()).thenReturn(true);
|
||||
when(permissionsEntity.isPermissionAdmin()).thenReturn(false);
|
||||
when(entity.getPermissions()).thenReturn(permissionsEntity);
|
||||
when(userRepository.findById(3L)).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.getId()).thenReturn(3L);
|
||||
when(user.getAssignedLibraries()).thenReturn(List.of(Library.builder().id(1L).watch(false).build()));
|
||||
|
||||
BookEntity book1 = mock(BookEntity.class);
|
||||
BookEntity book2 = mock(BookEntity.class);
|
||||
BookEntity book3 = mock(BookEntity.class);
|
||||
when(book1.getId()).thenReturn(1L);
|
||||
when(book2.getId()).thenReturn(2L);
|
||||
when(book3.getId()).thenReturn(3L);
|
||||
|
||||
when(bookMapper.toBook(book1)).thenReturn(Book.builder().id(1L).build());
|
||||
when(bookMapper.toBook(book3)).thenReturn(Book.builder().id(3L).build());
|
||||
|
||||
when(bookOpdsRepository.findBookIdsByLibraryIds(anySet(), any()))
|
||||
.thenReturn(new PageImpl<>(List.of(1L, 2L, 3L)));
|
||||
when(bookOpdsRepository.findAllWithMetadataByIdsAndLibraryIds(anyList(), anySet()))
|
||||
.thenReturn(List.of(book1, book2, book3));
|
||||
|
||||
when(contentRestrictionService.applyRestrictions(anyList(), eq(3L)))
|
||||
.thenReturn(List.of(book1, book3));
|
||||
|
||||
Page<Book> result = opdsBookService.getBooksPage(3L, null, null, null, 0, 10);
|
||||
|
||||
assertThat(result.getContent()).hasSize(2);
|
||||
assertThat(result.getContent()).extracting(Book::getId).containsExactly(1L, 3L);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user