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,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;
}
@@ -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<>();
@@ -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);
@@ -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");
}
}
+2
View File
@@ -41,6 +41,8 @@ export const routes: Routes = [
{path: 'unshelved-books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'series', loadComponent: () => import('./features/series-browser/components/series-browser/series-browser.component').then(m => m.SeriesBrowserComponent), canActivate: [AuthGuard]},
{path: 'series/:seriesName', loadComponent: () => import('./features/book/components/series-page/series-page.component').then(m => m.SeriesPageComponent), canActivate: [AuthGuard]},
{path: 'authors', loadComponent: () => import('./features/author-browser/components/author-browser/author-browser.component').then(m => m.AuthorBrowserComponent), canActivate: [AuthGuard]},
{path: 'author/:authorId', loadComponent: () => import('./features/author-browser/components/author-detail/author-detail.component').then(m => m.AuthorDetailComponent), canActivate: [AuthGuard]},
{path: 'magic-shelf/:magicShelfId/books', component: BookBrowserComponent, canActivate: [AuthGuard]},
{path: 'book/:bookId', loadComponent: () => import('./features/metadata/component/book-metadata-center/book-metadata-center.component').then(m => m.BookMetadataCenterComponent), canActivate: [AuthGuard]},
{path: 'bookdrop', loadComponent: () => import('./features/bookdrop/component/bookdrop-file-review/bookdrop-file-review.component').then(m => m.BookdropFileReviewComponent), canActivate: [BookdropGuard]},
@@ -14,7 +14,9 @@ export class CustomReuseStrategy implements RouteReuseStrategy {
'unshelved-books',
'library/:libraryId/books',
'shelf/:shelfId/books',
'magic-shelf/:magicShelfId/books'
'magic-shelf/:magicShelfId/books',
'authors',
'series'
];
private readonly BOOK_DETAILS_PATH = 'book/:bookId';
@@ -29,10 +31,6 @@ export class CustomReuseStrategy implements RouteReuseStrategy {
return this.BOOK_BROWSER_PATHS.includes(path || '');
}
private isBookDetailsRoute(route: ActivatedRouteSnapshot): boolean {
return route.routeConfig?.path === this.BOOK_DETAILS_PATH;
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.isBookBrowserRoute(route);
}
@@ -0,0 +1,285 @@
<ng-container *transloco="let t; prefix: 'authorBrowser'">
@if (loading) {
<div class="loading-state">
<p-progressSpinner
[style]="{'width': '60px', 'height': '60px'}"
strokeWidth="3"
fill="transparent"
animationDuration="1.5s">
</p-progressSpinner>
</div>
}
@if (!loading) {
<div class="browse-header">
<h2 class="browse-title">{{ t('browseAllAuthors') }}</h2>
<div class="browse-controls">
<div class="search-wrapper">
<i class="pi pi-search search-icon"></i>
<input
pInputText
type="text"
[placeholder]="t('searchPlaceholder')"
[ngModel]="searchTerm$ | async"
(ngModelChange)="onSearchChange($event)"
class="search-input"/>
</div>
<div class="filter-sort-wrapper">
<p-select
[options]="sortOptions"
[ngModel]="sortBy$ | async"
(ngModelChange)="onSortChange($event)"
optionLabel="label"
optionValue="value"
class="sort-dropdown">
</p-select>
<button class="sort-direction-btn" (click)="toggleSortDirection()">
<i class="pi" [class.pi-arrow-up]="(sortDirection$ | async) === 'asc'" [class.pi-arrow-down]="(sortDirection$ | async) === 'desc'"></i>
</button>
<button class="filter-btn" (click)="filterPopover.toggle($event)">
<i class="pi pi-filter"></i>
@if (activeFilterCount > 0) {
<span class="filter-badge"></span>
}
</button>
@if (!isMobile) {
<button class="display-settings-btn" (click)="displaySettingsPopover.toggle($event)">
<i class="pi pi-sliders-h"></i>
</button>
<p-popover #displaySettingsPopover>
<div class="display-settings-content">
<label class="display-settings-label">{{ t('cardSize') }}</label>
<p-slider
[(ngModel)]="authorScaleService.scaleFactor"
[min]="0.7"
[max]="1.3"
[step]="0.01"
[style]="{ width: '100%' }"
(onChange)="updateScale()">
</p-slider>
<div class="scale-value-display">
{{ authorScaleService.scaleFactor.toFixed(2) }}x
</div>
</div>
</p-popover>
}
<p-popover #filterPopover>
<div class="filter-popover-content">
<div class="filter-group">
<label class="filter-label">{{ t('filters.matchStatus') }}</label>
<p-select
[options]="[
{label: t('filters.all'), value: 'all'},
{label: t('filters.matched'), value: 'matched'},
{label: t('filters.unmatched'), value: 'unmatched'}
]"
[ngModel]="(filters$ | async)?.matchStatus"
(ngModelChange)="onFilterChange('matchStatus', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
<div class="filter-group">
<label class="filter-label">{{ t('filters.photoStatus') }}</label>
<p-select
[options]="[
{label: t('filters.all'), value: 'all'},
{label: t('filters.hasPhoto'), value: 'has-photo'},
{label: t('filters.noPhoto'), value: 'no-photo'}
]"
[ngModel]="(filters$ | async)?.photoStatus"
(ngModelChange)="onFilterChange('photoStatus', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
<div class="filter-group">
<label class="filter-label">{{ t('filters.readStatus') }}</label>
<p-select
[options]="[
{label: t('filters.all'), value: 'all'},
{label: t('filters.allRead'), value: 'all-read'},
{label: t('filters.someRead'), value: 'some-read'},
{label: t('filters.inProgress'), value: 'in-progress'},
{label: t('filters.unread'), value: 'unread'}
]"
[ngModel]="(filters$ | async)?.readStatus"
(ngModelChange)="onFilterChange('readStatus', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
<div class="filter-group">
<label class="filter-label">{{ t('filters.bookCount') }}</label>
<p-select
[options]="[
{label: t('filters.all'), value: 'all'},
{label: '0', value: '0'},
{label: '1', value: '1'},
{label: '2', value: '2'},
{label: '3', value: '3'},
{label: '4', value: '4'},
{label: '5', value: '5'},
{label: '6-10', value: '6-10'},
{label: '11-20', value: '11-20'},
{label: '21-35', value: '21-35'},
{label: '36+', value: '36+'}
]"
[ngModel]="(filters$ | async)?.bookCount"
(ngModelChange)="onFilterChange('bookCount', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
<div class="filter-group">
<label class="filter-label">{{ t('filters.library') }}</label>
<p-select
[options]="libraryOptions"
[ngModel]="(filters$ | async)?.library"
(ngModelChange)="onFilterChange('library', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
<div class="filter-group">
<label class="filter-label">{{ t('filters.genre') }}</label>
<p-select
[options]="genreOptions"
[ngModel]="(filters$ | async)?.genre"
(ngModelChange)="onFilterChange('genre', $event)"
optionLabel="label"
optionValue="value"
class="filter-dropdown">
</p-select>
</div>
@if (activeFilterCount > 0) {
<p-button
[label]="t('filters.reset')"
icon="pi pi-filter-slash"
severity="secondary"
[outlined]="true"
size="small"
(onClick)="resetFilters()"
class="filter-reset-btn">
</p-button>
}
</div>
</p-popover>
</div>
</div>
</div>
@if (filteredAuthors$ | async; as authorList) {
@if (authorList.length === 0) {
<div class="empty-state">
<i class="pi pi-users empty-icon"></i>
<p>{{ t('noAuthorsFound') }}</p>
</div>
} @else {
<virtual-scroller
#scroll
[items]="authorList"
class="virtual-scroller">
<div class="author-grid"
#container
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (author of scroll.viewPortItems; track author.id; let i = $index) {
<div class="virtual-scroller-item"
[ngStyle]="{width: cardWidth + 'px', height: cardHeight + 'px'}"
[style.--card-scale]="authorScaleService.scaleFactor">
<app-author-card
[author]="author"
[index]="authorList.indexOf(author)"
[cacheBuster]="thumbnailCacheBusters.get(author.id) || 0"
[canQuickMatch]="canEditMetadata"
[canDelete]="canDeleteBook"
[isCheckboxEnabled]="canEditMetadata || canDeleteBook"
[isSelected]="isAuthorSelected(author.id)"
(cardClick)="navigateToAuthor($event)"
(viewAuthor)="navigateToAuthor($event)"
(editAuthor)="navigateToAuthorEdit($event)"
(deleteAuthor)="deleteAuthor($event)"
(quickMatched)="onAuthorQuickMatched($event)"
(checkboxClick)="onCheckboxClicked($event)">
</app-author-card>
</div>
}
</div>
</virtual-scroller>
}
}
@if (userService.userState$ | async; as userState) {
<div class="author-browser-footer" [class.footer-hidden]="selectedCount === 0">
<div class="footer-content">
<div class="selected-count-badge">
<i class="pi pi-check-circle"></i>
<span class="selected-count">{{ selectedCount }}</span>
<span class="selected-label">{{ t('footer.selected') }}</span>
</div>
@if (canEditMetadata || canDeleteBook) {
<p-divider layout="vertical"></p-divider>
<div class="action-buttons-group">
@if (canEditMetadata) {
<p-button
icon="pi pi-bolt"
outlined="true"
severity="info"
(onClick)="autoMatchSelected()"
[pTooltip]="t('footer.autoMatch')"
tooltipPosition="top">
</p-button>
}
@if (canDeleteBook) {
<p-button
icon="pi pi-trash"
outlined="true"
severity="danger"
(onClick)="deleteSelected()"
[pTooltip]="t('footer.deleteSelected')"
tooltipPosition="top">
</p-button>
}
</div>
}
<p-divider layout="vertical"></p-divider>
<div class="action-buttons-group">
<p-button
outlined="true"
icon="pi pi-check-square"
severity="success"
(click)="selectAllAuthors()"
[pTooltip]="t('footer.selectAll')"
tooltipPosition="top">
</p-button>
<p-button
outlined="true"
icon="pi pi-times"
severity="warn"
(click)="deselectAllAuthors()"
[pTooltip]="t('footer.deselectAll')"
tooltipPosition="top">
</p-button>
</div>
</div>
</div>
}
}
</ng-container>
@@ -0,0 +1,305 @@
.loading-state {
display: flex;
align-items: center;
justify-content: center;
height: calc(100dvh - 6.7rem);
}
.browse-header {
padding: 0.75rem 1rem 0;
}
.browse-title {
font-size: 1.5rem;
font-weight: 800;
margin-bottom: 0.75rem;
background: linear-gradient(135deg, #ffffff, #e2e8f0, #3b82f6);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
letter-spacing: -0.02em;
}
.browse-controls {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 0.5rem;
align-items: center;
}
.search-wrapper {
position: relative;
flex: 1;
min-width: 200px;
max-width: 400px;
.search-icon {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: #94a3b8;
font-size: 0.9rem;
z-index: 1;
}
.search-input {
width: 100%;
padding-left: 2.25rem;
font-size: 0.9rem;
}
}
.filter-sort-wrapper {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
align-items: center;
}
.sort-dropdown,
.filter-dropdown {
min-width: 160px;
}
.display-settings-btn,
.filter-btn,
.sort-direction-btn {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border-radius: 8px;
border: 1px solid color-mix(in srgb, var(--p-surface-500), transparent 50%);
background: color-mix(in srgb, var(--p-surface-700), transparent 30%);
color: #94a3b8;
cursor: pointer;
transition: all 0.2s ease;
&:hover {
color: #e2e8f0;
border-color: var(--p-primary-400);
}
}
.filter-badge {
position: absolute;
top: 4px;
right: 4px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--p-primary-400);
}
.display-settings-content {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 180px;
}
.display-settings-label {
font-size: 0.85rem;
font-weight: 600;
color: #e2e8f0;
}
.scale-value-display {
text-align: center;
font-size: 0.8rem;
color: #94a3b8;
}
.filter-popover-content {
display: flex;
flex-direction: column;
gap: 0.75rem;
min-width: 220px;
}
.filter-group {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.filter-label {
font-size: 0.8rem;
font-weight: 600;
color: #94a3b8;
}
.filter-reset-btn {
margin-top: 0.25rem;
}
.virtual-scroller {
width: 100%;
height: calc(100dvh - 12.5rem);
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--primary-color) rgba(20, 20, 30, 0.5);
&::-webkit-scrollbar {
width: 12px;
}
&::-webkit-scrollbar-track {
background: rgba(20, 20, 30, 0.5);
border-radius: 10px;
}
@media (max-width: 768px) {
height: calc(100dvh - 13rem);
padding: 0.5rem;
&::-webkit-scrollbar {
width: 8px;
}
}
}
.author-grid {
display: grid;
gap: 1.25rem;
align-items: start;
justify-items: center;
width: 100%;
padding-top: 1rem;
padding-right: 1rem;
padding-left: 1rem;
}
.virtual-scroller-item {
position: relative;
overflow: visible;
transition: width 0.2s ease, height 0.2s ease;
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4rem 2rem;
text-align: center;
.empty-icon {
font-size: 3rem;
color: #64748b;
margin-bottom: 1rem;
}
p {
color: #94a3b8;
font-size: 1rem;
font-weight: 500;
}
}
.author-browser-footer {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
padding: 1rem 0.5rem 0.5rem;
z-index: 1;
border-radius: 10px 10px 0 0;
border: 1px solid rgba(255, 255, 255, 0.5);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
background: rgba(0, 0, 0, 0.65);
transition: transform 0.1s ease, opacity 0.1s ease;
&.footer-hidden {
transform: translateX(-50%) translateY(100%);
opacity: 0;
pointer-events: none;
}
> .footer-content {
width: 100%;
}
@media (max-width: 768px) {
max-width: 100%;
left: 0;
right: 0;
transform: none;
&.footer-hidden {
transform: translateY(100%);
}
}
}
.footer-content {
display: flex;
align-items: center;
justify-content: center;
padding: 0 0.75rem;
}
.selected-count-badge {
display: inline-flex;
align-items: center;
padding: 0.5rem 1rem;
font-size: 0.9rem;
color: #e4e4e7;
i {
font-size: 1rem;
margin-right: 0.5rem;
}
}
.selected-count {
font-weight: 700;
font-size: 1rem;
color: var(--primary-color);
}
.selected-label {
margin-left: 0.25rem;
}
.action-buttons-group {
display: flex;
gap: 0.5rem;
@media (min-width: 768px) {
gap: 1.5rem;
}
}
@media (max-width: 767px) {
.browse-header {
padding: 0.5rem 0.5rem 0;
}
.browse-controls {
flex-direction: column;
}
.search-wrapper {
max-width: 100%;
}
.filter-sort-wrapper {
width: 100%;
}
.sort-dropdown {
flex: 1;
min-width: 0;
}
}
@@ -0,0 +1,627 @@
import {Component, HostListener, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {AsyncPipe, NgStyle} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {combineLatest, Observable, BehaviorSubject, Subscription} from 'rxjs';
import {filter, map} from 'rxjs/operators';
import {ProgressSpinner} from 'primeng/progressspinner';
import {InputText} from 'primeng/inputtext';
import {Select} from 'primeng/select';
import {Slider} from 'primeng/slider';
import {Popover} from 'primeng/popover';
import {Button} from 'primeng/button';
import {Divider} from 'primeng/divider';
import {Tooltip} from 'primeng/tooltip';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {VirtualScrollerComponent, VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {BookBrowserScrollService} from '../../../book/components/book-browser/book-browser-scroll.service';
import {MessageService} from 'primeng/api';
import {AuthorService} from '../../service/author.service';
import {AuthorSummary, EnrichedAuthor, AuthorFilters, DEFAULT_AUTHOR_FILTERS} from '../../model/author.model';
import {AuthorCardComponent} from '../author-card/author-card.component';
import {AuthorScalePreferenceService} from '../../service/author-scale-preference.service';
import {AuthorSelectionService, AuthorCheckboxClickEvent} from '../../service/author-selection.service';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
import {UserService} from '../../../settings/user-management/user.service';
import {BookService} from '../../../book/service/book.service';
import {Book, ReadStatus} from '../../../book/model/book.model';
type SortDirection = 'asc' | 'desc';
interface SortOption {
label: string;
value: string;
}
interface FilterOption {
label: string;
value: string;
}
const DEFAULT_SORT_DIRECTIONS: Record<string, SortDirection> = {
'name': 'asc',
'book-count': 'desc',
'matched': 'desc',
'recently-added': 'desc',
'recently-read': 'desc',
'reading-progress': 'desc',
'avg-rating': 'desc',
'photo': 'desc',
'series-count': 'desc'
};
@Component({
selector: 'app-author-browser',
standalone: true,
templateUrl: './author-browser.component.html',
styleUrls: ['./author-browser.component.scss'],
imports: [
AsyncPipe,
NgStyle,
FormsModule,
ProgressSpinner,
InputText,
Select,
Slider,
Popover,
Button,
Divider,
Tooltip,
TranslocoDirective,
AuthorCardComponent,
VirtualScrollerModule
]
})
export class AuthorBrowserComponent implements OnInit, OnDestroy {
private static readonly BASE_WIDTH = 165;
private static readonly BASE_HEIGHT = 290;
private static readonly MOBILE_BASE_WIDTH = 140;
private static readonly MOBILE_BASE_HEIGHT = 250;
private authorService = inject(AuthorService);
private bookService = inject(BookService);
private messageService = inject(MessageService);
private pageTitle = inject(PageTitleService);
private scrollService = inject(BookBrowserScrollService);
private t = inject(TranslocoService);
private router = inject(Router);
private activatedRoute = inject(ActivatedRoute);
protected userService = inject(UserService);
protected authorScaleService = inject(AuthorScalePreferenceService);
protected selectionService = inject(AuthorSelectionService);
@ViewChild('scroll')
virtualScroller: VirtualScrollerComponent | undefined;
private subscriptions: Subscription[] = [];
loading = true;
private authorsLoaded = false;
private booksLoaded = false;
screenWidth = window.innerWidth;
selectedCount = 0;
isCheckboxEnabled = false;
thumbnailCacheBusters = new Map<number, number>();
@HostListener('window:resize')
onResize(): void {
this.screenWidth = window.innerWidth;
}
get isMobile(): boolean {
return this.screenWidth <= 767;
}
get cardWidth(): number {
const base = this.isMobile
? AuthorBrowserComponent.MOBILE_BASE_WIDTH
: AuthorBrowserComponent.BASE_WIDTH;
return Math.round(base * this.authorScaleService.scaleFactor);
}
get cardHeight(): number {
const base = this.isMobile
? AuthorBrowserComponent.MOBILE_BASE_HEIGHT
: AuthorBrowserComponent.BASE_HEIGHT;
return Math.round(base * this.authorScaleService.scaleFactor);
}
get gridColumnMinWidth(): string {
return `${this.cardWidth}px`;
}
searchTerm$ = new BehaviorSubject<string>('');
sortBy$ = new BehaviorSubject<string>('name');
sortDirection$ = new BehaviorSubject<SortDirection>('asc');
allAuthors$ = new BehaviorSubject<AuthorSummary[]>([]);
filters$ = new BehaviorSubject<AuthorFilters>({...DEFAULT_AUTHOR_FILTERS});
sortOptions: SortOption[] = [];
libraryOptions: FilterOption[] = [];
genreOptions: FilterOption[] = [];
activeFilterCount = 0;
private readonly validSortValues = [
'name', 'book-count', 'matched', 'recently-added', 'recently-read',
'reading-progress', 'avg-rating', 'photo', 'series-count'
];
filteredAuthors$!: Observable<EnrichedAuthor[]>;
private enrichedAuthors$ = new BehaviorSubject<EnrichedAuthor[]>([]);
ngOnInit(): void {
this.pageTitle.setPageTitle(this.t.translate('authorBrowser.pageTitle'));
this.sortOptions = [
{label: this.t.translate('authorBrowser.sort.name'), value: 'name'},
{label: this.t.translate('authorBrowser.sort.bookCount'), value: 'book-count'},
{label: this.t.translate('authorBrowser.sort.matched'), value: 'matched'},
{label: this.t.translate('authorBrowser.sort.recentlyAdded'), value: 'recently-added'},
{label: this.t.translate('authorBrowser.sort.recentlyRead'), value: 'recently-read'},
{label: this.t.translate('authorBrowser.sort.readingProgress'), value: 'reading-progress'},
{label: this.t.translate('authorBrowser.sort.avgRating'), value: 'avg-rating'},
{label: this.t.translate('authorBrowser.sort.photo'), value: 'photo'},
{label: this.t.translate('authorBrowser.sort.seriesCount'), value: 'series-count'}
];
const sortParam = this.activatedRoute.snapshot.queryParamMap.get('sort');
const dirParam = this.activatedRoute.snapshot.queryParamMap.get('dir') as SortDirection | null;
if (sortParam && this.validSortValues.includes(sortParam)) {
this.sortBy$.next(sortParam);
this.sortDirection$.next(dirParam === 'asc' || dirParam === 'desc' ? dirParam : DEFAULT_SORT_DIRECTIONS[sortParam]);
}
this.subscriptions.push(
this.authorService.allAuthors$.pipe(
filter((authors): authors is AuthorSummary[] => authors !== null)
).subscribe(authors => {
this.allAuthors$.next(authors);
this.authorsLoaded = true;
this.updateLoading();
})
);
this.subscriptions.push(
combineLatest([
this.allAuthors$,
this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => state.books || [])
)
]).subscribe(([authors, books]) => {
this.booksLoaded = true;
this.updateLoading();
const enriched = this.enrichAuthors(authors, books);
this.updateDynamicFilterOptions(enriched);
this.enrichedAuthors$.next(enriched);
})
);
this.filteredAuthors$ = combineLatest([
this.enrichedAuthors$,
this.searchTerm$,
this.sortBy$,
this.sortDirection$,
this.filters$
]).pipe(
map(([enriched, search, sortBy, sortDir, filters]) => {
let result = enriched;
if (search.trim()) {
const term = search.trim().toLowerCase();
result = result.filter(a => a.name.toLowerCase().includes(term));
}
result = this.applyFilters(result, filters);
result = this.applySort(result, sortBy, sortDir);
this.selectionService.setCurrentAuthors(result);
return result;
})
);
this.subscriptions.push(
this.selectionService.selectedAuthors$.subscribe(selected => {
this.selectedCount = selected.size;
this.isCheckboxEnabled = selected.size > 0;
})
);
this.setupScrollPositionTracking();
}
ngOnDestroy(): void {
this.subscriptions.forEach(s => s.unsubscribe());
this.selectionService.deselectAll();
}
onSearchChange(value: string): void {
this.searchTerm$.next(value);
}
onSortChange(value: string): void {
this.sortBy$.next(value);
this.sortDirection$.next(DEFAULT_SORT_DIRECTIONS[value] || 'asc');
this.updateSortQueryParams(value, this.sortDirection$.value);
}
toggleSortDirection(): void {
const next: SortDirection = this.sortDirection$.value === 'asc' ? 'desc' : 'asc';
this.sortDirection$.next(next);
this.updateSortQueryParams(this.sortBy$.value, next);
}
onFilterChange(key: keyof AuthorFilters, value: string): void {
const current = this.filters$.value;
this.filters$.next({...current, [key]: value});
this.updateActiveFilterCount();
}
resetFilters(): void {
this.filters$.next({...DEFAULT_AUTHOR_FILTERS});
this.activeFilterCount = 0;
}
updateScale(): void {
this.authorScaleService.setScale(this.authorScaleService.scaleFactor);
}
get canEditMetadata(): boolean {
const user = this.userService.getCurrentUser();
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
}
get canDeleteBook(): boolean {
const user = this.userService.getCurrentUser();
return !!user?.permissions?.admin || !!user?.permissions?.canDeleteBook;
}
isAuthorSelected(authorId: number): boolean {
return this.selectionService.selectedAuthors.has(authorId);
}
onCheckboxClicked(event: AuthorCheckboxClickEvent): void {
this.selectionService.handleCheckboxClick(event);
}
selectAllAuthors(): void {
this.selectionService.selectAll();
}
deselectAllAuthors(): void {
this.selectionService.deselectAll();
}
navigateToAuthor(author: AuthorSummary): void {
this.router.navigate(['/author', author.id]);
}
navigateToAuthorEdit(author: AuthorSummary): void {
this.router.navigate(['/author', author.id], {queryParams: {tab: 'edit'}});
}
deleteAuthor(author: AuthorSummary): void {
this.authorService.deleteAuthors([author.id]).subscribe({
next: () => {
this.removeAuthorsFromList([author.id]);
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.toast.deleteSuccessSummary'),
detail: this.t.translate('authorBrowser.toast.deleteSuccessDetail')
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.toast.deleteFailedSummary'),
detail: this.t.translate('authorBrowser.toast.deleteFailedDetail')
});
}
});
}
onAuthorQuickMatched(updated: AuthorSummary): void {
this.thumbnailCacheBusters.set(updated.id, Date.now());
const current = this.allAuthors$.value;
const updatedList = current.map(a => a.id === updated.id ? updated : a);
this.allAuthors$.next(updatedList);
}
autoMatchSelected(): void {
const ids = this.selectionService.getSelectedIds();
this.selectionService.deselectAll();
this.authorService.autoMatchAuthors(ids).subscribe({
next: (matched) => {
this.thumbnailCacheBusters.set(matched.id, Date.now());
const current = this.allAuthors$.value;
this.allAuthors$.next(current.map(a => a.id === matched.id
? {...a, asin: matched.asin, hasPhoto: matched.hasPhoto}
: a
));
},
complete: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.toast.autoMatchSuccessSummary'),
detail: this.t.translate('authorBrowser.toast.autoMatchSuccessDetail')
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.toast.autoMatchFailedSummary'),
detail: this.t.translate('authorBrowser.toast.autoMatchFailedDetail')
});
}
});
}
deleteSelected(): void {
const ids = this.selectionService.getSelectedIds();
this.authorService.deleteAuthors(ids).subscribe({
next: () => {
this.selectionService.deselectAll();
this.removeAuthorsFromList(ids);
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.toast.deleteSelectedSuccessSummary'),
detail: this.t.translate('authorBrowser.toast.deleteSelectedSuccessDetail')
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.toast.deleteFailedSummary'),
detail: this.t.translate('authorBrowser.toast.deleteFailedDetail')
});
}
});
}
private updateSortQueryParams(sort: string, dir: SortDirection): void {
this.router.navigate([], {
queryParams: {sort, dir},
queryParamsHandling: 'merge',
replaceUrl: true
});
}
private updateLoading(): void {
this.loading = !this.authorsLoaded || !this.booksLoaded;
}
private updateActiveFilterCount(): void {
const f = this.filters$.value;
let count = 0;
if (f.matchStatus !== 'all') count++;
if (f.photoStatus !== 'all') count++;
if (f.readStatus !== 'all') count++;
if (f.bookCount !== 'all') count++;
if (f.library !== 'all') count++;
if (f.genre !== 'all') count++;
this.activeFilterCount = count;
}
private updateDynamicFilterOptions(authors: EnrichedAuthor[]): void {
const allLabel = this.t.translate('authorBrowser.filters.all');
const librarySet = new Set<string>();
const genreSet = new Set<string>();
for (const a of authors) {
for (const lib of a.libraryNames) librarySet.add(lib);
for (const cat of a.categories) genreSet.add(cat);
}
this.libraryOptions = [
{label: allLabel, value: 'all'},
...[...librarySet].sort().map(lib => ({label: lib, value: lib}))
];
this.genreOptions = [
{label: allLabel, value: 'all'},
...[...genreSet].sort().map(cat => ({label: cat, value: cat}))
];
}
private enrichAuthors(authors: AuthorSummary[], books: Book[]): EnrichedAuthor[] {
const booksByAuthor = new Map<string, Book[]>();
for (const book of books) {
if (book.metadata?.authors) {
for (const authorName of book.metadata.authors) {
const key = authorName.toLowerCase();
let list = booksByAuthor.get(key);
if (!list) {
list = [];
booksByAuthor.set(key, list);
}
list.push(book);
}
}
}
return authors.map(author => {
const authorBooks = booksByAuthor.get(author.name.toLowerCase()) || [];
const libraryIds = new Set<number>();
const libraryNameSet = new Set<string>();
const categorySet = new Set<string>();
const seriesSet = new Set<string>();
let latestAddedOn: string | null = null;
let lastReadTime: string | null = null;
let readCount = 0;
let inProgressCount = 0;
let ratingSum = 0;
let ratingCount = 0;
for (const book of authorBooks) {
libraryIds.add(book.libraryId);
if (book.libraryName) libraryNameSet.add(book.libraryName);
if (book.metadata?.categories) {
for (const cat of book.metadata.categories) categorySet.add(cat);
}
if (book.metadata?.seriesName) {
seriesSet.add(book.metadata.seriesName.toLowerCase());
}
if (book.addedOn && (!latestAddedOn || book.addedOn > latestAddedOn)) {
latestAddedOn = book.addedOn;
}
if (book.lastReadTime && (!lastReadTime || book.lastReadTime > lastReadTime)) {
lastReadTime = book.lastReadTime;
}
if (book.readStatus === ReadStatus.READ) readCount++;
if (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING) inProgressCount++;
if (book.personalRating != null) {
ratingSum += book.personalRating;
ratingCount++;
}
}
const totalBooks = authorBooks.length;
let readStatus: EnrichedAuthor['readStatus'] = 'unread';
if (totalBooks > 0) {
if (readCount === totalBooks) {
readStatus = 'all-read';
} else if (inProgressCount > 0) {
readStatus = 'in-progress';
} else if (readCount > 0) {
readStatus = 'some-read';
}
}
return {
...author,
libraryIds,
libraryNames: [...libraryNameSet].sort(),
categories: [...categorySet].sort(),
readStatus,
hasSeries: seriesSet.size > 0,
seriesCount: seriesSet.size,
latestAddedOn,
lastReadTime,
readingProgress: totalBooks > 0 ? Math.round((readCount / totalBooks) * 100) : 0,
avgPersonalRating: ratingCount > 0 ? ratingSum / ratingCount : null
};
});
}
private applyFilters(authors: EnrichedAuthor[], filters: AuthorFilters): EnrichedAuthor[] {
return authors.filter(a => {
if (filters.matchStatus === 'matched' && !a.asin) return false;
if (filters.matchStatus === 'unmatched' && a.asin) return false;
if (filters.photoStatus === 'has-photo' && !a.hasPhoto) return false;
if (filters.photoStatus === 'no-photo' && a.hasPhoto) return false;
if (filters.readStatus !== 'all' && a.readStatus !== filters.readStatus) return false;
if (filters.bookCount !== 'all') {
const c = a.bookCount;
switch (filters.bookCount) {
case '0': if (c !== 0) return false; break;
case '1': if (c !== 1) return false; break;
case '2': if (c !== 2) return false; break;
case '3': if (c !== 3) return false; break;
case '4': if (c !== 4) return false; break;
case '5': if (c !== 5) return false; break;
case '6-10': if (c < 6 || c > 10) return false; break;
case '11-20': if (c < 11 || c > 20) return false; break;
case '21-35': if (c < 21 || c > 35) return false; break;
case '36+': if (c < 36) return false; break;
}
}
if (filters.library !== 'all' && !a.libraryNames.includes(filters.library)) return false;
if (filters.genre !== 'all' && !a.categories.includes(filters.genre)) return false;
return true;
});
}
private getScrollPositionKey(): string {
const path = this.activatedRoute.snapshot.routeConfig?.path ?? '';
return this.scrollService.createKey(path, this.activatedRoute.snapshot.params);
}
private setupScrollPositionTracking(): void {
this.subscriptions.push(
this.router.events.pipe(
filter(event => event instanceof NavigationStart)
).subscribe(() => {
this.dismissBodyMenus();
this.saveScrollPosition();
})
);
}
private dismissBodyMenus(): void {
document.querySelectorAll('.p-tieredmenu-overlay').forEach(el => el.remove());
}
private saveScrollPosition(): void {
if (this.virtualScroller?.viewPortInfo) {
const key = this.getScrollPositionKey();
const position = this.virtualScroller.viewPortInfo.scrollStartPosition ?? 0;
this.scrollService.savePosition(key, position);
}
}
private removeAuthorsFromList(ids: number[]): void {
const idSet = new Set(ids);
const updated = this.allAuthors$.value.filter(a => !idSet.has(a.id));
this.allAuthors$.next(updated);
}
private applySort(authors: EnrichedAuthor[], sortBy: string, direction: SortDirection): EnrichedAuthor[] {
const sorted = [...authors];
const dir = direction === 'asc' ? 1 : -1;
switch (sortBy) {
case 'name':
return sorted.sort((a, b) => dir * a.name.localeCompare(b.name));
case 'book-count':
return sorted.sort((a, b) => dir * (a.bookCount - b.bookCount));
case 'matched':
return sorted.sort((a, b) => {
const aVal = a.asin ? 1 : 0;
const bVal = b.asin ? 1 : 0;
if (aVal !== bVal) return dir * (aVal - bVal);
return a.name.localeCompare(b.name);
});
case 'recently-added':
return sorted.sort((a, b) => {
if (!a.latestAddedOn && !b.latestAddedOn) return a.name.localeCompare(b.name);
if (!a.latestAddedOn) return 1;
if (!b.latestAddedOn) return -1;
return dir * a.latestAddedOn.localeCompare(b.latestAddedOn);
});
case 'recently-read':
return sorted.sort((a, b) => {
if (!a.lastReadTime && !b.lastReadTime) return a.name.localeCompare(b.name);
if (!a.lastReadTime) return 1;
if (!b.lastReadTime) return -1;
return dir * a.lastReadTime.localeCompare(b.lastReadTime);
});
case 'reading-progress':
return sorted.sort((a, b) => dir * (a.readingProgress - b.readingProgress));
case 'avg-rating':
return sorted.sort((a, b) => {
if (a.avgPersonalRating == null && b.avgPersonalRating == null) return a.name.localeCompare(b.name);
if (a.avgPersonalRating == null) return 1;
if (b.avgPersonalRating == null) return -1;
return dir * (a.avgPersonalRating - b.avgPersonalRating);
});
case 'photo':
return sorted.sort((a, b) => {
const aVal = a.hasPhoto ? 1 : 0;
const bVal = b.hasPhoto ? 1 : 0;
if (aVal !== bVal) return dir * (aVal - bVal);
return a.name.localeCompare(b.name);
});
case 'series-count':
return sorted.sort((a, b) => dir * (a.seriesCount - b.seriesCount));
default:
return sorted;
}
}
}
@@ -0,0 +1,48 @@
<div class="author-card" [class.selected]="isSelected" (click)="onCardClick($event)">
<div class="cover-container" [ngClass]="{'loaded': isImageLoaded}">
@if (hasPhoto) {
<img
[src]="thumbnailUrl"
class="author-photo"
[class.loaded]="isImageLoaded"
[alt]="author.name"
loading="lazy"
decoding="async"
(load)="onImageLoad()"
(error)="onPhotoError()"/>
} @else {
<div class="author-photo-placeholder">
<i class="pi pi-user"></i>
</div>
}
<span class="book-count-badge">{{ author.bookCount }}</span>
@if (isCheckboxEnabled) {
<p-checkbox
[binary]="true"
class="select-checkbox"
(click)="captureMouseEvent($event)"
[ngModel]="isSelected"
(onChange)="toggleSelection($event)">
</p-checkbox>
}
<div class="card-overlay">
@if (isMatched) {
<i class="pi pi-check-circle matched-icon" [pTooltip]="'authorBrowser.card.matched' | transloco" tooltipPosition="top"></i>
}
<h4 class="author-name" [pTooltip]="author.name" tooltipPosition="bottom">{{ author.name }}</h4>
<div class="menu-button-container">
<p-tieredmenu #menu [model]="items" [popup]="true" appendTo="body" (onShow)="onMenuShow()" (onHide)="onMenuHide()"></p-tieredmenu>
<p-button
class="card-menu-btn"
size="small"
[text]="true"
(click)="onMenuToggle($event, menu)"
icon="pi pi-ellipsis-v">
</p-button>
</div>
</div>
</div>
</div>
@@ -0,0 +1,166 @@
.author-card {
background-color: var(--card-background);
border-radius: 8px;
position: relative;
overflow: hidden;
height: 100%;
display: flex;
flex-direction: column;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: box-shadow 0.25s ease, transform 0.25s ease;
cursor: pointer;
&:hover {
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
transform: translateY(-2px);
}
&.selected {
border: 2px solid var(--primary-color);
}
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
.cover-container {
position: relative;
width: 100%;
height: 100%;
background-color: var(--card-background);
border-radius: 8px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.cover-container:not(.loaded) {
background: linear-gradient(
90deg,
var(--surface-ground) 25%,
var(--surface-hover, rgba(255, 255, 255, 0.08)) 50%,
var(--surface-ground) 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s ease-in-out infinite;
}
.author-photo {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
opacity: 0;
transition: opacity 0.2s ease-in, transform 0.35s ease;
}
.author-photo.loaded {
opacity: 1;
}
.author-card:hover .author-photo.loaded {
transform: scale(1.04);
}
.author-photo-placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
color: #64748b;
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
i {
font-size: 3rem;
}
}
.book-count-badge {
position: absolute;
top: 8px;
left: 8px;
font-size: 0.8rem;
font-weight: 700;
color: #fff;
background: rgba(0, 0, 0, 0.6);
padding: 3px 9px;
border-radius: 10px;
line-height: 1.3;
z-index: 3;
}
.card-overlay {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 8px 2px 4px 8px;
background: linear-gradient(to top, rgba(0, 0, 0, 0.9) 0%, rgba(0, 0, 0, 0.5) 70%, transparent 100%);
display: flex;
align-items: center;
gap: 6px;
z-index: 2;
}
.matched-icon {
color: #22c55e;
font-size: 0.85rem;
flex-shrink: 0;
filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}
.author-name {
font-size: 0.8rem;
font-weight: 600;
color: #fff;
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.3;
flex: 1;
min-width: 0;
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6);
}
.menu-button-container {
flex-shrink: 0;
}
::ng-deep .card-menu-btn .p-button {
padding: 0.15rem 0.25rem !important;
color: #fff !important;
&:hover {
background: rgba(255, 255, 255, 0.15) !important;
}
}
.select-checkbox {
position: absolute;
top: 8px;
right: 8px;
opacity: 0;
visibility: hidden;
transition: opacity 0.15s ease, visibility 0.15s ease;
z-index: 3;
@media (max-width: 767px) {
top: 4px;
right: 4px;
}
}
.cover-container:hover .select-checkbox,
.author-card.selected .select-checkbox {
opacity: 1;
visibility: visible;
}
@@ -0,0 +1,181 @@
import {ChangeDetectorRef, Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
import {NgClass} from '@angular/common';
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {Tooltip} from 'primeng/tooltip';
import {CheckboxChangeEvent, CheckboxModule} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {TieredMenu} from 'primeng/tieredmenu';
import {Button} from 'primeng/button';
import {MenuItem, MessageService} from 'primeng/api';
import {AuthorSummary} from '../../model/author.model';
import {AuthorService} from '../../service/author.service';
@Component({
selector: 'app-author-card',
standalone: true,
templateUrl: './author-card.component.html',
styleUrls: ['./author-card.component.scss'],
imports: [NgClass, TranslocoPipe, Tooltip, CheckboxModule, FormsModule, TieredMenu, Button]
})
export class AuthorCardComponent implements OnChanges {
@Input({required: true}) author!: AuthorSummary;
@Input() canQuickMatch = false;
@Input() canDelete = false;
@Input() isCheckboxEnabled = false;
@Input() isSelected = false;
@Output() cardClick = new EventEmitter<AuthorSummary>();
@Output() quickMatched = new EventEmitter<AuthorSummary>();
@Output() checkboxClick = new EventEmitter<{ index: number; author: AuthorSummary; selected: boolean; shiftKey: boolean }>();
@Output() viewAuthor = new EventEmitter<AuthorSummary>();
@Output() editAuthor = new EventEmitter<AuthorSummary>();
@Output() deleteAuthor = new EventEmitter<AuthorSummary>();
@Output() menuToggled = new EventEmitter<boolean>();
@Input() index = 0;
@Input() cacheBuster = 0;
private authorService = inject(AuthorService);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
private cdr = inject(ChangeDetectorRef);
private lastShiftKey = false;
hasPhoto = false;
isImageLoaded = false;
quickMatching = false;
items: MenuItem[] = [];
private menuInitialized = false;
ngOnChanges(changes: SimpleChanges): void {
if (changes['author']) {
const prev = changes['author'].previousValue as AuthorSummary | undefined;
const curr = changes['author'].currentValue as AuthorSummary;
if (!prev || prev.id !== curr.id || prev.hasPhoto !== curr.hasPhoto || prev.asin !== curr.asin) {
this.hasPhoto = curr.hasPhoto;
this.isImageLoaded = false;
}
}
if (changes['cacheBuster'] && !changes['cacheBuster'].firstChange) {
this.hasPhoto = true;
this.isImageLoaded = false;
}
}
get thumbnailUrl(): string {
return this.authorService.getAuthorThumbnailUrl(this.author.id, this.cacheBuster || undefined);
}
get isMatched(): boolean {
return !!this.author.asin;
}
onCardClick(event: MouseEvent): void {
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
event.stopPropagation();
this.toggleCardSelection(!this.isSelected);
return;
}
event.stopPropagation();
this.cardClick.emit(this.author);
}
onImageLoad(): void {
this.isImageLoaded = true;
}
onPhotoError(): void {
this.hasPhoto = false;
}
captureMouseEvent(event: MouseEvent): void {
event.stopPropagation();
this.lastShiftKey = event.shiftKey;
}
toggleSelection(event: CheckboxChangeEvent): void {
this.checkboxClick.emit({index: this.index, author: this.author, selected: event.checked, shiftKey: this.lastShiftKey});
}
toggleCardSelection(selected: boolean): void {
this.checkboxClick.emit({index: this.index, author: this.author, selected, shiftKey: false});
}
onMenuToggle(event: Event, menu: TieredMenu): void {
event.stopPropagation();
if (!this.menuInitialized) {
this.menuInitialized = true;
this.initMenu();
this.cdr.markForCheck();
}
menu.toggle(event);
}
onMenuShow(): void {
this.menuToggled.emit(true);
}
onMenuHide(): void {
this.menuToggled.emit(false);
}
private initMenu(): void {
this.items = [
{
label: this.t.translate('authorBrowser.card.menu.viewAuthor'),
icon: 'pi pi-user',
command: () => this.viewAuthor.emit(this.author)
},
...(this.canQuickMatch ? [
{
label: this.t.translate('authorBrowser.card.menu.editAuthor'),
icon: 'pi pi-pencil',
command: () => this.editAuthor.emit(this.author)
},
{
label: this.t.translate('authorBrowser.card.menu.quickMatch'),
icon: this.quickMatching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt',
disabled: this.quickMatching,
command: () => this.onQuickMatch()
}
] : []),
...(this.canDelete ? [
{
label: this.t.translate('authorBrowser.card.menu.deleteAuthor'),
icon: 'pi pi-trash',
command: () => this.deleteAuthor.emit(this.author)
}
] : [])
];
}
private onQuickMatch(): void {
if (this.quickMatching) return;
this.quickMatching = true;
this.authorService.quickMatchAuthor(this.author.id).subscribe({
next: (updated) => {
this.quickMatching = false;
this.author = {...this.author, asin: updated.asin, hasPhoto: true};
this.hasPhoto = true;
this.isImageLoaded = false;
this.menuInitialized = false;
this.quickMatched.emit(this.author);
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.toast.quickMatchSuccessSummary'),
detail: this.t.translate('authorBrowser.toast.quickMatchSuccessDetail')
});
},
error: () => {
this.quickMatching = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.toast.quickMatchFailedSummary'),
detail: this.t.translate('authorBrowser.toast.quickMatchFailedDetail')
});
}
});
}
}
@@ -0,0 +1,148 @@
<ng-container *transloco="let t; prefix: 'authorBrowser.detail'">
@if (loading) {
<div class="loading-state">
<p-progressSpinner strokeWidth="4" fill="transparent" animationDuration=".8s">
</p-progressSpinner>
<p style="color: var(--primary-color);">{{ t('loading') }}</p>
</div>
}
@if (!loading && author) {
<div class="author-wrapper">
<p-tabs [value]="tab" lazy="true" scrollable>
<p-tablist>
<p-tab value="books">
<i class="pi pi-user"></i>
{{ t('booksTab') }}
</p-tab>
@if (canEditMetadata) {
<p-tab value="edit">
<i class="pi pi-pencil"></i>
{{ t('editTab') }}
</p-tab>
<p-tab value="match">
<i class="pi pi-search"></i>
{{ t('matchTab') }}
</p-tab>
}
</p-tablist>
<p-tabpanels class="tabpanels-responsive">
<p-tabpanel value="books">
<div class="author-header">
<div class="author-photo-section">
@if (hasPhoto) {
<img
[src]="photoUrl"
class="author-photo-large"
[alt]="author.name"
(error)="onPhotoError()"/>
} @else {
<div class="author-photo-placeholder-large">
<i class="pi pi-user"></i>
</div>
}
</div>
<div class="author-info">
<div class="author-title-row">
<h2 class="author-title">{{ author.name }}</h2>
@if (author.asin) {
<a [href]="'https://www.amazon.com/stores/author/' + author.asin + '/about'"
target="_blank"
rel="noopener noreferrer"
class="asin-link">
<p-tag [value]="'ASIN: ' + author.asin" severity="info"></p-tag>
</a>
<a [href]="'https://www.audible.com/author/' + author.asin"
target="_blank"
rel="noopener noreferrer"
class="asin-link">
<p-tag value="Audible" severity="warn"></p-tag>
</a>
}
@if (canEditMetadata) {
<p-button
[icon]="quickMatching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
[outlined]="true"
severity="warn"
size="small"
[disabled]="quickMatching"
(onClick)="quickMatch()"
[pTooltip]="t('quickMatchTooltip')"
tooltipPosition="top">
</p-button>
}
</div>
@if (author.description) {
<div class="description-box">
<div #descriptionContent
[ngClass]="{'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded}"
class="description-container">
<div class="readonly-editor">{{ author.description }}</div>
</div>
@if (isExpanded || isOverflowing) {
<p-button
[label]="isExpanded ? t('showLess') : t('showMore')"
[icon]="isExpanded ? 'pi pi-chevron-up' : 'pi pi-chevron-down'"
iconPos="right"
size="small"
text
(click)="toggleExpand()">
</p-button>
}
</div>
}
</div>
</div>
@if (authorBooks$ | async; as books) {
<div class="books-section">
<h3 class="section-title">{{ t('booksBy', {name: author.name}) }} ({{ books.length }})</h3>
@if (books.length === 0) {
<div class="empty-books">
<i class="pi pi-book"></i>
<p>{{ t('noBooksFound') }}</p>
</div>
} @else {
<virtual-scroller #scroll [items]="books" class="books-virtual-scroller">
<div class="books-grid" #container
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
@for (book of scroll.viewPortItems; track book.id; let i = $index) {
<div class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
<app-book-card
[index]="books.indexOf(book)"
[book]="book"
[isSeriesCollapsed]="false"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
}
</div>
</virtual-scroller>
}
</div>
}
</p-tabpanel>
@if (canEditMetadata) {
<p-tabpanel value="edit">
<app-author-editor
[authorId]="author.id"
[author]="author"
(authorUpdated)="onAuthorUpdated($event)">
</app-author-editor>
</p-tabpanel>
<p-tabpanel value="match">
<app-author-match
[authorId]="author.id"
[authorName]="author.name"
(authorMatched)="onAuthorUpdated($event)">
</app-author-match>
</p-tabpanel>
}
</p-tabpanels>
</p-tabs>
</div>
}
</ng-container>
@@ -0,0 +1,211 @@
.tabpanels-responsive {
height: calc(100dvh - 9.7rem);
overflow: auto;
}
@media (max-width: 768px) {
.tabpanels-responsive {
height: calc(100dvh - 8.5rem);
}
}
.author-wrapper {
position: relative;
border-radius: 0.75rem;
overflow: hidden;
border: 1px solid var(--p-content-border-color);
}
.loading-state {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
gap: 1rem;
}
.author-header {
display: flex;
gap: 1.5rem;
padding: 0.5rem;
margin-bottom: 1.5rem;
@media (max-width: 767px) {
flex-direction: column;
align-items: center;
text-align: center;
}
}
.author-photo-section {
flex-shrink: 0;
}
.author-photo-large {
width: 180px;
height: 220px;
object-fit: cover;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
@media (max-width: 767px) {
width: 140px;
height: 175px;
}
}
.author-photo-placeholder-large {
width: 180px;
height: 220px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
color: #64748b;
i {
font-size: 4rem;
}
@media (max-width: 767px) {
width: 140px;
height: 175px;
}
}
.author-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.author-title-row {
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
@media (max-width: 767px) {
justify-content: center;
}
}
.asin-link {
text-decoration: none;
cursor: pointer;
transition: opacity 0.2s;
&:hover {
opacity: 0.8;
}
}
.author-title {
font-size: 1.5rem;
font-weight: 800;
line-height: 1.25;
margin: 0;
@media (min-width: 768px) {
font-size: 1.875rem;
}
}
.description-box {
padding: 1rem 0.5rem 0.5rem;
@media (max-width: 767px) {
text-align: left;
}
}
.description-container {
transition: all 0.3s;
overflow: hidden;
}
.line-clamp-5 {
display: -webkit-box;
-webkit-line-clamp: 5;
-webkit-box-orient: vertical;
overflow: hidden;
}
.line-clamp-none {
-webkit-line-clamp: unset;
}
.readonly-editor {
font-size: 0.9rem;
color: #d1d5db;
line-height: 1.6;
white-space: pre-wrap;
}
.books-section {
padding: 0 0.5rem;
}
.section-title {
font-size: 1.1rem;
font-weight: 700;
margin-bottom: 1rem;
color: #e2e8f0;
}
.books-virtual-scroller {
width: 100%;
height: calc(100dvh - 22rem);
box-sizing: border-box;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--primary-color) rgba(20, 20, 30, 0.5);
&::-webkit-scrollbar {
width: 12px;
}
&::-webkit-scrollbar-track {
background: rgba(20, 20, 30, 0.5);
border-radius: 10px;
}
}
.books-grid {
display: grid;
gap: 1.3rem;
align-items: start;
justify-items: center;
width: 100%;
padding: 0.5rem;
}
.virtual-scroller-item {
position: relative;
overflow: visible;
}
.empty-books {
display: flex;
flex-direction: column;
align-items: center;
padding: 3rem;
text-align: center;
i {
font-size: 2.5rem;
color: #64748b;
margin-bottom: 0.75rem;
}
p {
color: #94a3b8;
font-size: 1rem;
margin: 0;
}
}
@@ -0,0 +1,184 @@
import {AfterViewChecked, Component, ElementRef, inject, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AsyncPipe, NgClass, NgStyle} from '@angular/common';
import {combineLatest, Observable} from 'rxjs';
import {filter, map} from 'rxjs/operators';
import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs';
import {ProgressSpinner} from 'primeng/progressspinner';
import {Button} from 'primeng/button';
import {Tag} from 'primeng/tag';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {MessageService} from 'primeng/api';
import {Tooltip} from 'primeng/tooltip';
import {AuthorService} from '../../service/author.service';
import {AuthorDetails} from '../../model/author.model';
import {BookService} from '../../../book/service/book.service';
import {Book} from '../../../book/model/book.model';
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
import {CoverScalePreferenceService} from '../../../book/components/book-browser/cover-scale-preference.service';
import {BookCardOverlayPreferenceService} from '../../../book/components/book-browser/book-card-overlay-preference.service';
import {UserService} from '../../../settings/user-management/user.service';
import {AuthorMatchComponent} from '../author-match/author-match.component';
import {AuthorEditorComponent} from '../author-editor/author-editor.component';
import {PageTitleService} from '../../../../shared/service/page-title.service';
@Component({
selector: 'app-author-detail',
standalone: true,
templateUrl: './author-detail.component.html',
styleUrls: ['./author-detail.component.scss'],
imports: [
AsyncPipe,
NgClass,
NgStyle,
Tabs,
TabList,
Tab,
TabPanels,
TabPanel,
ProgressSpinner,
Button,
Tag,
TranslocoDirective,
Tooltip,
VirtualScrollerModule,
BookCardComponent,
AuthorMatchComponent,
AuthorEditorComponent
]
})
export class AuthorDetailComponent implements OnInit, AfterViewChecked {
private route = inject(ActivatedRoute);
private router = inject(Router);
private authorService = inject(AuthorService);
private bookService = inject(BookService);
private messageService = inject(MessageService);
protected coverScalePreferenceService = inject(CoverScalePreferenceService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
protected userService = inject(UserService);
private pageTitle = inject(PageTitleService);
private t = inject(TranslocoService);
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
author: AuthorDetails | null = null;
loading = true;
tab = 'books';
isExpanded = false;
isOverflowing = false;
hasPhoto = true;
photoTimestamp = Date.now();
quickMatching = false;
authorBooks$!: Observable<Book[]>;
get currentCardSize() {
return this.coverScalePreferenceService.currentCardSize;
}
get gridColumnMinWidth(): string {
return this.coverScalePreferenceService.gridColumnMinWidth;
}
get photoUrl(): string {
if (!this.author) return '';
return this.authorService.getAuthorPhotoUrl(this.author.id) + '&t=' + this.photoTimestamp;
}
get canEditMetadata(): boolean {
const user = this.userService.getCurrentUser();
return !!user?.permissions?.admin || !!user?.permissions?.canEditMetadata;
}
ngOnInit(): void {
const authorId = Number(this.route.snapshot.paramMap.get('authorId'));
const tabParam = this.route.snapshot.queryParamMap.get('tab');
if (tabParam) {
this.tab = tabParam;
}
this.loadAuthor(authorId);
this.authorBooks$ = this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => {
const books = state.books || [];
const authorName = this.author?.name?.toLowerCase();
if (!authorName) return [];
return books.filter(b =>
b.metadata?.authors?.some(a => a.toLowerCase() === authorName)
);
})
);
}
ngAfterViewChecked(): void {
if (!this.isExpanded && this.descriptionContentRef) {
const el = this.descriptionContentRef.nativeElement;
this.isOverflowing = el.scrollHeight > el.clientHeight;
}
}
toggleExpand(): void {
this.isExpanded = !this.isExpanded;
}
onPhotoError(): void {
this.hasPhoto = false;
}
onAuthorUpdated(updatedAuthor: AuthorDetails): void {
this.author = updatedAuthor;
this.hasPhoto = true;
this.photoTimestamp = Date.now();
}
quickMatch(): void {
if (!this.author || this.quickMatching) return;
this.quickMatching = true;
this.authorService.quickMatchAuthor(this.author.id).subscribe({
next: (matched) => {
this.onAuthorUpdated(matched);
this.quickMatching = false;
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.toast.quickMatchSuccessSummary'),
detail: this.t.translate('authorBrowser.toast.quickMatchSuccessDetail')
});
},
error: () => {
this.quickMatching = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.toast.quickMatchFailedSummary'),
detail: this.t.translate('authorBrowser.toast.quickMatchFailedDetail')
});
}
});
}
private loadAuthor(authorId: number): void {
this.authorService.getAuthorDetails(authorId).subscribe({
next: (author) => {
this.author = author;
this.loading = false;
this.pageTitle.setPageTitle(author.name);
this.authorBooks$ = this.bookService.bookState$.pipe(
filter(state => state.loaded && !!state.books),
map(state => {
const books = state.books || [];
const name = author.name.toLowerCase();
return books.filter(b =>
b.metadata?.authors?.some(a => a.toLowerCase() === name)
);
})
);
},
error: () => {
this.loading = false;
}
});
}
}
@@ -0,0 +1,134 @@
<ng-container *transloco="let t; prefix: 'authorBrowser.editor'">
<div class="editor-container">
<div class="cover-section">
@if (hasPhoto) {
<p-image
[src]="photoUrl"
alt="Author Photo"
width="200"
appendTo="body"
[preview]="true"
(onImageError)="onPhotoError()">
</p-image>
} @else {
<div class="photo-placeholder">
<i class="pi pi-user"></i>
</div>
}
@if (isUploading) {
<p-progressSpinner class="upload-spinner" strokeWidth="4" fill="transparent" animationDuration=".8s"></p-progressSpinner>
}
<div class="cover-actions">
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
[pTooltip]="t('uploadPhotoTooltip')"
tooltipPosition="top"
[disabled]="form.get('photoLocked')?.value"
name="file"
[url]="uploadUrl"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onUpload()"
(onError)="onUploadError()"
[auto]="true"
(onBeforeUpload)="onBeforeUpload()">
</p-fileupload>
<p-button
[pTooltip]="t('searchPhotoTooltip')"
tooltipPosition="top"
size="small"
icon="pi pi-search"
[outlined]="true"
[disabled]="form.get('photoLocked')?.value"
(onClick)="openPhotoSearch()"
severity="info">
</p-button>
@if (!form.get('photoLocked')?.value) {
<p-button
[pTooltip]="t('lockField')"
tooltipPosition="top"
size="small"
icon="pi pi-lock-open"
[outlined]="true"
(onClick)="togglePhotoLock()"
severity="success">
</p-button>
}
@if (form.get('photoLocked')?.value) {
<p-button
[pTooltip]="t('unlockField')"
tooltipPosition="top"
size="small"
icon="pi pi-lock"
[outlined]="true"
(onClick)="togglePhotoLock()"
severity="warn">
</p-button>
}
</div>
</div>
<form class="fields-section" [formGroup]="form" (ngSubmit)="onSave()">
<div class="field-group">
<label for="authorName">{{ t('nameLabel') }}</label>
<div class="field-with-lock">
<input pInputText id="authorName" formControlName="name"/>
@if (!form.get('nameLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('name')" severity="success"></p-button>
}
@if (form.get('nameLocked')?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('name')" severity="warn"></p-button>
}
</div>
</div>
<div class="field-group">
<label for="authorAsin">{{ t('asinLabel') }}</label>
<div class="field-with-lock">
<input pInputText id="authorAsin" formControlName="asin"/>
@if (!form.get('asinLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
}
@if (form.get('asinLocked')?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
}
</div>
</div>
<div class="field-group description-group">
<label for="authorDescription">{{ t('descriptionLabel') }}</label>
<div class="field-with-lock description-with-lock">
<textarea pTextarea id="authorDescription" formControlName="description"
[rows]="8" [autoResize]="true"></textarea>
@if (!form.get('descriptionLocked')?.value) {
<p-button icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('description')" severity="success" size="small"></p-button>
}
@if (form.get('descriptionLocked')?.value) {
<p-button icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('description')" severity="warn" size="small"></p-button>
}
</div>
</div>
<div class="form-footer">
<p-divider></p-divider>
<div class="footer-actions">
<p-button [label]="t('unlockAllBtn')" icon="pi pi-lock-open" [outlined]="true" severity="success" (onClick)="unlockAll()"></p-button>
<p-button [label]="t('lockAllBtn')" icon="pi pi-lock" [outlined]="true" severity="warn" (onClick)="lockAll()"></p-button>
<p-divider layout="vertical"/>
<p-button
type="submit"
[label]="isSaving ? t('saving') : t('saveBtn')"
[icon]="isSaving ? 'pi pi-spin pi-spinner' : 'pi pi-check'"
[disabled]="isSaving">
</p-button>
</div>
</div>
</form>
</div>
</ng-container>
@@ -0,0 +1,126 @@
:host {
display: flex;
flex-direction: column;
flex: 1;
min-height: calc(100dvh - 11rem);
}
.editor-container {
padding: 1rem 0.5rem;
display: flex;
gap: 2rem;
flex: 1;
@media (max-width: 767px) {
flex-direction: column;
align-items: center;
}
}
.cover-section {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
position: relative;
}
.photo-placeholder {
width: 200px;
height: 280px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
color: #64748b;
i {
font-size: 4rem;
}
}
.upload-spinner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.cover-actions {
display: flex;
align-items: center;
gap: 0.75rem;
padding-top: 0.75rem;
}
.fields-section {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.field-group {
margin-bottom: 1.25rem;
label {
display: block;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-color-secondary);
margin-bottom: 0.4rem;
}
}
.field-with-lock {
display: flex;
input,
textarea {
width: 100%;
}
}
::ng-deep .field-with-lock input {
border-radius: 6px 0 0 6px;
}
.field-with-lock textarea {
border-radius: 6px 0 6px 6px;
}
::ng-deep .field-with-lock button {
border-color: var(--p-inputtext-border-color) !important;
border-radius: 0 6px 6px 0 !important;
border-left: 0px !important;
}
.description-with-lock {
display: flex;
flex-grow: 1;
width: 100%;
textarea {
width: 100%;
height: 100%;
}
}
.form-footer {
margin-top: auto;
}
.footer-actions {
display: flex;
align-items: center;
gap: 0.5rem;
justify-content: flex-end;
padding: 0.5rem 0;
@media (max-width: 639px) {
flex-wrap: wrap;
justify-content: center;
}
}
@@ -0,0 +1,220 @@
import {Component, EventEmitter, inject, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {Textarea} from 'primeng/textarea';
import {Tooltip} from 'primeng/tooltip';
import {Image} from 'primeng/image';
import {FileUpload} from 'primeng/fileupload';
import {ProgressSpinner} from 'primeng/progressspinner';
import {Divider} from 'primeng/divider';
import {MessageService} from 'primeng/api';
import {DialogService} from 'primeng/dynamicdialog';
import {AuthorService} from '../../service/author.service';
import {AuthorDetails} from '../../model/author.model';
import {AuthorPhotoSearchComponent} from '../author-photo-search/author-photo-search.component';
@Component({
selector: 'app-author-editor',
standalone: true,
templateUrl: './author-editor.component.html',
styleUrls: ['./author-editor.component.scss'],
imports: [
ReactiveFormsModule,
TranslocoDirective,
Button,
InputText,
Textarea,
Tooltip,
Image,
FileUpload,
ProgressSpinner,
Divider
],
providers: [DialogService]
})
export class AuthorEditorComponent implements OnInit, OnChanges {
@Input({required: true}) authorId!: number;
@Input({required: true}) author!: AuthorDetails;
@Output() authorUpdated = new EventEmitter<AuthorDetails>();
private authorService = inject(AuthorService);
private messageService = inject(MessageService);
private dialogService = inject(DialogService);
private t = inject(TranslocoService);
form!: FormGroup;
isSaving = false;
isUploading = false;
hasPhoto = true;
photoTimestamp = Date.now();
get photoUrl(): string {
return this.authorService.getAuthorPhotoUrl(this.authorId) + '&t=' + this.photoTimestamp;
}
get uploadUrl(): string {
return this.authorService.getUploadAuthorPhotoUrl(this.authorId);
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['author'] && !changes['author'].firstChange) {
this.hasPhoto = true;
this.photoTimestamp = Date.now();
}
}
ngOnInit(): void {
this.form = new FormGroup({
name: new FormControl(this.author.name || ''),
nameLocked: new FormControl(this.author.nameLocked || false),
description: new FormControl(this.author.description || ''),
descriptionLocked: new FormControl(this.author.descriptionLocked || false),
asin: new FormControl(this.author.asin || ''),
asinLocked: new FormControl(this.author.asinLocked || false),
photoLocked: new FormControl(this.author.photoLocked || false)
});
this.applyLockStates();
}
toggleLock(field: string): void {
const lockedControl = this.form.get(field + 'Locked');
if (!lockedControl) return;
const isLocked = !lockedControl.value;
lockedControl.setValue(isLocked);
const fieldControl = this.form.get(field);
if (fieldControl) {
isLocked ? fieldControl.disable() : fieldControl.enable();
}
this.saveMetadata();
}
togglePhotoLock(): void {
const lockedControl = this.form.get('photoLocked');
if (!lockedControl) return;
lockedControl.setValue(!lockedControl.value);
this.saveMetadata();
}
onSave(): void {
this.saveMetadata();
}
lockAll(): void {
for (const field of ['name', 'description', 'asin']) {
this.form.get(field + 'Locked')?.setValue(true);
this.form.get(field)?.disable();
}
this.form.get('photoLocked')?.setValue(true);
this.saveMetadata();
}
unlockAll(): void {
for (const field of ['name', 'description', 'asin']) {
this.form.get(field + 'Locked')?.setValue(false);
this.form.get(field)?.enable();
}
this.form.get('photoLocked')?.setValue(false);
this.saveMetadata();
}
openPhotoSearch(): void {
const ref = this.dialogService.open(AuthorPhotoSearchComponent, {
data: {authorId: this.authorId, authorName: this.author.name},
header: this.t.translate('authorBrowser.editor.searchPhotoTitle'),
width: '70vw',
height: '80vh',
modal: true,
closable: true,
dismissableMask: true,
contentStyle: {'overflow': 'hidden', 'padding': '0', 'display': 'flex', 'flex-direction': 'column'}
});
ref?.onClose.subscribe((result: boolean) => {
if (result) {
this.photoTimestamp = Date.now();
this.hasPhoto = true;
this.authorUpdated.emit(this.author);
}
});
}
onPhotoError(): void {
this.hasPhoto = false;
}
onBeforeUpload(): void {
this.isUploading = true;
}
onUpload(): void {
this.isUploading = false;
this.photoTimestamp = Date.now();
this.hasPhoto = true;
this.authorUpdated.emit(this.author);
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.editor.toast.photoUploadedSummary'),
detail: this.t.translate('authorBrowser.editor.toast.photoUploadedDetail')
});
}
onUploadError(): void {
this.isUploading = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
detail: this.t.translate('authorBrowser.editor.toast.photoUploadErrorDetail')
});
}
private saveMetadata(): void {
if (this.isSaving) return;
this.isSaving = true;
const formValue = this.form.getRawValue();
const request = {
name: formValue.name?.trim() || undefined,
description: formValue.description?.trim(),
asin: formValue.asin?.trim(),
nameLocked: formValue.nameLocked,
descriptionLocked: formValue.descriptionLocked,
asinLocked: formValue.asinLocked,
photoLocked: formValue.photoLocked
};
this.authorService.updateAuthor(this.authorId, request).subscribe({
next: (updated) => {
this.isSaving = false;
this.authorUpdated.emit(updated);
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.editor.toast.successSummary'),
detail: this.t.translate('authorBrowser.editor.toast.successDetail')
});
},
error: () => {
this.isSaving = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
detail: this.t.translate('authorBrowser.editor.toast.errorDetail')
});
}
});
}
private applyLockStates(): void {
for (const field of ['name', 'description', 'asin']) {
const lockedControl = this.form.get(field + 'Locked');
const fieldControl = this.form.get(field);
if (lockedControl?.value && fieldControl) {
fieldControl.disable();
}
}
}
}
@@ -0,0 +1,96 @@
<ng-container *transloco="let t; prefix: 'authorBrowser.match'">
<div class="match-container">
<div class="search-form">
<div class="search-fields">
<div class="field">
<label>{{ t('authorNameLabel') }}</label>
<input pInputText type="text" [(ngModel)]="searchQuery" [placeholder]="t('authorNamePlaceholder')" class="search-input"/>
</div>
<div class="field region-field">
<label>{{ t('regionLabel') }}</label>
<p-select
[options]="regionOptions"
[(ngModel)]="selectedRegion"
optionLabel="label"
optionValue="value"
class="region-dropdown">
</p-select>
</div>
<div class="field search-btn-field">
<p-button
[label]="t('searchBtn')"
icon="pi pi-search"
(onClick)="search()"
[loading]="searching"
[disabled]="!searchQuery.trim()">
</p-button>
</div>
</div>
</div>
@if (searching) {
<div class="search-loading">
<p-progressSpinner
[style]="{'width': '40px', 'height': '40px'}"
strokeWidth="3"
fill="transparent"
animationDuration="1.5s">
</p-progressSpinner>
<span>{{ t('searching') }}</span>
</div>
}
@if (!searching && hasSearched && results.length === 0) {
<div class="empty-results">
<i class="pi pi-info-circle"></i>
<p>{{ t('noResults') }}</p>
<p class="hint">{{ t('noResultsHint') }}</p>
</div>
}
@if (!searching && !hasSearched) {
<div class="ready-state">
<i class="pi pi-search"></i>
<p>{{ t('readyToSearch') }}</p>
<p class="hint">{{ t('readyToSearchHint') }}</p>
</div>
}
@if (!searching && results.length > 0) {
<div class="results-header">
<span>{{ t('resultsFound', {count: results.length}) }}</span>
</div>
<div class="results-list">
@for (result of results; track result.asin) {
<div class="result-card">
<div class="result-image">
@if (result.imageUrl) {
<img [src]="result.imageUrl" [alt]="result.name" loading="lazy"/>
} @else {
<div class="result-placeholder">
<i class="pi pi-user"></i>
</div>
}
</div>
<div class="result-info">
<h4 class="result-name">{{ result.name }}</h4>
<span class="result-asin">ASIN: {{ result.asin }}</span>
@if (result.description) {
<p class="result-description">{{ result.description }}</p>
}
</div>
<div class="result-action">
<p-button
[label]="t('matchBtn')"
icon="pi pi-link"
severity="success"
[loading]="matching"
(onClick)="matchAuthor(result)">
</p-button>
</div>
</div>
}
</div>
}
</div>
</ng-container>
@@ -0,0 +1,203 @@
.match-container {
padding: 1rem;
}
.search-form {
margin-bottom: 1.5rem;
}
.search-fields {
display: flex;
gap: 1rem;
align-items: flex-end;
.field {
display: flex;
flex-direction: column;
gap: 0.4rem;
label {
font-size: 0.85rem;
font-weight: 600;
color: #94a3b8;
}
&:first-child {
flex: 1;
min-width: 0;
}
}
.search-input {
width: 100%;
}
.region-field {
min-width: 100px;
}
.region-dropdown {
min-width: 100px;
}
.search-btn-field {
padding-bottom: 1px;
}
}
.search-loading {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 3rem;
color: #94a3b8;
}
.empty-results,
.ready-state {
display: flex;
flex-direction: column;
align-items: center;
padding: 3rem;
text-align: center;
i {
font-size: 2.5rem;
color: #64748b;
margin-bottom: 0.75rem;
}
p {
color: #94a3b8;
font-size: 1rem;
margin: 0;
}
.hint {
font-size: 0.85rem;
color: #64748b;
margin-top: 0.25rem;
}
}
.results-header {
font-size: 0.9rem;
color: #94a3b8;
margin-bottom: 1rem;
font-weight: 600;
}
.results-list {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.result-card {
display: flex;
gap: 1rem;
padding: 1rem;
border-radius: 10px;
border: 1px solid color-mix(in srgb, var(--p-surface-500), transparent 60%);
background: color-mix(in srgb, var(--p-surface-900), transparent 30%);
transition: border-color 0.2s ease;
&:hover {
border-color: color-mix(in srgb, var(--p-primary-400), transparent 50%);
}
}
.result-image {
flex-shrink: 0;
width: 80px;
height: 100px;
border-radius: 8px;
overflow: hidden;
background: color-mix(in srgb, var(--p-surface-800), transparent 20%);
img {
width: 100%;
height: 100%;
object-fit: cover;
}
}
.result-placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
color: #64748b;
i {
font-size: 2rem;
}
}
.result-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.result-name {
font-size: 1rem;
font-weight: 700;
color: #e2e8f0;
margin: 0;
}
.result-asin {
font-size: 0.8rem;
color: #64748b;
font-family: monospace;
}
.result-description {
font-size: 0.85rem;
color: #94a3b8;
margin: 0.25rem 0 0;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.result-action {
flex-shrink: 0;
display: flex;
align-items: center;
}
@media (max-width: 767px) {
.search-fields {
flex-direction: column;
.search-input {
width: 100%;
}
.region-field,
.region-dropdown {
min-width: 100%;
}
}
.result-card {
flex-direction: column;
}
.result-image {
width: 60px;
height: 75px;
}
.result-action {
align-self: flex-end;
}
}
@@ -0,0 +1,119 @@
import {Component, EventEmitter, inject, Input, OnInit, Output} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {Select} from 'primeng/select';
import {ProgressSpinner} from 'primeng/progressspinner';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {MessageService} from 'primeng/api';
import {AuthorService} from '../../service/author.service';
import {AuthorDetails, AuthorMatchRequest, AuthorSearchResult} from '../../model/author.model';
interface RegionOption {
label: string;
value: string;
}
@Component({
selector: 'app-author-match',
standalone: true,
templateUrl: './author-match.component.html',
styleUrls: ['./author-match.component.scss'],
imports: [
FormsModule,
Button,
InputText,
Select,
ProgressSpinner,
TranslocoDirective
]
})
export class AuthorMatchComponent implements OnInit {
@Input({required: true}) authorId!: number;
@Input({required: true}) authorName!: string;
@Output() authorMatched = new EventEmitter<AuthorDetails>();
private authorService = inject(AuthorService);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
searchQuery = '';
selectedRegion = 'us';
searching = false;
matching = false;
results: AuthorSearchResult[] = [];
hasSearched = false;
regionOptions: RegionOption[] = [
{label: 'US', value: 'us'},
{label: 'UK', value: 'uk'},
{label: 'AU', value: 'au'},
{label: 'CA', value: 'ca'},
{label: 'IN', value: 'in'},
{label: 'FR', value: 'fr'},
{label: 'DE', value: 'de'},
{label: 'IT', value: 'it'},
{label: 'ES', value: 'es'},
{label: 'JP', value: 'jp'}
];
ngOnInit(): void {
this.searchQuery = this.authorName;
}
search(): void {
if (!this.searchQuery.trim()) return;
this.searching = true;
this.results = [];
this.hasSearched = true;
this.authorService.searchAuthorMetadata(this.authorId, this.searchQuery.trim(), this.selectedRegion)
.subscribe({
next: (results) => {
this.results = results;
this.searching = false;
},
error: () => {
this.searching = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.match.toast.searchFailedSummary'),
detail: this.t.translate('authorBrowser.match.toast.searchFailedDetail'),
life: 3000
});
}
});
}
matchAuthor(result: AuthorSearchResult): void {
this.matching = true;
const request: AuthorMatchRequest = {
source: result.source,
asin: result.asin,
region: this.selectedRegion
};
this.authorService.matchAuthor(this.authorId, request).subscribe({
next: (updatedAuthor) => {
this.matching = false;
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.match.toast.matchSuccessSummary'),
detail: this.t.translate('authorBrowser.match.toast.matchSuccessDetail'),
life: 3000
});
this.authorMatched.emit(updatedAuthor);
},
error: () => {
this.matching = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.match.toast.matchFailedSummary'),
detail: this.t.translate('authorBrowser.match.toast.matchFailedDetail'),
life: 3000
});
}
});
}
}
@@ -0,0 +1,101 @@
<ng-container *transloco="let t; prefix: 'authorBrowser.photoSearch'">
<div class="photo-search-container">
<div class="search-section">
<form [formGroup]="searchForm" (ngSubmit)="onSearch()">
<div class="form-row">
<div class="form-field">
<label for="photoQuery">
<i class="pi pi-user"></i>
{{ t('queryLabel') }}
</label>
<input
pInputText
id="photoQuery"
formControlName="query"
[placeholder]="t('queryPlaceholder')"/>
</div>
<div class="form-actions">
<p-button
type="submit"
[label]="t('searchBtn')"
icon="pi pi-search"
[loading]="searching"
[disabled]="searchForm.invalid">
</p-button>
<p-button
type="button"
icon="pi pi-refresh"
[text]="true"
[rounded]="true"
severity="secondary"
(click)="onClear()"
[pTooltip]="t('resetTooltip')"
tooltipPosition="top">
</p-button>
</div>
</div>
</form>
</div>
<div class="results-section">
@if (!hasSearched) {
<div class="empty-state">
<div class="empty-state-icon">
<i class="pi pi-images"></i>
</div>
<h3>{{ t('readyTitle') }}</h3>
<p>{{ t('readyHint') }}</p>
</div>
} @else if (searching) {
<div class="loading-state">
<p-progressSpinner strokeWidth="3" animationDuration="1s"></p-progressSpinner>
<p>{{ t('searching') }}</p>
</div>
} @else if (photos.length === 0) {
<div class="empty-state no-results">
<div class="empty-state-icon warning">
<i class="pi pi-search"></i>
</div>
<h3>{{ t('noResults') }}</h3>
<p>{{ t('noResultsHint') }}</p>
</div>
} @else {
<div class="results-header">
<span class="results-count">
<i class="pi pi-images"></i>
{{ t('resultsFound', { count: photos.length }) }}
</span>
</div>
<div class="photos-grid">
@for (photo of photos; track photo.url; let i = $index) {
<div class="photo-card">
<div class="photo-image-wrapper">
<p-image
[src]="photo.url"
[alt]="t('photoAlt', { index: i + 1 })"
appendTo="body"
[preview]="true">
</p-image>
@if (photo.width && photo.height) {
<div class="resolution-badge">
{{ photo.width }} x {{ photo.height }}
</div>
}
<div class="photo-overlay">
<p-button
(click)="selectAndUploadPhoto(photo)"
[label]="t('selectBtn')"
icon="pi pi-check"
size="small">
</p-button>
</div>
</div>
</div>
}
</div>
}
</div>
</div>
</ng-container>
@@ -0,0 +1,244 @@
:host {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.photo-search-container {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
padding: 0 1.5rem 1.5rem 1.5rem;
}
.search-section {
flex-shrink: 0;
background: var(--surface-ground);
border: 1px solid var(--surface-border);
border-radius: 12px;
padding: 1.25rem 1.5rem;
margin-bottom: 1.5rem;
.form-row {
display: flex;
align-items: flex-end;
gap: 1rem;
}
.form-field {
display: flex;
flex-direction: column;
gap: 0.5rem;
flex: 1;
label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text-color-secondary);
i {
font-size: 0.875rem;
color: var(--primary-color);
}
}
input {
width: 100%;
}
}
.form-actions {
display: flex;
align-items: center;
gap: 0.5rem;
padding-bottom: 1px;
}
}
.results-section {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
overflow-y: auto;
}
.empty-state,
.loading-state {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem;
text-align: center;
background: var(--surface-ground);
border: 1px dashed var(--surface-border);
border-radius: 12px;
h3 {
margin: 0 0 0.5rem;
font-size: 1.125rem;
font-weight: 600;
color: var(--text-color);
}
p {
margin: 0;
font-size: 0.9rem;
color: var(--text-color-secondary);
max-width: 300px;
}
}
.empty-state-icon {
width: 80px;
height: 80px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, var(--primary-100), var(--primary-50));
border-radius: 50%;
margin-bottom: 1.5rem;
i {
font-size: 2rem;
color: var(--primary-color);
}
&.warning {
background: linear-gradient(135deg, var(--yellow-100), var(--yellow-50));
i {
color: var(--yellow-600);
}
}
}
.loading-state {
p {
margin-top: 1rem;
}
}
.results-header {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
padding-bottom: 0.75rem;
border-bottom: 1px solid var(--surface-border);
.results-count {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.95rem;
font-weight: 600;
color: var(--text-color);
i {
color: var(--primary-color);
}
}
}
.photos-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 1.25rem;
padding: 0.25rem;
}
.photo-card {
.photo-image-wrapper {
position: relative;
width: 150px;
height: 200px;
border-radius: 8px;
overflow: hidden;
background: var(--surface-ground);
border: 2px solid transparent;
&:hover {
border-color: var(--primary-color);
.photo-overlay {
opacity: 1;
}
}
::ng-deep {
.p-image {
width: 100%;
height: 100%;
}
.p-image-preview {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
}
}
}
.resolution-badge {
position: absolute;
top: 6px;
right: 6px;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 3px 6px;
border-radius: 4px;
font-size: 0.7rem;
font-weight: 600;
z-index: 2;
pointer-events: none;
}
.photo-overlay {
position: absolute;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 0.5rem;
background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
opacity: 0;
z-index: 3;
}
}
@media (max-width: 768px) {
.search-section .form-row {
flex-direction: column;
align-items: stretch;
.form-actions {
flex-direction: row;
justify-content: flex-end;
margin-top: 0.5rem;
}
}
.photos-grid {
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 1rem;
}
}
@@ -0,0 +1,105 @@
import {Component, inject, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {ProgressSpinner} from 'primeng/progressspinner';
import {Image} from 'primeng/image';
import {Tooltip} from 'primeng/tooltip';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {MessageService} from 'primeng/api';
import {finalize} from 'rxjs/operators';
import {AuthorService} from '../../service/author.service';
import {AuthorPhotoResult} from '../../model/author.model';
@Component({
selector: 'app-author-photo-search',
templateUrl: './author-photo-search.component.html',
styleUrls: ['./author-photo-search.component.scss'],
imports: [
ReactiveFormsModule,
Button,
InputText,
ProgressSpinner,
Image,
Tooltip,
TranslocoDirective
]
})
export class AuthorPhotoSearchComponent implements OnInit {
searchForm: FormGroup;
photos: AuthorPhotoResult[] = [];
searching = false;
hasSearched = false;
private fb = inject(FormBuilder);
private authorService = inject(AuthorService);
private dynamicDialogConfig = inject(DynamicDialogConfig);
protected dynamicDialogRef = inject(DynamicDialogRef);
private messageService = inject(MessageService);
private t = inject(TranslocoService);
private authorId!: number;
constructor() {
this.searchForm = this.fb.group({
query: ['', Validators.required]
});
}
ngOnInit(): void {
this.authorId = this.dynamicDialogConfig.data.authorId;
const authorName = this.dynamicDialogConfig.data.authorName;
if (authorName) {
this.searchForm.patchValue({query: authorName});
if (this.searchForm.valid) {
this.onSearch();
}
}
}
onSearch(): void {
if (!this.searchForm.valid) return;
this.searching = true;
this.authorService.searchAuthorPhotos(this.authorId, this.searchForm.value.query)
.pipe(finalize(() => this.searching = false))
.subscribe({
next: (photos) => {
this.photos = photos.sort((a, b) => a.index - b.index);
this.hasSearched = true;
},
error: () => {
this.photos = [];
this.hasSearched = true;
}
});
}
selectAndUploadPhoto(photo: AuthorPhotoResult): void {
this.authorService.uploadAuthorPhotoFromUrl(this.authorId, photo.url).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('authorBrowser.editor.toast.photoUploadedSummary'),
detail: this.t.translate('authorBrowser.editor.toast.photoUploadedDetail')
});
this.dynamicDialogRef.close(true);
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('authorBrowser.editor.toast.errorSummary'),
detail: this.t.translate('authorBrowser.editor.toast.photoUploadErrorDetail')
});
}
});
}
onClear(): void {
this.searchForm.reset();
this.photos = [];
this.hasSearched = false;
}
}
@@ -0,0 +1,80 @@
export interface AuthorSummary {
id: number;
name: string;
asin?: string;
bookCount: number;
hasPhoto: boolean;
}
export interface EnrichedAuthor extends AuthorSummary {
libraryIds: Set<number>;
libraryNames: string[];
categories: string[];
readStatus: 'all-read' | 'some-read' | 'in-progress' | 'unread';
hasSeries: boolean;
seriesCount: number;
latestAddedOn: string | null;
lastReadTime: string | null;
readingProgress: number;
avgPersonalRating: number | null;
}
export interface AuthorFilters {
matchStatus: 'all' | 'matched' | 'unmatched';
photoStatus: 'all' | 'has-photo' | 'no-photo';
readStatus: 'all' | 'all-read' | 'some-read' | 'in-progress' | 'unread';
bookCount: 'all' | '0' | '1' | '2' | '3' | '4' | '5' | '6-10' | '11-20' | '21-35' | '36+';
library: string;
genre: string;
}
export const DEFAULT_AUTHOR_FILTERS: AuthorFilters = {
matchStatus: 'all',
photoStatus: 'all',
readStatus: 'all',
bookCount: 'all',
library: 'all',
genre: 'all'
};
export interface AuthorDetails {
id: number;
name: string;
description?: string;
asin?: string;
nameLocked: boolean;
descriptionLocked: boolean;
asinLocked: boolean;
photoLocked: boolean;
}
export interface AuthorSearchResult {
source: string;
asin: string;
name: string;
description?: string;
imageUrl?: string;
}
export interface AuthorMatchRequest {
source: string;
asin: string;
region: string;
}
export interface AuthorPhotoResult {
url: string;
width: number;
height: number;
index: number;
}
export interface AuthorUpdateRequest {
name?: string;
description?: string;
asin?: string;
nameLocked?: boolean;
descriptionLocked?: boolean;
asinLocked?: boolean;
photoLocked?: boolean;
}
@@ -0,0 +1,43 @@
import {inject, Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {LocalStorageService} from '../../../shared/service/local-storage.service';
@Injectable({
providedIn: 'root'
})
export class AuthorScalePreferenceService {
private readonly DEBOUNCE_MS = 1000;
private readonly STORAGE_KEY = 'authorScalePreference';
private readonly localStorageService = inject(LocalStorageService);
private readonly scaleChangeSubject = new Subject<number>();
scaleFactor = 1.0;
constructor() {
this.loadScaleFromStorage();
this.scaleChangeSubject
.pipe(debounceTime(this.DEBOUNCE_MS))
.subscribe(scale => this.saveScalePreference(scale));
}
setScale(scale: number): void {
this.scaleFactor = scale;
this.scaleChangeSubject.next(scale);
}
private saveScalePreference(scale: number): void {
this.localStorageService.set(this.STORAGE_KEY, scale);
}
private loadScaleFromStorage(): void {
const saved = this.localStorageService.get<number>(this.STORAGE_KEY);
if (saved !== null && !isNaN(saved)) {
this.scaleFactor = saved;
}
}
}
@@ -0,0 +1,85 @@
import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {AuthorSummary} from '../model/author.model';
export interface AuthorCheckboxClickEvent {
index: number;
author: AuthorSummary;
selected: boolean;
shiftKey: boolean;
}
@Injectable({providedIn: 'root'})
export class AuthorSelectionService {
private selectedAuthorsSubject = new BehaviorSubject<Set<number>>(new Set());
private currentAuthors: AuthorSummary[] = [];
private lastSelectedIndex: number | null = null;
selectedAuthors$: Observable<Set<number>> = this.selectedAuthorsSubject.asObservable();
get selectedAuthors(): Set<number> {
return this.selectedAuthorsSubject.value;
}
get selectedCount(): number {
return this.selectedAuthorsSubject.value.size;
}
setCurrentAuthors(authors: AuthorSummary[]): void {
this.currentAuthors = authors;
}
handleCheckboxClick(event: AuthorCheckboxClickEvent): void {
const {index, author, selected, shiftKey} = event;
if (!shiftKey || this.lastSelectedIndex === null) {
if (selected) {
this.select(author.id);
} else {
this.deselect(author.id);
}
this.lastSelectedIndex = index;
} else {
const start = Math.min(this.lastSelectedIndex, index);
const end = Math.max(this.lastSelectedIndex, index);
for (let i = start; i <= end; i++) {
const a = this.currentAuthors[i];
if (!a) continue;
if (selected) {
this.select(a.id);
} else {
this.deselect(a.id);
}
}
}
}
selectAll(): void {
const current = new Set(this.selectedAuthorsSubject.value);
for (const author of this.currentAuthors) {
current.add(author.id);
}
this.selectedAuthorsSubject.next(current);
}
deselectAll(): void {
this.selectedAuthorsSubject.next(new Set());
this.lastSelectedIndex = null;
}
getSelectedIds(): number[] {
return Array.from(this.selectedAuthorsSubject.value);
}
private select(id: number): void {
const current = new Set(this.selectedAuthorsSubject.value);
current.add(id);
this.selectedAuthorsSubject.next(current);
}
private deselect(id: number): void {
const current = new Set(this.selectedAuthorsSubject.value);
current.delete(id);
this.selectedAuthorsSubject.next(current);
}
}
@@ -0,0 +1,123 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {SseClient} from 'ngx-sse-client';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthorSummary, AuthorDetails, AuthorSearchResult, AuthorMatchRequest, AuthorUpdateRequest, AuthorPhotoResult} from '../model/author.model';
import {AuthService} from '../../../shared/service/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthorService {
private http = inject(HttpClient);
private authService = inject(AuthService);
private sseClient = inject(SseClient);
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/authors`;
private readonly mediaBaseUrl = `${API_CONFIG.BASE_URL}/api/v1/media`;
private allAuthorsSubject = new BehaviorSubject<AuthorSummary[] | null>(null);
allAuthors$ = this.allAuthorsSubject.asObservable();
getAllAuthors(): Observable<AuthorSummary[]> {
return this.http.get<AuthorSummary[]>(this.baseUrl).pipe(
tap(authors => this.allAuthorsSubject.next(authors))
);
}
getAuthorDetails(authorId: number): Observable<AuthorDetails> {
return this.http.get<AuthorDetails>(`${this.baseUrl}/${authorId}`);
}
getAuthorByName(name: string): Observable<AuthorDetails> {
return this.http.get<AuthorDetails>(`${this.baseUrl}/by-name`, {params: {name}});
}
searchAuthorMetadata(authorId: number, query: string, region: string): Observable<AuthorSearchResult[]> {
return this.http.get<AuthorSearchResult[]>(`${this.baseUrl}/${authorId}/search-metadata`, {
params: {q: query, region}
});
}
matchAuthor(authorId: number, request: AuthorMatchRequest): Observable<AuthorDetails> {
return this.http.post<AuthorDetails>(`${this.baseUrl}/${authorId}/match`, request);
}
quickMatchAuthor(authorId: number, region: string = 'us'): Observable<AuthorDetails> {
return this.http.post<AuthorDetails>(`${this.baseUrl}/${authorId}/quick-match`, null, {
params: {region}
});
}
autoMatchAuthors(authorIds: number[]): Observable<AuthorSummary> {
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
const headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', `Bearer ${token}`);
return this.sseClient.stream(
`${this.baseUrl}/auto-match`,
{keepAlive: false, reconnectionDelay: 1000, responseType: 'event'},
{headers, body: authorIds, withCredentials: true},
'POST'
).pipe(
map(event => {
if (event.type === 'error') {
throw new Error((event as ErrorEvent).message);
}
return JSON.parse((event as MessageEvent).data) as AuthorSummary;
})
);
}
updateAuthor(authorId: number, request: AuthorUpdateRequest): Observable<AuthorDetails> {
return this.http.put<AuthorDetails>(`${this.baseUrl}/${authorId}`, request);
}
unmatchAuthors(authorIds: number[]): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/unmatch`, authorIds);
}
deleteAuthors(authorIds: number[]): Observable<void> {
return this.http.delete<void>(this.baseUrl, {body: authorIds});
}
searchAuthorPhotos(authorId: number, query: string): Observable<AuthorPhotoResult[]> {
return this.http.get<AuthorPhotoResult[]>(`${this.baseUrl}/${authorId}/search-photos`, {
params: {q: query}
});
}
uploadAuthorPhotoFromUrl(authorId: number, imageUrl: string): Observable<void> {
return this.http.post<void>(`${this.baseUrl}/${authorId}/photo/url`, null, {
params: {url: imageUrl}
});
}
getUploadAuthorPhotoUrl(authorId: number): string {
return `${this.baseUrl}/${authorId}/photo/upload`;
}
getAuthorPhotoUrl(authorId: number): string {
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
let url = `${this.mediaBaseUrl}/author/${authorId}/photo`;
if (token) {
url += `?token=${token}`;
}
return url;
}
getAuthorThumbnailUrl(authorId: number, cacheBuster?: number): string {
const token = this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
let url = `${this.mediaBaseUrl}/author/${authorId}/thumbnail`;
if (token) {
url += `?token=${token}`;
}
if (cacheBuster) {
url += (token ? '&' : '?') + 't=' + cacheBuster;
}
return url;
}
}
@@ -35,6 +35,7 @@ import {BookMetadataHostService} from '../../../../../shared/service/book-metada
import {AppSettingsService} from '../../../../../shared/service/app-settings.service';
import {DeleteBookFileEvent, DeleteSupplementaryFileEvent, DownloadAdditionalFileEvent, DownloadAllFilesEvent, DownloadEvent, MetadataTabsComponent, ReadEvent} from './metadata-tabs/metadata-tabs.component';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {AuthorService} from '../../../../author-browser/service/author.service';
@Component({
@@ -57,6 +58,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
private taskHelperService = inject(TaskHelperService);
private authorService = inject(AuthorService);
protected urlHelper = inject(UrlHelperService);
protected userService = inject(UserService);
private confirmationService = inject(ConfirmationService);
@@ -740,7 +742,20 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
}
goToAuthorBooks(author: string): void {
this.handleMetadataClick('author', author);
this.authorService.getAuthorByName(author).subscribe({
next: (authorDetails) => {
const navigate = () => this.router.navigate(['/author', authorDetails.id]);
if (this.metadataCenterViewMode === 'dialog') {
this.dialogRef?.close();
setTimeout(navigate, 200);
} else {
navigate();
}
},
error: () => {
this.handleMetadataClick('author', author);
}
});
}
goToCategory(category: string): void {
@@ -13,6 +13,7 @@ import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {UserService} from '../../../../features/settings/user-management/user.service';
import {MagicShelfService, MagicShelfState} from '../../../../features/magic-shelf/service/magic-shelf.service';
import {SeriesDataService} from '../../../../features/series-browser/service/series-data.service';
import {AuthorService} from '../../../../features/author-browser/service/author.service';
import {MenuItem} from 'primeng/api';
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@@ -46,6 +47,7 @@ export class AppMenuComponent implements OnInit {
private userService = inject(UserService);
private magicShelfService = inject(MagicShelfService);
private seriesDataService = inject(SeriesDataService);
private authorService = inject(AuthorService);
private t = inject(TranslocoService);
private localStorageService = inject(LocalStorageService);
@@ -65,6 +67,8 @@ export class AppMenuComponent implements OnInit {
this.versionInfo = data;
});
this.authorService.getAllAuthors().subscribe();
this.userService.userState$.pipe(
filter(userState => !!userState?.user && userState.loaded))
.subscribe(userState => {
@@ -107,6 +111,13 @@ export class AppMenuComponent implements OnInit {
routerLink: ['/series'],
bookCount$: this.seriesDataService.allSeries$.pipe(map(series => series.length)),
},
{
label: this.t.translate('layout.menu.authors'),
type: 'Authors',
icon: 'pi pi-fw pi-users',
routerLink: ['/authors'],
bookCount$: this.authorService.allAuthors$.pipe(map(authors => authors?.length ?? 0)),
},
{
label: this.t.translate('layout.menu.notebook'),
icon: 'pi pi-fw pi-pencil',
@@ -83,9 +83,9 @@
<p-menu #entitymenu [model]="item.menu" [popup]="true" appendTo="body"></p-menu>
}
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.type === 'Series' || item.label === 'Unshelved' || item.label === 'Kobo') {
@if (item.type === 'Library' && (!admin && !canManipulateLibrary) || item.type === 'All Books' || item.type === 'Series' || item.type === 'Authors' || item.label === 'Unshelved' || item.label === 'Kobo') {
<p class="book-count">
{{ (item.bookCount$ | async)?.toString() || '0' }}
{{ formatCount(item.bookCount$ | async) }}
</p>
}
</span>
@@ -177,6 +177,12 @@ export class AppMenuitemComponent implements OnInit, OnDestroy {
}
}
formatCount(count: number | null | undefined): string {
if (count == null) return '0';
if (count >= 1000) return Math.floor(count / 1000) + 'K';
return count.toString();
}
getIconSelection(): IconSelection | null {
if (!this.item.icon) return null;
+140
View File
@@ -0,0 +1,140 @@
{
"pageTitle": "Authors",
"browseAllAuthors": "Browse All Authors",
"searchPlaceholder": "Search by author name...",
"noAuthorsFound": "No authors match your search.",
"cardSize": "Card Size",
"sort": {
"name": "Name",
"bookCount": "Book Count",
"matched": "Matched",
"recentlyAdded": "Recently Added",
"recentlyRead": "Recently Read",
"readingProgress": "Reading Progress",
"avgRating": "Avg Rating",
"photo": "Photo",
"seriesCount": "Series Count"
},
"filters": {
"all": "All",
"matchStatus": "Match Status",
"matched": "Matched",
"unmatched": "Unmatched",
"photoStatus": "Photo Status",
"hasPhoto": "Has Photo",
"noPhoto": "No Photo",
"readStatus": "Read Status",
"allRead": "All Read",
"someRead": "Some Read",
"inProgress": "In Progress",
"unread": "Unread",
"bookCount": "Book Count",
"library": "Library",
"genre": "Genre",
"reset": "Reset Filters"
},
"footer": {
"selected": "selected",
"autoMatch": "Auto-match selected",
"deleteSelected": "Delete selected",
"selectAll": "Select all",
"deselectAll": "Deselect all"
},
"toast": {
"deleteSuccessSummary": "Author Deleted",
"deleteSuccessDetail": "Author has been deleted successfully.",
"deleteFailedSummary": "Delete Failed",
"deleteFailedDetail": "Failed to delete author.",
"autoMatchSuccessSummary": "Auto-Match Complete",
"autoMatchSuccessDetail": "Selected authors have been matched successfully.",
"autoMatchFailedSummary": "Auto-Match Failed",
"autoMatchFailedDetail": "Failed to auto-match selected authors.",
"quickMatchSuccessSummary": "Quick Match Complete",
"quickMatchSuccessDetail": "Author has been matched successfully.",
"quickMatchFailedSummary": "Quick Match Failed",
"quickMatchFailedDetail": "Failed to quick-match the author.",
"deleteSelectedSuccessSummary": "Authors Deleted",
"deleteSelectedSuccessDetail": "Selected authors have been deleted successfully."
},
"card": {
"matched": "Matched",
"quickMatch": "Quick Match",
"book": "book",
"books": "books",
"menu": {
"viewAuthor": "View Author",
"editAuthor": "Edit Author",
"quickMatch": "Quick Match",
"deleteAuthor": "Delete Author"
}
},
"editor": {
"nameLabel": "Name",
"asinLabel": "ASIN",
"descriptionLabel": "Description",
"saveBtn": "Save",
"saving": "Saving...",
"uploadPhotoTooltip": "Upload photo",
"lockField": "Lock field",
"unlockField": "Unlock field",
"lockAllBtn": "Lock All",
"unlockAllBtn": "Unlock All",
"searchPhotoTooltip": "Search photo",
"searchPhotoTitle": "Search Author Photo",
"toast": {
"successSummary": "Author Updated",
"successDetail": "Author details have been updated successfully.",
"errorSummary": "Update Failed",
"errorDetail": "Failed to update author details.",
"photoUploadedSummary": "Photo Uploaded",
"photoUploadedDetail": "Author photo has been uploaded successfully.",
"photoUploadErrorDetail": "Failed to upload author photo."
}
},
"detail": {
"quickMatchTooltip": "Quick Match",
"loading": "Loading author details...",
"booksTab": "Author Details",
"editTab": "Edit Details",
"matchTab": "Search Author",
"showMore": "Show more",
"showLess": "Show less",
"booksBy": "Books by {{ name }}",
"noBooksFound": "No books found for this author."
},
"photoSearch": {
"queryLabel": "Author Name",
"queryPlaceholder": "Enter author name to search photos",
"searchBtn": "Search",
"resetTooltip": "Reset search",
"readyTitle": "Search for Photos",
"readyHint": "Enter the author name and click Search to find photos",
"searching": "Searching for photos...",
"noResults": "No Photos Found",
"noResultsHint": "Try adjusting your search term",
"resultsFound": "{{ count }} photos found",
"selectBtn": "Select",
"photoAlt": "Author photo {{ index }}"
},
"match": {
"authorNameLabel": "Author Name",
"authorNamePlaceholder": "Enter author name to search",
"regionLabel": "Region",
"searchBtn": "Search",
"searching": "Searching...",
"noResults": "No Results Found",
"noResultsHint": "Try adjusting your search term or selecting a different region",
"readyToSearch": "Ready to Search",
"readyToSearchHint": "Enter the author name and click Search to find metadata",
"resultsFound": "{{ count }} results found",
"matchBtn": "Match",
"toast": {
"searchFailedSummary": "Search Failed",
"searchFailedDetail": "Failed to search for author metadata.",
"matchSuccessSummary": "Author Matched",
"matchSuccessDetail": "Author metadata has been updated successfully.",
"matchFailedSummary": "Match Failed",
"matchFailedDetail": "Failed to match author with external metadata."
}
}
}
+2 -1
View File
@@ -34,8 +34,9 @@ import statsLibrary from './stats-library.json';
import statsUser from './stats-user.json';
import magicShelf from './magic-shelf.json';
import seriesBrowser from './series-browser.json';
import authorBrowser from './author-browser.json';
// To add a new domain: create the JSON file and add it here.
// Settings tabs each get their own file: settings-email, settings-reader, settings-view, etc.
const translations: Translation = {common, auth, nav, dashboard, settings, settingsEmail, settingsReader, settingsView, settingsMeta, settingsLibMeta, settingsApp, settingsUsers, settingsNaming, settingsOpds, settingsTasks, settingsAuditLogs, settingsAuth, settingsDevice, settingsProfile, app, shared, layout, libraryCreator, bookdrop, metadata, notebook, book, readerAudiobook, readerCbx, readerEbook, readerPdf, statsLibrary, statsUser, magicShelf, seriesBrowser};
const translations: Translation = {common, auth, nav, dashboard, settings, settingsEmail, settingsReader, settingsView, settingsMeta, settingsLibMeta, settingsApp, settingsUsers, settingsNaming, settingsOpds, settingsTasks, settingsAuditLogs, settingsAuth, settingsDevice, settingsProfile, app, shared, layout, libraryCreator, bookdrop, metadata, notebook, book, readerAudiobook, readerCbx, readerEbook, readerPdf, statsLibrary, statsUser, magicShelf, seriesBrowser, authorBrowser};
export default translations;
+1
View File
@@ -26,6 +26,7 @@
"magicShelves": "Magic Shelves",
"unshelved": "Unshelved",
"series": "Series",
"authors": "Authors",
"notebook": "Notebook",
"update": "(Update)"
},
+140
View File
@@ -0,0 +1,140 @@
{
"pageTitle": "Autores",
"browseAllAuthors": "Explorar todos los autores",
"searchPlaceholder": "Buscar por nombre de autor...",
"noAuthorsFound": "Ningún autor coincide con tu búsqueda.",
"cardSize": "Tamaño de tarjeta",
"sort": {
"name": "Nombre",
"bookCount": "Cantidad de libros",
"matched": "Coincidencia",
"recentlyAdded": "Agregados recientemente",
"recentlyRead": "Leídos recientemente",
"readingProgress": "Progreso de lectura",
"avgRating": "Calificación promedio",
"photo": "Foto",
"seriesCount": "Cantidad de series"
},
"filters": {
"all": "Todos",
"matchStatus": "Estado de coincidencia",
"matched": "Coincidentes",
"unmatched": "Sin coincidencia",
"photoStatus": "Estado de foto",
"hasPhoto": "Con foto",
"noPhoto": "Sin foto",
"readStatus": "Estado de lectura",
"allRead": "Todos leídos",
"someRead": "Algunos leídos",
"inProgress": "En progreso",
"unread": "Sin leer",
"bookCount": "Cantidad de libros",
"library": "Biblioteca",
"genre": "Género",
"reset": "Restablecer filtros"
},
"footer": {
"selected": "seleccionados",
"autoMatch": "Auto-coincidir seleccionados",
"deleteSelected": "Eliminar seleccionados",
"selectAll": "Seleccionar todos",
"deselectAll": "Deseleccionar todos"
},
"toast": {
"deleteSuccessSummary": "Autor eliminado",
"deleteSuccessDetail": "El autor se ha eliminado correctamente.",
"deleteFailedSummary": "Error al eliminar",
"deleteFailedDetail": "Error al eliminar el autor.",
"autoMatchSuccessSummary": "Auto-coincidencia completa",
"autoMatchSuccessDetail": "Los autores seleccionados se han asociado correctamente.",
"autoMatchFailedSummary": "Error de auto-coincidencia",
"autoMatchFailedDetail": "Error al asociar automáticamente los autores seleccionados.",
"quickMatchSuccessSummary": "Coincidencia rápida completa",
"quickMatchSuccessDetail": "El autor se ha asociado correctamente.",
"quickMatchFailedSummary": "Error de coincidencia rápida",
"quickMatchFailedDetail": "Error al realizar la coincidencia rápida del autor.",
"deleteSelectedSuccessSummary": "Autores eliminados",
"deleteSelectedSuccessDetail": "Los autores seleccionados se han eliminado correctamente."
},
"card": {
"matched": "Coincidencia",
"quickMatch": "Coincidencia rápida",
"book": "libro",
"books": "libros",
"menu": {
"viewAuthor": "Ver autor",
"editAuthor": "Editar autor",
"quickMatch": "Coincidencia rápida",
"deleteAuthor": "Eliminar autor"
}
},
"editor": {
"nameLabel": "Nombre",
"asinLabel": "ASIN",
"descriptionLabel": "Descripción",
"saveBtn": "Guardar",
"saving": "Guardando...",
"uploadPhotoTooltip": "Subir foto",
"lockField": "Bloquear campo",
"unlockField": "Desbloquear campo",
"lockAllBtn": "Bloquear todo",
"unlockAllBtn": "Desbloquear todo",
"searchPhotoTooltip": "Buscar foto",
"searchPhotoTitle": "Buscar foto del autor",
"toast": {
"successSummary": "Autor actualizado",
"successDetail": "Los detalles del autor se han actualizado correctamente.",
"errorSummary": "Error al actualizar",
"errorDetail": "Error al actualizar los detalles del autor.",
"photoUploadedSummary": "Foto subida",
"photoUploadedDetail": "La foto del autor se ha subido correctamente.",
"photoUploadErrorDetail": "Error al subir la foto del autor."
}
},
"detail": {
"quickMatchTooltip": "Coincidencia rápida",
"loading": "Cargando detalles del autor...",
"booksTab": "Detalles del autor",
"editTab": "Editar detalles",
"matchTab": "Buscar autor",
"showMore": "Mostrar más",
"showLess": "Mostrar menos",
"booksBy": "Libros de {{ name }}",
"noBooksFound": "No se encontraron libros de este autor."
},
"photoSearch": {
"queryLabel": "Nombre del autor",
"queryPlaceholder": "Ingrese el nombre del autor para buscar fotos",
"searchBtn": "Buscar",
"resetTooltip": "Restablecer búsqueda",
"readyTitle": "Buscar fotos",
"readyHint": "Ingrese el nombre del autor y haga clic en Buscar para encontrar fotos",
"searching": "Buscando fotos...",
"noResults": "No se encontraron fotos",
"noResultsHint": "Intente ajustar el término de búsqueda",
"resultsFound": "{{ count }} fotos encontradas",
"selectBtn": "Seleccionar",
"photoAlt": "Foto del autor {{ index }}"
},
"match": {
"authorNameLabel": "Nombre del autor",
"authorNamePlaceholder": "Ingrese el nombre del autor para buscar",
"regionLabel": "Región",
"searchBtn": "Buscar",
"searching": "Buscando...",
"noResults": "Sin resultados",
"noResultsHint": "Intente ajustar el término de búsqueda o seleccionar una región diferente",
"readyToSearch": "Listo para buscar",
"readyToSearchHint": "Ingrese el nombre del autor y haga clic en Buscar para encontrar metadatos",
"resultsFound": "{{ count }} resultados encontrados",
"matchBtn": "Coincidir",
"toast": {
"searchFailedSummary": "Error de búsqueda",
"searchFailedDetail": "Error al buscar metadatos del autor.",
"matchSuccessSummary": "Autor coincidente",
"matchSuccessDetail": "Los metadatos del autor se han actualizado correctamente.",
"matchFailedSummary": "Error de coincidencia",
"matchFailedDetail": "Error al asociar el autor con metadatos externos."
}
}
}
+2 -1
View File
@@ -34,8 +34,9 @@ import statsLibrary from './stats-library.json';
import statsUser from './stats-user.json';
import magicShelf from './magic-shelf.json';
import seriesBrowser from './series-browser.json';
import authorBrowser from './author-browser.json';
// To add a new domain: create the JSON file and add it here.
// Settings tabs each get their own file: settings-email, settings-reader, settings-view, etc.
const translations: Translation = {common, auth, nav, dashboard, settings, settingsEmail, settingsReader, settingsView, settingsMeta, settingsLibMeta, settingsApp, settingsUsers, settingsNaming, settingsOpds, settingsTasks, settingsAuditLogs, settingsAuth, settingsDevice, settingsProfile, app, shared, layout, libraryCreator, bookdrop, metadata, notebook, book, readerAudiobook, readerCbx, readerEbook, readerPdf, statsLibrary, statsUser, magicShelf, seriesBrowser};
const translations: Translation = {common, auth, nav, dashboard, settings, settingsEmail, settingsReader, settingsView, settingsMeta, settingsLibMeta, settingsApp, settingsUsers, settingsNaming, settingsOpds, settingsTasks, settingsAuditLogs, settingsAuth, settingsDevice, settingsProfile, app, shared, layout, libraryCreator, bookdrop, metadata, notebook, book, readerAudiobook, readerCbx, readerEbook, readerPdf, statsLibrary, statsUser, magicShelf, seriesBrowser, authorBrowser};
export default translations;
+1
View File
@@ -26,6 +26,7 @@
"magicShelves": "Estantes mágicos",
"unshelved": "Sin estante",
"series": "Series",
"authors": "Autores",
"notebook": "Cuaderno",
"update": "(Actualizar)"
},