feat(api): add paginated author browse, facets, and ids endpoints (#2354)

Co-authored-by: James Ward <james@notjam.es>
This commit is contained in:
Zach
2026-10-12 04:31:02 -04:00
committed by GitHub
co-authored by James Ward
parent a638aa1986
commit b3a2b8816d
11 changed files with 1736 additions and 0 deletions
@@ -0,0 +1,565 @@
package org.booklore.service.browse;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.booklore.BookloreApplication;
import org.booklore.browse.BrowsePage;
import org.booklore.browse.Link;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.model.dto.AuthorSummary;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.entity.CategoryEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.entity.UserContentRestrictionEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ContentRestrictionMode;
import org.booklore.model.enums.ContentRestrictionType;
import org.booklore.model.enums.ReadStatus;
import org.booklore.model.entity.TagEntity;
import org.booklore.service.task.TaskCronService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@SpringBootTest(classes = BookloreApplication.class)
@Transactional
@TestPropertySource(properties = {
"spring.flyway.enabled=false",
"spring.jpa.hibernate.ddl-auto=create-drop",
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
"spring.datasource.url=jdbc:h2:mem:authorbrowseservicetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.datasource.username=sa",
"spring.datasource.password=",
"app.path-config=build/tmp/test-config",
"app.bookdrop-folder=build/tmp/test-bookdrop",
"spring.main.allow-bean-definition-overriding=true",
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
})
@Import(AuthorBrowseServiceTest.TestConfig.class)
class AuthorBrowseServiceTest {
@Autowired
private AuthorBrowseService browseService;
@MockitoBean
private AuthenticationService authenticationService;
@PersistenceContext
private EntityManager em;
private BookLoreUserEntity userEntity;
private LibraryEntity library;
private LibraryPathEntity libraryPath;
private final Map<String, CategoryEntity> categories = new HashMap<>();
private final Map<String, TagEntity> tags = new HashMap<>();
@TestConfiguration
public static class TestConfig {
@Bean("flyway")
@Primary
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@Primary
public TaskCronService taskCronService() {
return mock(TaskCronService.class);
}
}
@BeforeEach
void seed() {
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
em.persist(userEntity);
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
.formatPriority(List.of(BookFileType.EPUB)).build();
em.persist(library);
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
em.persist(libraryPath);
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
}
private BookLoreUser nonAdminUser() {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
return BookLoreUser.builder()
.id(userEntity.getId())
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
.permissions(permissions)
.build();
}
private BookLoreUser adminUser() {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(true);
return BookLoreUser.builder()
.id(userEntity.getId())
.assignedLibraries(List.of())
.permissions(permissions)
.build();
}
private AuthorEntity author(String name) {
AuthorEntity author = AuthorEntity.builder().name(name).build();
em.persist(author);
return author;
}
private BookEntity book(String title, LibraryEntity lib, LibraryPathEntity path, List<AuthorEntity> authors) {
return book(title, lib, path, authors, null, null, null);
}
private BookEntity book(String title, LibraryEntity lib, LibraryPathEntity path, List<AuthorEntity> authors,
String seriesName, List<String> categoryNames, String language) {
BookEntity bookEntity = BookEntity.builder()
.library(lib).libraryPath(path).addedOn(Instant.now()).deleted(false).build();
em.persist(bookEntity);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(bookEntity).title(title).seriesName(seriesName).language(language).build();
metadata.setAuthors(new java.util.ArrayList<>(authors));
if (categoryNames != null) {
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
}
em.persist(metadata);
bookEntity.setMetadata(metadata);
return bookEntity;
}
private CategoryEntity category(String name) {
return categories.computeIfAbsent(name, n -> {
CategoryEntity e = CategoryEntity.builder().name(n).build();
em.persist(e);
return e;
});
}
private TagEntity tag(String name) {
return tags.computeIfAbsent(name, n -> {
TagEntity e = TagEntity.builder().name(n).build();
em.persist(e);
return e;
});
}
private void progress(BookEntity book, ReadStatus status) {
progress(book, status, null);
}
private void progress(BookEntity book, ReadStatus status, Integer personalRating) {
em.persist(UserBookProgressEntity.builder()
.user(userEntity).book(book).readStatus(status).lastReadTime(Instant.now())
.personalRating(personalRating).build());
}
private BrowsePage<AuthorSummary> browse(String sort, List<String> facet, String query, String cursor, int page, int size) {
return browse(sort, facet, null, query, cursor, page, size);
}
private BrowsePage<AuthorSummary> browse(String sort, List<String> facet, String facetLogic, String query, String cursor, int page, int size) {
return browseService.browse(sort, facet, facetLogic, query, cursor, PageRequest.of(page, size));
}
private List<Long> ids(BrowsePage<AuthorSummary> page) {
return page.content().stream().map(AuthorSummary::getId).toList();
}
@Test
void returnsPageWithTotalsAndCursorAndLinks() {
AuthorEntity alice = author("Alice");
AuthorEntity bob = author("Bob");
book("A", library, libraryPath, List.of(alice));
book("B", library, libraryPath, List.of(bob));
em.flush();
BrowsePage<AuthorSummary> result = browse(null, null, null, null, 0, 20);
assertThat(result.content()).hasSize(2);
assertThat(result.page().totalElements()).isEqualTo(2);
assertThat(result.page().cursor()).isNotBlank();
assertThat(result.links().stream().anyMatch(l -> l.rel().contains("self"))).isTrue();
}
@Test
void sortByNameAndSortName() {
AuthorEntity zeta = author("Zeta Abbott");
AuthorEntity anna = author("Anna Zimmer");
book("A", library, libraryPath, List.of(zeta));
book("B", library, libraryPath, List.of(anna));
em.flush();
assertThat(ids(browse("name", null, null, null, 0, 20))).containsExactly(anna.getId(), zeta.getId());
assertThat(ids(browse("-name", null, null, null, 0, 20))).containsExactly(zeta.getId(), anna.getId());
assertThat(ids(browse("sortName", null, null, null, 0, 20))).containsExactly(zeta.getId(), anna.getId());
}
@Test
void sortByBookCount() {
AuthorEntity prolific = author("Prolific");
AuthorEntity oneHit = author("One Hit");
book("A", library, libraryPath, List.of(prolific));
book("B", library, libraryPath, List.of(prolific));
book("C", library, libraryPath, List.of(oneHit));
em.flush();
BrowsePage<AuthorSummary> result = browse("-bookCount", null, null, null, 0, 20);
assertThat(ids(result)).containsExactly(prolific.getId(), oneHit.getId());
assertThat(result.content().get(0).getBookCount()).isEqualTo(2);
assertThat(result.content().get(1).getBookCount()).isEqualTo(1);
}
@Test
void sortBySeriesCountAndAddedOn() {
AuthorEntity serial = author("Serial");
AuthorEntity standalone = author("Standalone");
book("S1", library, libraryPath, List.of(serial), "Saga", null, null)
.setAddedOn(Instant.parse("2024-01-01T00:00:00Z"));
book("S2", library, libraryPath, List.of(serial), "Other Saga", null, null)
.setAddedOn(Instant.parse("2024-02-01T00:00:00Z"));
book("Solo", library, libraryPath, List.of(standalone))
.setAddedOn(Instant.parse("2024-03-01T00:00:00Z"));
em.flush();
assertThat(ids(browse("-seriesCount", null, null, null, 0, 20)))
.containsExactly(serial.getId(), standalone.getId());
assertThat(ids(browse("-addedOn", null, null, null, 0, 20)))
.containsExactly(standalone.getId(), serial.getId());
assertThat(ids(browse("addedOn", null, null, null, 0, 20)))
.containsExactly(serial.getId(), standalone.getId());
}
@Test
void sortByLastReadTimeAndAvgRating() {
AuthorEntity read = author("Read Author");
AuthorEntity unread = author("Unread Author");
BookEntity readBook = book("R", library, libraryPath, List.of(read));
BookEntity unreadBook = book("U", library, libraryPath, List.of(unread));
readBook.getMetadata().setGoodreadsRating(2.0);
unreadBook.getMetadata().setGoodreadsRating(4.5);
progress(readBook, ReadStatus.READ, 5);
em.flush();
assertThat(ids(browse("-lastReadTime", null, null, null, 0, 20)))
.containsExactly(read.getId(), unread.getId());
assertThat(ids(browse("-goodreadsRating", null, null, null, 0, 20)))
.containsExactly(unread.getId(), read.getId());
assertThat(ids(browse("goodreadsRating", null, null, null, 0, 20)))
.containsExactly(read.getId(), unread.getId());
assertThat(ids(browse("-personalRating", null, null, null, 0, 20)))
.containsExactly(read.getId(), unread.getId());
}
@Test
void facetLogicCombinesSelectedValues() {
AuthorEntity horrorOnly = author("Horror Only");
AuthorEntity romanceOnly = author("Romance Only");
AuthorEntity both = author("Both");
AuthorEntity neither = author("Neither");
book("H", library, libraryPath, List.of(horrorOnly), null, List.of("Horror"), null);
book("R", library, libraryPath, List.of(romanceOnly), null, List.of("Romance"), null);
book("B", library, libraryPath, List.of(both), null, List.of("Horror", "Romance"), null);
book("N", library, libraryPath, List.of(neither), null, List.of("Fantasy"), null);
em.flush();
List<String> facets = List.of("genre:Horror", "genre:Romance");
assertThat(ids(browse("name", facets, "or", null, null, 0, 20)))
.containsExactly(both.getId(), horrorOnly.getId(), romanceOnly.getId());
assertThat(ids(browse("name", facets, "and", null, null, 0, 20)))
.containsExactly(both.getId());
assertThat(ids(browse("name", facets, "not", null, null, 0, 20)))
.containsExactly(neither.getId());
}
@Test
void queryFiltersOnNameAndAsin() {
AuthorEntity tolkien = author("J.R.R. Tolkien");
tolkien.setAsin("B000AP9A6K");
AuthorEntity herbert = author("Frank Herbert");
book("A", library, libraryPath, List.of(tolkien));
book("B", library, libraryPath, List.of(herbert));
em.flush();
assertThat(ids(browse(null, null, "tolkien", null, 0, 20))).containsExactly(tolkien.getId());
assertThat(ids(browse(null, null, "b000ap9a6k", null, 0, 20))).containsExactly(tolkien.getId());
}
@Test
void hasAsinFacetIsApplied() {
AuthorEntity matched = author("Matched");
matched.setAsin("B0FAKE");
AuthorEntity unmatched = author("Unmatched");
book("A", library, libraryPath, List.of(matched));
book("B", library, libraryPath, List.of(unmatched));
em.flush();
assertThat(ids(browse(null, List.of("has_asin:true"), null, null, 0, 20))).containsExactly(matched.getId());
assertThat(ids(browse(null, List.of("has_asin:false"), null, null, 0, 20))).containsExactly(unmatched.getId());
}
@Test
void hasDescriptionFacetIsApplied() {
AuthorEntity documented = author("Documented");
documented.setDescription("Has a bio.");
AuthorEntity bare = author("Bare");
book("A", library, libraryPath, List.of(documented));
book("B", library, libraryPath, List.of(bare));
em.flush();
assertThat(ids(browse(null, List.of("has_description:true"), null, null, 0, 20)))
.containsExactly(documented.getId());
}
@Test
void bookCountRangeFacetIsApplied() {
AuthorEntity one = author("One");
AuthorEntity three = author("Three");
book("A", library, libraryPath, List.of(one));
for (int i = 0; i < 3; i++) {
book("B" + i, library, libraryPath, List.of(three));
}
em.flush();
assertThat(ids(browse(null, List.of("book_count:1"), null, null, 0, 20))).containsExactly(one.getId());
assertThat(ids(browse(null, List.of("book_count:2-"), null, null, 0, 20))).containsExactly(three.getId());
assertThat(ids(browse(null, List.of("book_count:-2"), null, null, 0, 20))).containsExactly(one.getId());
assertThat(ids(browse(null, List.of("book_count:1-3"), null, null, 0, 20)))
.containsExactlyInAnyOrder(one.getId(), three.getId());
}
@Test
void invalidBookCountRangeIsRejected() {
assertThatThrownBy(() -> browse(null, List.of("book_count:abc"), null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
assertThatThrownBy(() -> browse(null, List.of("book_count:5-2"), null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST));
}
@Test
void genreAndLanguageFacetsAreApplied() {
AuthorEntity horror = author("Horror Writer");
AuthorEntity romance = author("Romance Writer");
book("H", library, libraryPath, List.of(horror), null, List.of("Horror"), "en");
book("R", library, libraryPath, List.of(romance), null, List.of("Romance"), "fr");
em.flush();
assertThat(ids(browse(null, List.of("genre:Horror"), null, null, 0, 20))).containsExactly(horror.getId());
assertThat(ids(browse(null, List.of("language:fr"), null, null, 0, 20))).containsExactly(romance.getId());
}
@Test
void libraryFacetIsApplied() {
LibraryEntity otherLibrary = LibraryEntity.builder().name("Other").icon("book").watch(false)
.formatPriority(List.of(BookFileType.EPUB)).build();
em.persist(otherLibrary);
LibraryPathEntity otherPath = LibraryPathEntity.builder().library(otherLibrary).path("/o").build();
em.persist(otherPath);
when(authenticationService.getAuthenticatedUser()).thenReturn(adminUser());
AuthorEntity here = author("Here");
AuthorEntity there = author("There");
book("A", library, libraryPath, List.of(here));
book("B", otherLibrary, otherPath, List.of(there));
em.flush();
assertThat(ids(browse(null, List.of("library:" + library.getId()), null, null, 0, 20)))
.containsExactly(here.getId());
}
@Test
void readStatusFacetUsesBookVocabulary() {
AuthorEntity finished = author("Finished");
AuthorEntity reading = author("Reading");
AuthorEntity unsetRow = author("Unset Row");
AuthorEntity untouched = author("Untouched");
BookEntity f = book("F", library, libraryPath, List.of(finished));
progress(f, ReadStatus.READ);
BookEntity r = book("R", library, libraryPath, List.of(reading));
progress(r, ReadStatus.READING);
BookEntity u = book("U", library, libraryPath, List.of(unsetRow));
progress(u, ReadStatus.UNSET);
book("N", library, libraryPath, List.of(untouched));
em.flush();
assertThat(ids(browse(null, List.of("read_status:READ"), null, null, 0, 20)))
.containsExactly(finished.getId());
assertThat(ids(browse(null, List.of("read_status:reading"), null, null, 0, 20)))
.containsExactly(reading.getId());
assertThat(ids(browse(null, List.of("read_status:UNSET"), null, null, 0, 20)))
.containsExactlyInAnyOrder(unsetRow.getId(), untouched.getId());
assertThatThrownBy(() -> browse(null, List.of("read_status:some_read"), null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("Invalid read_status value");
}
@Test
void nonAdminSeesOnlyAuthorsWithVisibleBooks() {
LibraryEntity otherLibrary = LibraryEntity.builder().name("Other").icon("book").watch(false)
.formatPriority(List.of(BookFileType.EPUB)).build();
em.persist(otherLibrary);
LibraryPathEntity otherPath = LibraryPathEntity.builder().library(otherLibrary).path("/o").build();
em.persist(otherPath);
AuthorEntity visible = author("Visible");
AuthorEntity hidden = author("Hidden");
AuthorEntity bookless = author("Bookless");
book("In", library, libraryPath, List.of(visible));
book("Out", otherLibrary, otherPath, List.of(hidden));
em.flush();
assertThat(ids(browse(null, null, null, null, 0, 20))).containsExactly(visible.getId());
when(authenticationService.getAuthenticatedUser()).thenReturn(adminUser());
assertThat(ids(browse("name", null, null, null, 0, 20)))
.containsExactly(bookless.getId(), hidden.getId(), visible.getId());
}
@Test
void nonAdminWithNoLibrariesSeesNothing() {
AuthorEntity a = author("Alice");
book("A", library, libraryPath, List.of(a));
em.flush();
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
when(authenticationService.getAuthenticatedUser()).thenReturn(BookLoreUser.builder()
.id(userEntity.getId())
.assignedLibraries(List.of())
.permissions(permissions)
.build());
BrowsePage<AuthorSummary> result = browse(null, null, null, null, 0, 20);
assertThat(result.content()).isEmpty();
assertThat(result.page().totalElements()).isZero();
assertThat(browseService.findAllIds(null, null, null, null)).isEmpty();
}
@Test
void contentRestrictionsHideAuthorsAndTheirCounts() {
em.persist(UserContentRestrictionEntity.builder()
.user(userEntity)
.restrictionType(ContentRestrictionType.TAG)
.mode(ContentRestrictionMode.EXCLUDE)
.value("adult")
.build());
AuthorEntity clean = author("Clean");
AuthorEntity mixed = author("Mixed");
AuthorEntity restricted = author("Restricted");
book("C", library, libraryPath, List.of(clean));
book("M1", library, libraryPath, List.of(mixed));
BookEntity m2 = book("M2", library, libraryPath, List.of(mixed));
m2.getMetadata().setTags(java.util.Set.of(tag("adult")));
BookEntity r = book("R", library, libraryPath, List.of(restricted));
r.getMetadata().setTags(java.util.Set.of(tag("adult")));
em.flush();
BrowsePage<AuthorSummary> result = browse("name", null, null, null, 0, 20);
assertThat(ids(result)).containsExactly(clean.getId(), mixed.getId());
AuthorSummary mixedSummary = result.content().get(1);
assertThat(mixedSummary.getBookCount()).isEqualTo(1);
}
@Test
void cursorWalkIsConsistent() {
for (int i = 0; i < 5; i++) {
AuthorEntity a = author(String.format("Author%02d", i));
book("B" + i, library, libraryPath, List.of(a));
}
em.flush();
BrowsePage<AuthorSummary> page0 = browse("name", null, null, null, 0, 2);
assertThat(page0.content()).hasSize(2);
assertThat(page0.page().totalElements()).isEqualTo(5);
Link next = page0.links().stream().filter(l -> l.rel().contains("next")).findFirst().orElseThrow();
String cursor = next.href().substring(next.href().indexOf("cursor=") + "cursor=".length());
BrowsePage<AuthorSummary> page1 = browse("name", null, null, cursor, 0, 2);
assertThat(page1.content()).hasSize(2);
assertThat(ids(page1)).doesNotContainAnyElementsOf(ids(page0));
}
@Test
void cursorWithConflictingFacetsIsRejected() {
AuthorEntity a = author("Alice");
book("A", library, libraryPath, List.of(a));
em.flush();
String cursor = browse(null, null, null, null, 0, 20).page().cursor();
assertThatThrownBy(() -> browse(null, List.of("has_asin:true"), null, cursor, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("does not match");
}
@Test
void unknownSortAndFacetAreRejected() {
assertThatThrownBy(() -> browse("title", null, null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("Unknown sort key");
assertThatThrownBy(() -> browse(null, List.of("shoe_size:12"), null, null, 0, 20))
.isInstanceOfSatisfying(APIException.class, e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST))
.hasMessageContaining("Unknown facet");
}
@Test
void findAllIdsMatchesPageOrderingForSameFilters() {
for (int i = 0; i < 5; i++) {
AuthorEntity a = author(String.format("Author%02d", i));
book("B" + i, library, libraryPath, List.of(a));
}
em.flush();
List<Long> pageIds = ids(browse("name", null, null, null, 0, 20));
assertThat(browseService.findAllIds("name", null, null, null)).isEqualTo(pageIds);
}
@Test
void findAllIdsAppliesFacets() {
AuthorEntity matched = author("Matched");
matched.setAsin("B0FAKE");
AuthorEntity unmatched = author("Unmatched");
book("A", library, libraryPath, List.of(matched));
book("B", library, libraryPath, List.of(unmatched));
em.flush();
assertThat(browseService.findAllIds(null, List.of("has_asin:true"), null, null))
.containsExactly(matched.getId());
}
}
@@ -0,0 +1,295 @@
package org.booklore.service.browse;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.booklore.BookloreApplication;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.Library;
import org.booklore.model.dto.browse.FacetGroupsResponse;
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetGroup;
import org.booklore.model.dto.browse.FacetGroupsResponse.FacetLink;
import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.model.entity.CategoryEntity;
import org.booklore.model.entity.LibraryEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.service.task.TaskCronService;
import org.booklore.util.FileService;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@SpringBootTest(classes = BookloreApplication.class)
@Transactional
@TestPropertySource(properties = {
"spring.flyway.enabled=false",
"spring.jpa.hibernate.ddl-auto=create-drop",
"spring.jpa.database-platform=org.hibernate.dialect.H2Dialect",
"spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect",
"spring.datasource.url=jdbc:h2:mem:authorfacetservicetest;DB_CLOSE_DELAY=-1;NON_KEYWORDS=VALUE",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.datasource.username=sa",
"spring.datasource.password=",
"app.path-config=build/tmp/test-config",
"app.bookdrop-folder=build/tmp/test-bookdrop",
"spring.main.allow-bean-definition-overriding=true",
"spring.task.scheduling.enabled=false",
"app.task.scan-library-cron=*/1 * * * * *",
"app.task.process-bookdrop-cron=*/1 * * * * *",
"app.features.oidc-enabled=false"
})
@Import(AuthorFacetServiceTest.TestConfig.class)
class AuthorFacetServiceTest {
@Autowired
private AuthorFacetService facetService;
@Autowired
private AuthorPhotoIndex photoIndex;
@Autowired
private FileService fileService;
@MockitoBean
private AuthenticationService authenticationService;
@PersistenceContext
private EntityManager em;
private BookLoreUserEntity userEntity;
private LibraryEntity library;
private LibraryPathEntity libraryPath;
private final Map<String, CategoryEntity> categories = new HashMap<>();
@TestConfiguration
public static class TestConfig {
@Bean("flyway")
@Primary
public Flyway flyway() {
return mock(Flyway.class);
}
@Bean
@Primary
public TaskCronService taskCronService() {
return mock(TaskCronService.class);
}
}
@BeforeEach
void seed() throws IOException {
facetService.clearCache();
photoIndex.clearCache();
deleteAuthorImages();
userEntity = BookLoreUserEntity.builder().username("reader").passwordHash("x").name("Reader").build();
em.persist(userEntity);
library = LibraryEntity.builder().name("Lib").icon("book").watch(false)
.formatPriority(List.of(BookFileType.EPUB)).build();
em.persist(library);
libraryPath = LibraryPathEntity.builder().library(library).path("/p").build();
em.persist(libraryPath);
when(authenticationService.getAuthenticatedUser()).thenReturn(nonAdminUser());
}
@AfterEach
void cleanUpAuthorImages() throws IOException {
deleteAuthorImages();
}
private void deleteAuthorImages() throws IOException {
Path imagesRoot = Paths.get(fileService.getAuthorImagesRoot());
if (Files.isDirectory(imagesRoot)) {
try (Stream<Path> paths = Files.walk(imagesRoot)) {
paths.sorted(Comparator.reverseOrder()).forEach(p -> {
try {
Files.delete(p);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}
private BookLoreUser nonAdminUser() {
BookLoreUser.UserPermissions permissions = new BookLoreUser.UserPermissions();
permissions.setAdmin(false);
return BookLoreUser.builder()
.id(userEntity.getId())
.assignedLibraries(List.of(Library.builder().id(library.getId()).build()))
.permissions(permissions)
.build();
}
private AuthorEntity author(String name) {
AuthorEntity author = AuthorEntity.builder().name(name).build();
em.persist(author);
return author;
}
private void book(String title, List<AuthorEntity> authors, List<String> categoryNames, String language) {
BookEntity bookEntity = BookEntity.builder()
.library(library).libraryPath(libraryPath).addedOn(Instant.now()).deleted(false).build();
em.persist(bookEntity);
BookMetadataEntity metadata = BookMetadataEntity.builder()
.book(bookEntity).title(title).language(language).build();
metadata.setAuthors(new ArrayList<>(authors));
if (categoryNames != null) {
metadata.setCategories(categoryNames.stream().map(this::category).collect(Collectors.toSet()));
}
em.persist(metadata);
bookEntity.setMetadata(metadata);
}
private CategoryEntity category(String name) {
return categories.computeIfAbsent(name, n -> {
CategoryEntity e = CategoryEntity.builder().name(n).build();
em.persist(e);
return e;
});
}
private FacetGroup group(FacetGroupsResponse response, String key) {
return response.facets().stream()
.filter(g -> g.metadata().key().equals(key))
.findFirst().orElseThrow();
}
private Long count(FacetGroup group, String value) {
return group.links().stream()
.filter(l -> l.value().equals(value))
.findFirst()
.map(l -> l.properties().numberOfItems())
.orElse(0L);
}
@Test
void returnsSortGroupAndFacetGroupsWithCounts() {
AuthorEntity matched = author("Matched");
matched.setAsin("B0FAKE");
matched.setDescription("Bio");
AuthorEntity unmatched = author("Unmatched");
book("A", List.of(matched), List.of("Horror"), "en");
book("B", List.of(unmatched), List.of("Romance", "Horror"), "fr");
em.flush();
FacetGroupsResponse response = facetService.getFacets(null, null, null);
FacetGroup sort = group(response, "sort");
assertThat(sort.metadata().rel()).isEqualTo("sort");
assertThat(sort.links().stream().map(FacetLink::value))
.contains("name", "-name", "bookCount", "-bookCount", "amazonRating", "-personalRating");
assertThat(sort.links().stream().map(FacetLink::value)).doesNotContain("id", "-id");
assertThat(count(group(response, "has_asin"), "true")).isEqualTo(1);
assertThat(count(group(response, "has_asin"), "false")).isEqualTo(1);
assertThat(count(group(response, "has_description"), "true")).isEqualTo(1);
FacetGroup genre = group(response, "genre");
assertThat(count(genre, "Horror")).isEqualTo(2);
assertThat(count(genre, "Romance")).isEqualTo(1);
FacetGroup language = group(response, "language");
assertThat(count(language, "en")).isEqualTo(1);
assertThat(count(language, "fr")).isEqualTo(1);
assertThat(response.facets().stream().map(g -> g.metadata().key()))
.doesNotContain("book_count", "library", "read_status");
}
@Test
void hasPhotoFacetCountsFromDisk() throws IOException {
AuthorEntity photographed = author("Photographed");
AuthorEntity faceless = author("Faceless");
book("A", List.of(photographed), null, null);
book("B", List.of(faceless), null, null);
em.flush();
Path thumbnail = Paths.get(fileService.getAuthorThumbnailFile(photographed.getId()));
Files.createDirectories(thumbnail.getParent());
Files.write(thumbnail, new byte[]{1});
FacetGroupsResponse response = facetService.getFacets(null, null, null);
assertThat(count(group(response, "has_photo"), "true")).isEqualTo(1);
assertThat(count(group(response, "has_photo"), "false")).isEqualTo(1);
}
@Test
void ownFacetSelectionsAreOmittedFromItsCounts() {
AuthorEntity matched = author("Matched");
matched.setAsin("B0FAKE");
AuthorEntity unmatched = author("Unmatched");
book("A", List.of(matched), List.of("Horror"), null);
book("B", List.of(unmatched), List.of("Romance"), null);
em.flush();
FacetGroupsResponse response = facetService.getFacets(List.of("has_asin:true"), null, null);
assertThat(count(group(response, "has_asin"), "false")).isEqualTo(1);
assertThat(count(group(response, "genre"), "Horror")).isEqualTo(1);
assertThat(group(response, "genre").links().stream().map(FacetLink::value))
.doesNotContain("Romance");
}
@Test
void zeroCountValuesAreOmitted() {
AuthorEntity unmatched = author("Unmatched");
book("A", List.of(unmatched), null, null);
em.flush();
FacetGroupsResponse response = facetService.getFacets(null, null, null);
assertThat(group(response, "has_asin").links().stream().map(FacetLink::value))
.containsExactly("false");
}
@Test
void activeFacetLinksCarrySelfRel() {
AuthorEntity matched = author("Matched");
matched.setAsin("B0FAKE");
AuthorEntity unmatched = author("Unmatched");
book("A", List.of(matched), null, null);
book("B", List.of(unmatched), null, null);
em.flush();
FacetGroupsResponse response = facetService.getFacets(List.of("has_asin:true"), null, null);
FacetLink active = group(response, "has_asin").links().stream()
.filter(l -> l.value().equals("true"))
.findFirst().orElseThrow();
assertThat(active.rel()).contains("self", "facet");
Set<String> hrefs = group(response, "has_asin").links().stream()
.map(FacetLink::href).collect(Collectors.toSet());
assertThat(hrefs).allSatisfy(href -> assertThat(href).startsWith("/api/v1/authors/page"));
}
}