Add author metadata fetching via Audnexus with browser, detail, and editor pages (#2843)

This commit is contained in:
ACX
2026-02-22 10:02:56 -07:00
committed by GitHub
parent 6bec01f286
commit 08bfafe544
57 changed files with 5578 additions and 14 deletions
@@ -0,0 +1,250 @@
package org.booklore.service;
import org.booklore.exception.APIException;
import org.booklore.model.dto.AuthorDetails;
import org.booklore.model.dto.AuthorSearchResult;
import org.booklore.model.dto.request.AuthorMatchRequest;
import org.booklore.model.entity.AuthorEntity;
import org.booklore.model.enums.AuditAction;
import org.booklore.model.enums.AuthorMetadataSource;
import org.booklore.repository.AuthorRepository;
import org.booklore.service.audit.AuditService;
import org.booklore.service.metadata.DuckDuckGoCoverService;
import org.booklore.service.metadata.parser.AuthorParser;
import org.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class AuthorMetadataServiceTest {
@Mock private AuthorRepository authorRepository;
@Mock private AuthorParser authorParser;
@Mock private AuditService auditService;
@Mock private FileService fileService;
@Mock private DuckDuckGoCoverService duckDuckGoCoverService;
private AuthorMetadataService service;
@BeforeEach
void setUp() {
Map<AuthorMetadataSource, AuthorParser> authorParserMap = Map.of(
AuthorMetadataSource.AUDNEXUS, authorParser
);
service = new AuthorMetadataService(authorRepository, authorParserMap, auditService, fileService, duckDuckGoCoverService);
}
@Test
void searchAuthorMetadata_returnsResults() {
AuthorSearchResult r1 = AuthorSearchResult.builder()
.source(AuthorMetadataSource.AUDNEXUS).asin("B000APZGGS")
.name("Stephen King").description("American author")
.imageUrl("https://example.com/king.jpg")
.build();
AuthorSearchResult r2 = AuthorSearchResult.builder()
.source(AuthorMetadataSource.AUDNEXUS).asin("B000AP1234")
.name("Stephen King Jr").description("Another author")
.imageUrl("https://example.com/kingjr.jpg")
.build();
when(authorParser.searchAuthors("Stephen King", "us")).thenReturn(List.of(r1, r2));
List<AuthorSearchResult> results = service.searchAuthorMetadata("Stephen King", "us");
assertThat(results).hasSize(2);
assertThat(results.get(0).getAsin()).isEqualTo("B000APZGGS");
assertThat(results.get(0).getSource()).isEqualTo(AuthorMetadataSource.AUDNEXUS);
assertThat(results.get(0).getName()).isEqualTo("Stephen King");
assertThat(results.get(0).getDescription()).isEqualTo("American author");
assertThat(results.get(0).getImageUrl()).isEqualTo("https://example.com/king.jpg");
assertThat(results.get(1).getAsin()).isEqualTo("B000AP1234");
}
@Test
void searchAuthorMetadata_returnsEmptyListWhenNull() {
when(authorParser.searchAuthors("Unknown", "us")).thenReturn(null);
List<AuthorSearchResult> results = service.searchAuthorMetadata("Unknown", "us");
assertThat(results).isEmpty();
}
@Test
void searchAuthorMetadata_returnsEmptyListWhenEmpty() {
when(authorParser.searchAuthors("Nobody", "us")).thenReturn(Collections.emptyList());
List<AuthorSearchResult> results = service.searchAuthorMetadata("Nobody", "us");
assertThat(results).isEmpty();
}
@Test
void matchAuthor_updatesEntityAndReturnsDetails() {
AuthorEntity author = new AuthorEntity();
author.setId(1L);
author.setName("Stephen King");
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
AuthorSearchResult result = AuthorSearchResult.builder()
.source(AuthorMetadataSource.AUDNEXUS).asin("B000APZGGS")
.description("Master of horror").imageUrl("https://example.com/king.jpg")
.name("Stephen King")
.build();
when(authorParser.getAuthorByAsin("B000APZGGS", "us")).thenReturn(result);
when(authorRepository.save(any(AuthorEntity.class))).thenAnswer(i -> i.getArgument(0));
AuthorMatchRequest request = new AuthorMatchRequest();
request.setAsin("B000APZGGS");
request.setSource(AuthorMetadataSource.AUDNEXUS);
request.setRegion("us");
AuthorDetails details = service.matchAuthor(1L, request);
assertThat(details.getId()).isEqualTo(1L);
assertThat(details.getName()).isEqualTo("Stephen King");
assertThat(details.getDescription()).isEqualTo("Master of horror");
assertThat(details.getAsin()).isEqualTo("B000APZGGS");
assertThat(author.getDescription()).isEqualTo("Master of horror");
assertThat(author.getAsin()).isEqualTo("B000APZGGS");
verify(authorRepository).save(author);
verify(fileService).createAuthorThumbnailFromUrl(eq(1L), eq("https://example.com/king.jpg"));
verify(auditService).log(eq(AuditAction.AUTHOR_METADATA_UPDATED), eq("Author"), eq(1L), anyString());
}
@Test
void matchAuthor_throwsWhenAuthorNotFound() {
when(authorRepository.findById(99L)).thenReturn(Optional.empty());
AuthorMatchRequest request = new AuthorMatchRequest();
request.setAsin("B000APZGGS");
request.setSource(AuthorMetadataSource.AUDNEXUS);
assertThatThrownBy(() -> service.matchAuthor(99L, request))
.isInstanceOf(APIException.class)
.hasMessageContaining("Author not found");
}
@Test
void matchAuthor_throwsWhenProviderReturnsNull() {
AuthorEntity author = new AuthorEntity();
author.setId(1L);
author.setName("Test Author");
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
when(authorParser.getAuthorByAsin("INVALID", "us")).thenReturn(null);
AuthorMatchRequest request = new AuthorMatchRequest();
request.setAsin("INVALID");
request.setSource(AuthorMetadataSource.AUDNEXUS);
request.setRegion("us");
assertThatThrownBy(() -> service.matchAuthor(1L, request))
.isInstanceOf(APIException.class)
.hasMessageContaining("Failed to fetch author metadata");
}
@Test
void matchAuthor_throwsWhenSourceUnsupported() {
AuthorEntity author = new AuthorEntity();
author.setId(1L);
author.setName("Test Author");
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
AuthorMatchRequest request = new AuthorMatchRequest();
request.setAsin("12345");
request.setSource(null);
request.setRegion("us");
assertThatThrownBy(() -> service.matchAuthor(1L, request))
.isInstanceOf(APIException.class)
.hasMessageContaining("Unsupported author metadata source");
}
@Test
void getAuthorDetails_returnsDetails() {
AuthorEntity author = new AuthorEntity();
author.setId(5L);
author.setName("Brandon Sanderson");
author.setDescription("Fantasy author");
author.setAsin("B001IGFHW6");
when(authorRepository.findById(5L)).thenReturn(Optional.of(author));
AuthorDetails details = service.getAuthorDetails(5L);
assertThat(details.getId()).isEqualTo(5L);
assertThat(details.getName()).isEqualTo("Brandon Sanderson");
assertThat(details.getDescription()).isEqualTo("Fantasy author");
assertThat(details.getAsin()).isEqualTo("B001IGFHW6");
}
@Test
void getAuthorDetails_throwsWhenNotFound() {
when(authorRepository.findById(99L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.getAuthorDetails(99L))
.isInstanceOf(APIException.class)
.hasMessageContaining("Author not found");
}
@Test
void getAuthorPhoto_returnsNullWhenFileDoesNotExist() {
when(fileService.getAuthorPhotoFile(1L)).thenReturn("/nonexistent/path/photo.jpg");
assertThat(service.getAuthorPhoto(1L)).isNull();
}
@Test
void getAuthorThumbnail_returnsNullWhenFileDoesNotExist() {
when(fileService.getAuthorThumbnailFile(1L)).thenReturn("/nonexistent/path/thumbnail.jpg");
assertThat(service.getAuthorThumbnail(1L)).isNull();
}
@Test
void matchAuthor_skipsPhotoWhenPhotoLocked() {
AuthorEntity author = new AuthorEntity();
author.setId(1L);
author.setName("Test Author");
author.setPhotoLocked(true);
when(authorRepository.findById(1L)).thenReturn(Optional.of(author));
AuthorSearchResult result = AuthorSearchResult.builder()
.source(AuthorMetadataSource.AUDNEXUS).asin("B000APZGGS")
.description("Bio").imageUrl("https://example.com/photo.jpg")
.name("Test Author")
.build();
when(authorParser.getAuthorByAsin("B000APZGGS", "us")).thenReturn(result);
when(authorRepository.save(any(AuthorEntity.class))).thenAnswer(i -> i.getArgument(0));
AuthorMatchRequest request = new AuthorMatchRequest();
request.setAsin("B000APZGGS");
request.setSource(AuthorMetadataSource.AUDNEXUS);
request.setRegion("us");
service.matchAuthor(1L, request);
verify(fileService, never()).createAuthorThumbnailFromUrl(anyLong(), anyString());
}
}
@@ -61,7 +61,10 @@ class BookCoverServiceTest {
private BookEntity mockBookEntity(Long id, boolean coverLocked) {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Test Title");
metadata.setAuthors(Set.of(new AuthorEntity(1L, "Author Name", null)));
AuthorEntity author = new AuthorEntity();
author.setId(1L);
author.setName("Author Name");
metadata.setAuthors(Set.of(author));
metadata.setCoverLocked(coverLocked);
BookEntity book = new BookEntity();
book.setId(id);
@@ -0,0 +1,185 @@
package org.booklore.service.metadata.parser;
import org.booklore.model.dto.AuthorSearchResult;
import org.booklore.model.enums.AuthorMetadataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class AudnexusAuthorParserTest {
@Mock private HttpClient httpClient;
private final ObjectMapper objectMapper = JsonMapper.builder().build();
private AudnexusAuthorParser parser;
@BeforeEach
void setUp() {
parser = new AudnexusAuthorParser(httpClient, objectMapper);
}
@Test
@SuppressWarnings("unchecked")
void searchAuthors_returnsResultsOnSuccess() throws Exception {
String json = """
[
{"asin": "B000APZGGS", "name": "Stephen King", "description": "Horror author", "image": "https://img.com/king.jpg"},
{"asin": "B000AP1234", "name": "Stephen King Jr", "description": "Another one", "image": null}
]
""";
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(200);
when(mockResponse.body()).thenReturn(json);
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
List<AuthorSearchResult> results = parser.searchAuthors("Stephen King", "us");
assertThat(results).hasSize(2);
assertThat(results.get(0).getAsin()).isEqualTo("B000APZGGS");
assertThat(results.get(0).getSource()).isEqualTo(AuthorMetadataSource.AUDNEXUS);
assertThat(results.get(0).getName()).isEqualTo("Stephen King");
assertThat(results.get(0).getDescription()).isEqualTo("Horror author");
assertThat(results.get(0).getImageUrl()).isEqualTo("https://img.com/king.jpg");
assertThat(results.get(1).getAsin()).isEqualTo("B000AP1234");
assertThat(results.get(1).getImageUrl()).isNull();
}
@Test
@SuppressWarnings("unchecked")
void searchAuthors_returnsEmptyListOnNon200() throws Exception {
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(500);
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
List<AuthorSearchResult> results = parser.searchAuthors("Nobody", "us");
assertThat(results).isEmpty();
}
@Test
void searchAuthors_returnsEmptyListOnException() throws Exception {
doThrow(new IOException("Connection failed")).when(httpClient).send(any(HttpRequest.class), any());
List<AuthorSearchResult> results = parser.searchAuthors("Fail", "us");
assertThat(results).isEmpty();
}
@Test
@SuppressWarnings("unchecked")
void searchAuthors_ignoresUnknownFields() throws Exception {
String json = """
[{"asin": "B000APZGGS", "name": "Author", "unknownField": "ignored", "anotherOne": 42}]
""";
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(200);
when(mockResponse.body()).thenReturn(json);
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
List<AuthorSearchResult> results = parser.searchAuthors("Author", "us");
assertThat(results).hasSize(1);
assertThat(results.get(0).getAsin()).isEqualTo("B000APZGGS");
}
@Test
@SuppressWarnings("unchecked")
void searchAuthors_sendsCorrectUrl() throws Exception {
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(200);
when(mockResponse.body()).thenReturn("[]");
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
parser.searchAuthors("Stephen King", "uk");
verify(httpClient).send(requestCaptor.capture(), any());
String uri = requestCaptor.getValue().uri().toString();
assertThat(uri).contains("api.audnex.us/authors");
assertThat(uri).contains("name=Stephen%20King");
assertThat(uri).contains("region=uk");
}
@Test
@SuppressWarnings("unchecked")
void getAuthorByAsin_returnsResultOnSuccess() throws Exception {
String json = """
{
"asin": "B000APZGGS",
"name": "Stephen King",
"description": "Master of horror fiction",
"image": "https://img.com/king.jpg",
"region": "us"
}
""";
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(200);
when(mockResponse.body()).thenReturn(json);
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
AuthorSearchResult result = parser.getAuthorByAsin("B000APZGGS", "us");
assertThat(result).isNotNull();
assertThat(result.getAsin()).isEqualTo("B000APZGGS");
assertThat(result.getSource()).isEqualTo(AuthorMetadataSource.AUDNEXUS);
assertThat(result.getName()).isEqualTo("Stephen King");
assertThat(result.getDescription()).isEqualTo("Master of horror fiction");
assertThat(result.getImageUrl()).isEqualTo("https://img.com/king.jpg");
}
@Test
@SuppressWarnings("unchecked")
void getAuthorByAsin_returnsNullOnNon200() throws Exception {
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(404);
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
AuthorSearchResult result = parser.getAuthorByAsin("INVALID", "us");
assertThat(result).isNull();
}
@Test
void getAuthorByAsin_returnsNullOnException() throws Exception {
doThrow(new IOException("Timeout")).when(httpClient).send(any(HttpRequest.class), any());
AuthorSearchResult result = parser.getAuthorByAsin("B000APZGGS", "us");
assertThat(result).isNull();
}
@Test
@SuppressWarnings("unchecked")
void getAuthorByAsin_sendsCorrectUrl() throws Exception {
HttpResponse<String> mockResponse = mock(HttpResponse.class);
when(mockResponse.statusCode()).thenReturn(200);
when(mockResponse.body()).thenReturn("{\"asin\":\"B000APZGGS\",\"name\":\"Test\"}");
doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any());
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
parser.getAuthorByAsin("B000APZGGS", "uk");
verify(httpClient).send(requestCaptor.capture(), any());
String uri = requestCaptor.getValue().uri().toString();
assertThat(uri).contains("api.audnex.us/authors/B000APZGGS");
assertThat(uri).contains("region=uk");
}
}