Add author metadata fetching via Audnexus with browser, detail, and editor pages (#2843)
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import org.booklore.model.enums.AuthorMetadataSource;
|
||||
import org.booklore.service.metadata.parser.AudnexusAuthorParser;
|
||||
import org.booklore.service.metadata.parser.AuthorParser;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
public class AuthorParserConfig {
|
||||
|
||||
@Bean
|
||||
public Map<AuthorMetadataSource, AuthorParser> authorParserMap(AudnexusAuthorParser audnexusAuthorParser) {
|
||||
return Map.of(
|
||||
AuthorMetadataSource.AUDNEXUS, audnexusAuthorParser
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,25 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.model.dto.AuthorDetails;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.CoverImage;
|
||||
import org.booklore.model.dto.request.AuthorMatchRequest;
|
||||
import org.booklore.model.dto.request.AuthorUpdateRequest;
|
||||
import org.booklore.service.AuthorMetadataService;
|
||||
import org.booklore.service.AuthorService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import reactor.core.publisher.Flux;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -18,6 +30,22 @@ import java.util.List;
|
||||
public class AuthorController {
|
||||
|
||||
private final AuthorService authorService;
|
||||
private final AuthorMetadataService authorMetadataService;
|
||||
|
||||
@Operation(summary = "Get all authors", description = "Retrieve all authors with book counts.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors returned successfully")
|
||||
@GetMapping
|
||||
public ResponseEntity<List<AuthorSummary>> getAllAuthors() {
|
||||
return ResponseEntity.ok(authorMetadataService.getAllAuthors());
|
||||
}
|
||||
|
||||
@Operation(summary = "Find author by name", description = "Find an author by exact name (case-insensitive).")
|
||||
@ApiResponse(responseCode = "200", description = "Author found successfully")
|
||||
@GetMapping("/by-name")
|
||||
public ResponseEntity<AuthorDetails> getAuthorByName(
|
||||
@Parameter(description = "Author name") @RequestParam("name") String name) {
|
||||
return ResponseEntity.ok(authorMetadataService.getAuthorByName(name));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get authors by book ID", description = "Retrieve a list of authors for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors returned successfully")
|
||||
@@ -26,4 +54,111 @@ public class AuthorController {
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(authorService.getAuthorsByBookId(bookId));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get author details", description = "Retrieve author details including metadata.")
|
||||
@ApiResponse(responseCode = "200", description = "Author details returned successfully")
|
||||
@GetMapping("/{authorId}")
|
||||
public ResponseEntity<AuthorDetails> getAuthorDetails(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId) {
|
||||
return ResponseEntity.ok(authorMetadataService.getAuthorDetails(authorId));
|
||||
}
|
||||
|
||||
@Operation(summary = "Update author", description = "Update author details such as name, description, and ASIN.")
|
||||
@ApiResponse(responseCode = "200", description = "Author updated successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PutMapping("/{authorId}")
|
||||
public ResponseEntity<AuthorDetails> updateAuthor(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestBody AuthorUpdateRequest request) {
|
||||
return ResponseEntity.ok(authorMetadataService.updateAuthor(authorId, request));
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload author photo", description = "Upload a photo for an author from a file.")
|
||||
@ApiResponse(responseCode = "200", description = "Author photo uploaded successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping("/{authorId}/photo/upload")
|
||||
public ResponseEntity<Void> uploadAuthorPhoto(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@Parameter(description = "Photo image file") @RequestParam("file") MultipartFile file) {
|
||||
authorMetadataService.uploadAuthorPhoto(authorId, file);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Search author metadata", description = "Search external providers for author metadata candidates.")
|
||||
@ApiResponse(responseCode = "200", description = "Search results returned successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@GetMapping("/{authorId}/search-metadata")
|
||||
public ResponseEntity<List<AuthorSearchResult>> searchAuthorMetadata(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@Parameter(description = "Author name to search") @RequestParam("q") String query,
|
||||
@Parameter(description = "Region for provider lookup") @RequestParam(defaultValue = "us") String region) {
|
||||
return ResponseEntity.ok(authorMetadataService.searchAuthorMetadata(query, region));
|
||||
}
|
||||
|
||||
@Operation(summary = "Match author metadata", description = "Match an author with an external provider result to populate metadata.")
|
||||
@ApiResponse(responseCode = "200", description = "Author matched successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping("/{authorId}/match")
|
||||
public ResponseEntity<AuthorDetails> matchAuthor(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestBody AuthorMatchRequest request) {
|
||||
return ResponseEntity.ok(authorMetadataService.matchAuthor(authorId, request));
|
||||
}
|
||||
|
||||
@Operation(summary = "Quick-match author", description = "Search and match an author with the first result in a single call.")
|
||||
@ApiResponse(responseCode = "200", description = "Author quick-matched successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping("/{authorId}/quick-match")
|
||||
public ResponseEntity<AuthorDetails> quickMatchAuthor(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestParam(defaultValue = "us") String region) {
|
||||
return ResponseEntity.ok(authorMetadataService.quickMatchAuthor(authorId, region));
|
||||
}
|
||||
|
||||
@Operation(summary = "Auto-match authors", description = "Automatically match multiple authors, streaming results as each is matched.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors auto-matched successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping(value = "/auto-match", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public Flux<AuthorSummary> autoMatchAuthors(@RequestBody List<Long> authorIds) {
|
||||
return authorMetadataService.autoMatchAuthors(authorIds);
|
||||
}
|
||||
|
||||
@Operation(summary = "Unmatch authors", description = "Clear metadata for multiple authors.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors unmatched successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping("/unmatch")
|
||||
public ResponseEntity<Void> unmatchAuthors(@RequestBody List<Long> authorIds) {
|
||||
authorMetadataService.unmatchAuthors(authorIds);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Search author photos", description = "Search for author photos using DuckDuckGo image search.")
|
||||
@ApiResponse(responseCode = "200", description = "Photo search results returned successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@GetMapping("/{authorId}/search-photos")
|
||||
public ResponseEntity<List<CoverImage>> searchAuthorPhotos(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@Parameter(description = "Author name to search") @RequestParam("q") String query) {
|
||||
return ResponseEntity.ok(authorMetadataService.searchAuthorPhotos(query));
|
||||
}
|
||||
|
||||
@Operation(summary = "Upload author photo from URL", description = "Download an image from a URL and save it as the author's photo.")
|
||||
@ApiResponse(responseCode = "200", description = "Author photo saved successfully")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
@PostMapping("/{authorId}/photo/url")
|
||||
public ResponseEntity<Void> uploadAuthorPhotoFromUrl(
|
||||
@Parameter(description = "ID of the author") @PathVariable long authorId,
|
||||
@RequestParam("url") String imageUrl) {
|
||||
authorMetadataService.uploadAuthorPhotoFromUrl(authorId, imageUrl);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@Operation(summary = "Delete authors", description = "Delete multiple authors and their associated images.")
|
||||
@ApiResponse(responseCode = "200", description = "Authors deleted successfully")
|
||||
@PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()")
|
||||
@DeleteMapping
|
||||
public ResponseEntity<Void> deleteAuthors(@RequestBody List<Long> authorIds) {
|
||||
authorMetadataService.deleteAuthors(authorIds);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.booklore.controller;
|
||||
|
||||
import org.booklore.service.AuthorMetadataService;
|
||||
import org.booklore.service.book.BookService;
|
||||
import org.booklore.service.bookdrop.BookDropService;
|
||||
import org.booklore.service.reader.CbxReaderService;
|
||||
@@ -26,6 +27,7 @@ public class BookMediaController {
|
||||
private final BookService bookService;
|
||||
private final CbxReaderService cbxReaderService;
|
||||
private final BookDropService bookDropService;
|
||||
private final AuthorMetadataService authorMetadataService;
|
||||
|
||||
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
|
||||
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
|
||||
@@ -67,6 +69,28 @@ public class BookMediaController {
|
||||
cbxReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get author photo", description = "Retrieve the photo for a specific author.")
|
||||
@ApiResponse(responseCode = "200", description = "Author photo returned successfully")
|
||||
@GetMapping("/author/{authorId}/photo")
|
||||
public ResponseEntity<Resource> getAuthorPhoto(@Parameter(description = "ID of the author") @PathVariable long authorId) {
|
||||
Resource photo = authorMetadataService.getAuthorPhoto(authorId);
|
||||
if (photo == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(photo);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get author thumbnail", description = "Retrieve the thumbnail for a specific author.")
|
||||
@ApiResponse(responseCode = "200", description = "Author thumbnail returned successfully")
|
||||
@GetMapping("/author/{authorId}/thumbnail")
|
||||
public ResponseEntity<Resource> getAuthorThumbnail(@Parameter(description = "ID of the author") @PathVariable long authorId) {
|
||||
Resource thumbnail = authorMetadataService.getAuthorThumbnail(authorId);
|
||||
if (thumbnail == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(thumbnail);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.")
|
||||
@ApiResponse(responseCode = "200", description = "Bookdrop cover returned successfully")
|
||||
@GetMapping("/bookdrop/{bookdropId}/cover")
|
||||
|
||||
@@ -63,7 +63,8 @@ public enum ApiError {
|
||||
PERMISSION_DENIED(HttpStatus.FORBIDDEN, "Permission denied: %s"),
|
||||
LIBRARY_PATH_NOT_ACCESSIBLE(HttpStatus.SERVICE_UNAVAILABLE, "Library scan aborted: path not accessible or empty: %s"),
|
||||
FORMAT_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "File format '%s' is not allowed in library '%s'"),
|
||||
RATE_LIMITED(HttpStatus.TOO_MANY_REQUESTS, "Too many failed login attempts. Please try again later.");
|
||||
RATE_LIMITED(HttpStatus.TOO_MANY_REQUESTS, "Too many failed login attempts. Please try again later."),
|
||||
AUTHOR_NOT_FOUND(HttpStatus.NOT_FOUND, "Author not found with ID: %d");
|
||||
|
||||
private final HttpStatus status;
|
||||
private final String message;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AuthorDetails {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String asin;
|
||||
private boolean nameLocked;
|
||||
private boolean descriptionLocked;
|
||||
private boolean asinLocked;
|
||||
private boolean photoLocked;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import org.booklore.model.enums.AuthorMetadataSource;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class AuthorSearchResult {
|
||||
private AuthorMetadataSource source;
|
||||
private String asin;
|
||||
private String name;
|
||||
private String description;
|
||||
private String imageUrl;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class AuthorSummary {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String asin;
|
||||
private int bookCount;
|
||||
private boolean hasPhoto;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
import org.booklore.model.enums.AuthorMetadataSource;
|
||||
|
||||
@Data
|
||||
public class AuthorMatchRequest {
|
||||
private AuthorMetadataSource source;
|
||||
private String asin;
|
||||
private String region = "us";
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.booklore.model.dto.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AuthorUpdateRequest {
|
||||
private String name;
|
||||
private String description;
|
||||
private String asin;
|
||||
private Boolean nameLocked;
|
||||
private Boolean descriptionLocked;
|
||||
private Boolean asinLocked;
|
||||
private Boolean photoLocked;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package org.booklore.model.dto.response.audnexus;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class AudnexusAuthorResponse {
|
||||
|
||||
private String asin;
|
||||
private String name;
|
||||
private String description;
|
||||
|
||||
@JsonProperty("image")
|
||||
private String imageUrl;
|
||||
private String region;
|
||||
private List<Genre> genres;
|
||||
private List<SimilarAuthor> similar;
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Genre {
|
||||
private String asin;
|
||||
private String name;
|
||||
private String type;
|
||||
}
|
||||
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class SimilarAuthor {
|
||||
private String asin;
|
||||
private String name;
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,24 @@ public class AuthorEntity {
|
||||
@Column(name = "name")
|
||||
private String name;
|
||||
|
||||
@Column(name = "description", columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@Column(name = "asin", length = 20)
|
||||
private String asin;
|
||||
|
||||
@Column(name = "name_locked", nullable = false)
|
||||
private boolean nameLocked;
|
||||
|
||||
@Column(name = "description_locked", nullable = false)
|
||||
private boolean descriptionLocked;
|
||||
|
||||
@Column(name = "asin_locked", nullable = false)
|
||||
private boolean asinLocked;
|
||||
|
||||
@Column(name = "photo_locked", nullable = false)
|
||||
private boolean photoLocked;
|
||||
|
||||
@ManyToMany(mappedBy = "authors", fetch = FetchType.LAZY)
|
||||
private List<BookMetadataEntity> bookMetadataEntityList;
|
||||
|
||||
|
||||
@@ -34,5 +34,7 @@ public enum AuditAction {
|
||||
NAMING_PATTERN_CHANGED,
|
||||
LOGIN_RATE_LIMITED,
|
||||
REFRESH_RATE_LIMITED,
|
||||
DUPLICATE_BOOKS_MERGED
|
||||
DUPLICATE_BOOKS_MERGED,
|
||||
AUTHOR_METADATA_UPDATED,
|
||||
AUTHOR_DELETED
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.booklore.model.enums;
|
||||
|
||||
public enum AuthorMetadataSource {
|
||||
AUDNEXUS
|
||||
}
|
||||
@@ -18,5 +18,9 @@ public interface AuthorRepository extends JpaRepository<AuthorEntity, Long> {
|
||||
|
||||
@Query("SELECT a FROM AuthorEntity a JOIN a.bookMetadataEntityList bm WHERE bm.bookId = :bookId")
|
||||
List<AuthorEntity> findAuthorsByBookId(@Param("bookId") Long bookId);
|
||||
}
|
||||
|
||||
Optional<AuthorEntity> findByAsin(String asin);
|
||||
|
||||
@Query("SELECT a, COUNT(bm) FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm GROUP BY a ORDER BY a.name")
|
||||
List<Object[]> findAllWithBookCount();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
package org.booklore.service;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.AuthorDetails;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
import org.booklore.model.dto.AuthorSummary;
|
||||
import org.booklore.model.dto.CoverImage;
|
||||
import org.booklore.model.dto.request.AuthorMatchRequest;
|
||||
import org.booklore.model.dto.request.AuthorUpdateRequest;
|
||||
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.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class AuthorMetadataService {
|
||||
|
||||
private final AuthorRepository authorRepository;
|
||||
private final Map<AuthorMetadataSource, AuthorParser> authorParserMap;
|
||||
private final AuditService auditService;
|
||||
private final FileService fileService;
|
||||
private final DuckDuckGoCoverService duckDuckGoCoverService;
|
||||
|
||||
public List<AuthorSummary> getAllAuthors() {
|
||||
List<Object[]> results = authorRepository.findAllWithBookCount();
|
||||
List<AuthorSummary> summaries = new ArrayList<>();
|
||||
for (Object[] row : results) {
|
||||
AuthorEntity author = (AuthorEntity) row[0];
|
||||
long bookCount = (Long) row[1];
|
||||
summaries.add(AuthorSummary.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.asin(author.getAsin())
|
||||
.bookCount((int) bookCount)
|
||||
.hasPhoto(Files.exists(Paths.get(fileService.getAuthorThumbnailFile(author.getId()))))
|
||||
.build());
|
||||
}
|
||||
return summaries;
|
||||
}
|
||||
|
||||
public List<AuthorSearchResult> searchAuthorMetadata(String name, String region) {
|
||||
return authorParserMap.values().stream()
|
||||
.flatMap(provider -> {
|
||||
List<AuthorSearchResult> results = provider.searchAuthors(name, region);
|
||||
return results != null ? results.stream() : java.util.stream.Stream.empty();
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
public AuthorDetails matchAuthor(Long authorId, AuthorMatchRequest request) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
AuthorParser provider = request.getSource() != null ? authorParserMap.get(request.getSource()) : null;
|
||||
if (provider == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Unsupported author metadata source: " + request.getSource());
|
||||
}
|
||||
|
||||
AuthorSearchResult result = provider.getAuthorByAsin(request.getAsin(), request.getRegion());
|
||||
if (result == null) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Failed to fetch author metadata");
|
||||
}
|
||||
|
||||
applyMetadataResult(author, result);
|
||||
authorRepository.save(author);
|
||||
|
||||
if (!author.isPhotoLocked() && result.getImageUrl() != null && !result.getImageUrl().isBlank()) {
|
||||
fileService.createAuthorThumbnailFromUrl(author.getId(), result.getImageUrl());
|
||||
}
|
||||
|
||||
auditService.log(AuditAction.AUTHOR_METADATA_UPDATED, "Author", authorId,
|
||||
"Matched author '" + author.getName() + "' via " + result.getSource() + " (ASIN: " + result.getAsin() + ")");
|
||||
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
public AuthorDetails quickMatchAuthor(Long authorId, String region) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
for (AuthorParser provider : authorParserMap.values()) {
|
||||
AuthorSearchResult result = provider.quickSearch(author.getName(), region);
|
||||
if (result != null) {
|
||||
applyMetadataResult(author, result);
|
||||
authorRepository.save(author);
|
||||
|
||||
if (!author.isPhotoLocked() && result.getImageUrl() != null && !result.getImageUrl().isBlank()) {
|
||||
fileService.createAuthorThumbnailFromUrl(author.getId(), result.getImageUrl());
|
||||
}
|
||||
|
||||
auditService.log(AuditAction.AUTHOR_METADATA_UPDATED, "Author", authorId,
|
||||
"Quick-matched author '" + author.getName() + "' via " + result.getSource() + " (ASIN: " + result.getAsin() + ")");
|
||||
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
}
|
||||
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("No metadata found for author: " + author.getName());
|
||||
}
|
||||
|
||||
public Flux<AuthorSummary> autoMatchAuthors(List<Long> authorIds) {
|
||||
return Flux.fromIterable(authorIds)
|
||||
.concatMap(authorId ->
|
||||
Mono.fromCallable(() -> {
|
||||
AuthorEntity author = authorRepository.findById(authorId).orElse(null);
|
||||
if (author == null) return null;
|
||||
AuthorDetails details = quickMatchAuthor(authorId, "us");
|
||||
return AuthorSummary.builder()
|
||||
.id(details.getId())
|
||||
.name(details.getName())
|
||||
.asin(details.getAsin())
|
||||
.hasPhoto(Files.exists(Paths.get(fileService.getAuthorThumbnailFile(authorId))))
|
||||
.build();
|
||||
})
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
.delayElement(java.time.Duration.ofMillis(
|
||||
java.util.concurrent.ThreadLocalRandom.current().nextLong(250, 750)))
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to auto-match author ID {}: {}", authorId, e.getMessage());
|
||||
return Mono.empty();
|
||||
})
|
||||
)
|
||||
.filter(java.util.Objects::nonNull);
|
||||
}
|
||||
|
||||
public void unmatchAuthors(List<Long> authorIds) {
|
||||
for (Long authorId : authorIds) {
|
||||
AuthorEntity author = authorRepository.findById(authorId).orElse(null);
|
||||
if (author == null) continue;
|
||||
|
||||
author.setDescription(null);
|
||||
author.setAsin(null);
|
||||
authorRepository.save(author);
|
||||
fileService.deleteAuthorImages(authorId);
|
||||
|
||||
auditService.log(AuditAction.AUTHOR_METADATA_UPDATED, "Author", authorId,
|
||||
"Unmatched author '" + author.getName() + "'");
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteAuthors(List<Long> authorIds) {
|
||||
for (Long authorId : authorIds) {
|
||||
AuthorEntity author = authorRepository.findById(authorId).orElse(null);
|
||||
if (author == null) continue;
|
||||
|
||||
String authorName = author.getName();
|
||||
fileService.deleteAuthorImages(authorId);
|
||||
authorRepository.delete(author);
|
||||
|
||||
auditService.log(AuditAction.AUTHOR_DELETED, "Author", authorId,
|
||||
"Deleted author '" + authorName + "'");
|
||||
}
|
||||
}
|
||||
|
||||
public void uploadAuthorPhoto(Long authorId, MultipartFile file) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
try {
|
||||
java.awt.image.BufferedImage image = FileService.readImage(file.getInputStream());
|
||||
if (image == null) {
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to decode image");
|
||||
}
|
||||
fileService.saveAuthorImages(image, authorId);
|
||||
image.flush();
|
||||
} catch (java.io.IOException e) {
|
||||
throw ApiError.FILE_READ_ERROR.createException(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public AuthorDetails updateAuthor(Long authorId, AuthorUpdateRequest request) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
if (request.getName() != null) {
|
||||
author.setName(request.getName());
|
||||
}
|
||||
if (request.getDescription() != null) {
|
||||
author.setDescription(request.getDescription().isBlank() ? null : request.getDescription());
|
||||
}
|
||||
if (request.getAsin() != null) {
|
||||
author.setAsin(request.getAsin().isBlank() ? null : request.getAsin());
|
||||
}
|
||||
if (request.getNameLocked() != null) {
|
||||
author.setNameLocked(request.getNameLocked());
|
||||
}
|
||||
if (request.getDescriptionLocked() != null) {
|
||||
author.setDescriptionLocked(request.getDescriptionLocked());
|
||||
}
|
||||
if (request.getAsinLocked() != null) {
|
||||
author.setAsinLocked(request.getAsinLocked());
|
||||
}
|
||||
if (request.getPhotoLocked() != null) {
|
||||
author.setPhotoLocked(request.getPhotoLocked());
|
||||
}
|
||||
|
||||
authorRepository.save(author);
|
||||
|
||||
auditService.log(AuditAction.AUTHOR_METADATA_UPDATED, "Author", authorId,
|
||||
"Updated author '" + author.getName() + "'");
|
||||
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
public List<CoverImage> searchAuthorPhotos(String name) {
|
||||
String searchTerm = name + " author photo portrait";
|
||||
List<CoverImage> results = duckDuckGoCoverService.searchImages(searchTerm);
|
||||
if (results.size() > 50) {
|
||||
results = results.subList(0, 50);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public void uploadAuthorPhotoFromUrl(Long authorId, String imageUrl) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
|
||||
fileService.createAuthorThumbnailFromUrl(authorId, imageUrl);
|
||||
}
|
||||
|
||||
public AuthorDetails getAuthorByName(String name) {
|
||||
AuthorEntity author = authorRepository.findByNameIgnoreCase(name)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(name));
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
public AuthorDetails getAuthorDetails(Long authorId) {
|
||||
AuthorEntity author = authorRepository.findById(authorId)
|
||||
.orElseThrow(() -> ApiError.AUTHOR_NOT_FOUND.createException(authorId));
|
||||
return toAuthorDetails(author);
|
||||
}
|
||||
|
||||
public Resource getAuthorPhoto(Long authorId) {
|
||||
Path photoPath = Paths.get(fileService.getAuthorPhotoFile(authorId));
|
||||
try {
|
||||
if (Files.exists(photoPath)) {
|
||||
return new UrlResource(photoPath.toUri());
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
log.warn("Malformed URL for author photo path: {}", photoPath);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Resource getAuthorThumbnail(Long authorId) {
|
||||
Path thumbnailPath = Paths.get(fileService.getAuthorThumbnailFile(authorId));
|
||||
try {
|
||||
if (Files.exists(thumbnailPath)) {
|
||||
return new UrlResource(thumbnailPath.toUri());
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
log.warn("Malformed URL for author thumbnail path: {}", thumbnailPath);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void applyMetadataResult(AuthorEntity author, AuthorSearchResult result) {
|
||||
if (!author.isDescriptionLocked()) {
|
||||
author.setDescription(result.getDescription());
|
||||
}
|
||||
if (!author.isAsinLocked()) {
|
||||
author.setAsin(result.getAsin());
|
||||
}
|
||||
}
|
||||
|
||||
private AuthorDetails toAuthorDetails(AuthorEntity author) {
|
||||
return AuthorDetails.builder()
|
||||
.id(author.getId())
|
||||
.name(author.getName())
|
||||
.description(author.getDescription())
|
||||
.asin(author.getAsin())
|
||||
.nameLocked(author.isNameLocked())
|
||||
.descriptionLocked(author.isDescriptionLocked())
|
||||
.asinLocked(author.isAsinLocked())
|
||||
.photoLocked(author.isPhotoLocked())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,32 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
return allImages;
|
||||
}
|
||||
|
||||
public List<CoverImage> searchImages(String searchTerm) {
|
||||
String searchParams = "&iar=images";
|
||||
String jsonParams = "&iar=images";
|
||||
|
||||
String encodedQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
||||
String searchUrl = SEARCH_BASE_URL + encodedQuery + searchParams;
|
||||
Connection.Response response = getResponse(searchUrl);
|
||||
Document doc = parseResponse(response);
|
||||
Map<String, String> cookies = response.cookies();
|
||||
Pattern tokenPattern = Pattern.compile("vqd=\"(\\d+-\\d+)\"");
|
||||
Matcher matcher = tokenPattern.matcher(doc.html());
|
||||
if (!matcher.find()) {
|
||||
log.error("Could not find search token for image search");
|
||||
return Collections.emptyList();
|
||||
}
|
||||
String searchToken = matcher.group(1);
|
||||
List<CoverImage> images = fetchImagesFromApi(searchTerm, searchToken, cookies, searchUrl, jsonParams);
|
||||
|
||||
for (int i = 0; i < images.size(); i++) {
|
||||
CoverImage img = images.get(i);
|
||||
images.set(i, new CoverImage(img.getUrl(), img.getWidth(), img.getHeight(), i + 1));
|
||||
}
|
||||
|
||||
return images;
|
||||
}
|
||||
|
||||
private List<CoverImage> fetchImagesFromApi(String query, String searchToken, Map<String, String> cookies, String referrerUrl, String jsonParams) {
|
||||
List<CoverImage> priority = new ArrayList<>();
|
||||
List<CoverImage> others = new ArrayList<>();
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package org.booklore.service.metadata.parser;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
import org.booklore.model.dto.response.audnexus.AudnexusAuthorResponse;
|
||||
import org.booklore.model.enums.AuthorMetadataSource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AudnexusAuthorParser implements AuthorParser {
|
||||
|
||||
private static final String BASE_URL = "https://api.audnex.us";
|
||||
private static final long MIN_REQUEST_INTERVAL_MS = 150;
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicLong lastRequestTime = new AtomicLong(0);
|
||||
|
||||
public AudnexusAuthorParser(HttpClient httpClient, ObjectMapper objectMapper) {
|
||||
this.httpClient = httpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AuthorSearchResult> searchAuthors(String name, String region) {
|
||||
try {
|
||||
waitForRateLimit();
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(BASE_URL + "/authors")
|
||||
.queryParam("name", name)
|
||||
.queryParam("region", region)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
log.info("Audnexus author search URL: {}", uri);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() == 200) {
|
||||
AudnexusAuthorResponse[] authors = objectMapper.readValue(response.body(), AudnexusAuthorResponse[].class);
|
||||
LinkedHashMap<String, AudnexusAuthorResponse> uniqueByAsin = new LinkedHashMap<>();
|
||||
for (AudnexusAuthorResponse author : authors) {
|
||||
uniqueByAsin.putIfAbsent(author.getAsin(), author);
|
||||
}
|
||||
List<AuthorSearchResult> results = new ArrayList<>();
|
||||
int limit = 10;
|
||||
for (AudnexusAuthorResponse author : uniqueByAsin.values()) {
|
||||
if (results.size() >= limit) break;
|
||||
AuthorSearchResult enriched = getAuthorByAsin(author.getAsin(), region);
|
||||
results.add(enriched != null ? enriched : toSearchResult(author));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
log.warn("Audnexus author search returned status {}", response.statusCode());
|
||||
return Collections.emptyList();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("Audnexus author search interrupted", e);
|
||||
return Collections.emptyList();
|
||||
} catch (Exception e) {
|
||||
log.error("Audnexus author search failed for name: {}", name, e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthorSearchResult quickSearch(String name, String region) {
|
||||
try {
|
||||
waitForRateLimit();
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(BASE_URL + "/authors")
|
||||
.queryParam("name", name)
|
||||
.queryParam("region", region)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
log.info("Audnexus author quick search URL: {}", uri);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() == 200) {
|
||||
AudnexusAuthorResponse[] authors = objectMapper.readValue(response.body(), AudnexusAuthorResponse[].class);
|
||||
if (authors.length == 0) return null;
|
||||
return getAuthorByAsin(authors[0].getAsin(), region);
|
||||
}
|
||||
|
||||
log.warn("Audnexus author quick search returned status {}", response.statusCode());
|
||||
return null;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Audnexus author quick search failed for name: {}", name, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthorSearchResult getAuthorByAsin(String asin, String region) {
|
||||
try {
|
||||
waitForRateLimit();
|
||||
|
||||
URI uri = UriComponentsBuilder.fromUriString(BASE_URL + "/authors/" + asin)
|
||||
.queryParam("region", region)
|
||||
.build()
|
||||
.toUri();
|
||||
|
||||
log.info("Audnexus author detail URL: {}", uri);
|
||||
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(uri)
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
if (response.statusCode() == 200) {
|
||||
AudnexusAuthorResponse author = objectMapper.readValue(response.body(), AudnexusAuthorResponse.class);
|
||||
return toSearchResult(author);
|
||||
}
|
||||
|
||||
log.warn("Audnexus author detail returned status {}", response.statusCode());
|
||||
return null;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.error("Audnexus author detail interrupted", e);
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Audnexus author detail failed for ASIN: {}", asin, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AuthorSearchResult toSearchResult(AudnexusAuthorResponse response) {
|
||||
return AuthorSearchResult.builder()
|
||||
.source(AuthorMetadataSource.AUDNEXUS)
|
||||
.asin(response.getAsin())
|
||||
.name(response.getName())
|
||||
.description(response.getDescription())
|
||||
.imageUrl(response.getImageUrl())
|
||||
.build();
|
||||
}
|
||||
|
||||
private void waitForRateLimit() {
|
||||
long now = System.currentTimeMillis();
|
||||
long timeSinceLastRequest = now - lastRequestTime.get();
|
||||
if (timeSinceLastRequest < MIN_REQUEST_INTERVAL_MS) {
|
||||
try {
|
||||
Thread.sleep(MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
lastRequestTime.set(System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package org.booklore.service.metadata.parser;
|
||||
|
||||
import org.booklore.model.dto.AuthorSearchResult;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface AuthorParser {
|
||||
|
||||
List<AuthorSearchResult> searchAuthors(String name, String region);
|
||||
|
||||
AuthorSearchResult getAuthorByAsin(String asin, String region);
|
||||
|
||||
AuthorSearchResult quickSearch(String name, String region);
|
||||
}
|
||||
@@ -45,11 +45,14 @@ public class FileService {
|
||||
|
||||
// @formatter:off
|
||||
private static final String IMAGES_DIR = "images";
|
||||
private static final String AUTHOR_IMAGES_DIR = "author-images";
|
||||
private static final String BACKGROUNDS_DIR = "backgrounds";
|
||||
private static final String ICONS_DIR = "icons";
|
||||
private static final String SVG_DIR = "svg";
|
||||
private static final String THUMBNAIL_FILENAME = "thumbnail.jpg";
|
||||
private static final String COVER_FILENAME = "cover.jpg";
|
||||
private static final String AUTHOR_PHOTO_FILENAME = "photo.jpg";
|
||||
private static final String AUTHOR_THUMBNAIL_FILENAME = "thumbnail.jpg";
|
||||
private static final String AUDIOBOOK_THUMBNAIL_FILENAME = "audiobook-thumbnail.jpg";
|
||||
private static final String AUDIOBOOK_COVER_FILENAME = "audiobook-cover.jpg";
|
||||
private static final String JPEG_MIME_TYPE = "image/jpeg";
|
||||
@@ -88,6 +91,18 @@ public class FileService {
|
||||
return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), AUDIOBOOK_COVER_FILENAME).toString();
|
||||
}
|
||||
|
||||
public String getAuthorImagesFolder(long authorId) {
|
||||
return Paths.get(appProperties.getPathConfig(), AUTHOR_IMAGES_DIR, String.valueOf(authorId)).toString();
|
||||
}
|
||||
|
||||
public String getAuthorPhotoFile(long authorId) {
|
||||
return Paths.get(appProperties.getPathConfig(), AUTHOR_IMAGES_DIR, String.valueOf(authorId), AUTHOR_PHOTO_FILENAME).toString();
|
||||
}
|
||||
|
||||
public String getAuthorThumbnailFile(long authorId) {
|
||||
return Paths.get(appProperties.getPathConfig(), AUTHOR_IMAGES_DIR, String.valueOf(authorId), AUTHOR_THUMBNAIL_FILENAME).toString();
|
||||
}
|
||||
|
||||
public String getBackgroundsFolder(Long userId) {
|
||||
if (userId != null) {
|
||||
return Paths.get(appProperties.getPathConfig(), BACKGROUNDS_DIR, "user-" + userId).toString();
|
||||
@@ -292,6 +307,116 @@ public class FileService {
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// AUTHOR PHOTO OPERATIONS
|
||||
// ========================================
|
||||
|
||||
public void createAuthorThumbnailFromUrl(long authorId, String imageUrl) {
|
||||
try {
|
||||
BufferedImage originalImage = downloadImageFromUrl(imageUrl);
|
||||
if (originalImage == null) {
|
||||
log.warn("Skipping author thumbnail creation for author {}: download/decode failed", authorId);
|
||||
return;
|
||||
}
|
||||
boolean success = saveAuthorImages(originalImage, authorId);
|
||||
if (!success) {
|
||||
log.warn("Failed to save author images for author ID: {}", authorId);
|
||||
}
|
||||
originalImage.flush();
|
||||
log.info("Author images created and saved from URL for author ID: {}", authorId);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to create author thumbnail from URL for author {}: {}", authorId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean saveAuthorImages(BufferedImage sourceImage, long authorId) throws IOException {
|
||||
BufferedImage rgbImage = null;
|
||||
BufferedImage resized = null;
|
||||
BufferedImage thumb = null;
|
||||
try {
|
||||
String folderPath = getAuthorImagesFolder(authorId);
|
||||
File folder = new File(folderPath);
|
||||
if (!folder.exists() && !folder.mkdirs()) {
|
||||
throw new IOException("Failed to create directory: " + folder.getAbsolutePath());
|
||||
}
|
||||
|
||||
rgbImage = new BufferedImage(
|
||||
sourceImage.getWidth(),
|
||||
sourceImage.getHeight(),
|
||||
BufferedImage.TYPE_INT_RGB
|
||||
);
|
||||
Graphics2D g = rgbImage.createGraphics();
|
||||
g.drawImage(sourceImage, 0, 0, Color.WHITE, null);
|
||||
g.dispose();
|
||||
|
||||
double scale = Math.min(
|
||||
(double) MAX_ORIGINAL_WIDTH / rgbImage.getWidth(),
|
||||
(double) MAX_ORIGINAL_HEIGHT / rgbImage.getHeight()
|
||||
);
|
||||
if (scale < 1.0) {
|
||||
resized = resizeImage(rgbImage, (int) (rgbImage.getWidth() * scale), (int) (rgbImage.getHeight() * scale));
|
||||
rgbImage.flush();
|
||||
rgbImage = resized;
|
||||
}
|
||||
|
||||
File photoFile = new File(folder, AUTHOR_PHOTO_FILENAME);
|
||||
boolean photoSaved = ImageIO.write(rgbImage, IMAGE_FORMAT, photoFile);
|
||||
|
||||
double targetRatio = (double) THUMBNAIL_WIDTH / THUMBNAIL_HEIGHT;
|
||||
double sourceRatio = (double) rgbImage.getWidth() / rgbImage.getHeight();
|
||||
int cropWidth, cropHeight, cropX, cropY;
|
||||
if (sourceRatio > targetRatio) {
|
||||
cropHeight = rgbImage.getHeight();
|
||||
cropWidth = (int) (cropHeight * targetRatio);
|
||||
cropX = (rgbImage.getWidth() - cropWidth) / 2;
|
||||
cropY = 0;
|
||||
} else {
|
||||
cropWidth = rgbImage.getWidth();
|
||||
cropHeight = (int) (cropWidth / targetRatio);
|
||||
cropX = 0;
|
||||
cropY = (rgbImage.getHeight() - cropHeight) / 2;
|
||||
}
|
||||
BufferedImage cropped = rgbImage.getSubimage(cropX, cropY, cropWidth, cropHeight);
|
||||
thumb = resizeImage(cropped, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
|
||||
|
||||
File thumbnailFile = new File(folder, AUTHOR_THUMBNAIL_FILENAME);
|
||||
boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile);
|
||||
|
||||
return photoSaved && thumbnailSaved;
|
||||
} finally {
|
||||
if (rgbImage != null) {
|
||||
rgbImage.flush();
|
||||
}
|
||||
if (resized != null && resized != rgbImage) {
|
||||
resized.flush();
|
||||
}
|
||||
if (thumb != null) {
|
||||
thumb.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteAuthorImages(long authorId) {
|
||||
String authorImageFolder = getAuthorImagesFolder(authorId);
|
||||
Path folderPath = Paths.get(authorImageFolder);
|
||||
try {
|
||||
if (Files.exists(folderPath) && Files.isDirectory(folderPath)) {
|
||||
try (Stream<Path> walk = Files.walk(folderPath)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.forEach(path -> {
|
||||
try {
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to delete file: {} - {}", path, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error deleting author images for author {}: {}", authorId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// AUDIOBOOK COVER OPERATIONS
|
||||
// ========================================
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS description TEXT;
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS asin VARCHAR(20);
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS name_locked BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS description_locked BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS asin_locked BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE author ADD COLUMN IF NOT EXISTS photo_locked BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_author_asin ON author (asin);
|
||||
@@ -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);
|
||||
|
||||
+185
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user