diff --git a/booklore-api/src/main/java/org/booklore/config/AuthorParserConfig.java b/booklore-api/src/main/java/org/booklore/config/AuthorParserConfig.java new file mode 100644 index 000000000..e159540c2 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/config/AuthorParserConfig.java @@ -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 authorParserMap(AudnexusAuthorParser audnexusAuthorParser) { + return Map.of( + AuthorMetadataSource.AUDNEXUS, audnexusAuthorParser + ); + } +} diff --git a/booklore-api/src/main/java/org/booklore/controller/AuthorController.java b/booklore-api/src/main/java/org/booklore/controller/AuthorController.java index a9331b71e..34393b00b 100644 --- a/booklore-api/src/main/java/org/booklore/controller/AuthorController.java +++ b/booklore-api/src/main/java/org/booklore/controller/AuthorController.java @@ -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> 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 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 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 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 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> 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 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 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 autoMatchAuthors(@RequestBody List 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 unmatchAuthors(@RequestBody List 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> 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 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 deleteAuthors(@RequestBody List authorIds) { + authorMetadataService.deleteAuthors(authorIds); + return ResponseEntity.ok().build(); + } } diff --git a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java index 84438d88a..22bc8e94b 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java @@ -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 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 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") diff --git a/booklore-api/src/main/java/org/booklore/exception/ApiError.java b/booklore-api/src/main/java/org/booklore/exception/ApiError.java index 89987903c..8ede210fa 100644 --- a/booklore-api/src/main/java/org/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/org/booklore/exception/ApiError.java @@ -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; diff --git a/booklore-api/src/main/java/org/booklore/model/dto/AuthorDetails.java b/booklore-api/src/main/java/org/booklore/model/dto/AuthorDetails.java new file mode 100644 index 000000000..ee1a1623c --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/AuthorDetails.java @@ -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; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/AuthorSearchResult.java b/booklore-api/src/main/java/org/booklore/model/dto/AuthorSearchResult.java new file mode 100644 index 000000000..40cc0a0fb --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/AuthorSearchResult.java @@ -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; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/AuthorSummary.java b/booklore-api/src/main/java/org/booklore/model/dto/AuthorSummary.java new file mode 100644 index 000000000..8af99b541 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/AuthorSummary.java @@ -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; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorMatchRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorMatchRequest.java new file mode 100644 index 000000000..e01cd9428 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorMatchRequest.java @@ -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"; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorUpdateRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorUpdateRequest.java new file mode 100644 index 000000000..4090cbc1d --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/AuthorUpdateRequest.java @@ -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; +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/response/audnexus/AudnexusAuthorResponse.java b/booklore-api/src/main/java/org/booklore/model/dto/response/audnexus/AudnexusAuthorResponse.java new file mode 100644 index 000000000..e75cb202a --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/response/audnexus/AudnexusAuthorResponse.java @@ -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 genres; + private List 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; + } +} diff --git a/booklore-api/src/main/java/org/booklore/model/entity/AuthorEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/AuthorEntity.java index b29bad3d8..247095699 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/AuthorEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/AuthorEntity.java @@ -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 bookMetadataEntityList; diff --git a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java index 791dc5173..7c07a636d 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/AuditAction.java @@ -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 } diff --git a/booklore-api/src/main/java/org/booklore/model/enums/AuthorMetadataSource.java b/booklore-api/src/main/java/org/booklore/model/enums/AuthorMetadataSource.java new file mode 100644 index 000000000..bfdd9d7e7 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/enums/AuthorMetadataSource.java @@ -0,0 +1,5 @@ +package org.booklore.model.enums; + +public enum AuthorMetadataSource { + AUDNEXUS +} diff --git a/booklore-api/src/main/java/org/booklore/repository/AuthorRepository.java b/booklore-api/src/main/java/org/booklore/repository/AuthorRepository.java index f1516fdff..cedc9c5b4 100644 --- a/booklore-api/src/main/java/org/booklore/repository/AuthorRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/AuthorRepository.java @@ -18,5 +18,9 @@ public interface AuthorRepository extends JpaRepository { @Query("SELECT a FROM AuthorEntity a JOIN a.bookMetadataEntityList bm WHERE bm.bookId = :bookId") List findAuthorsByBookId(@Param("bookId") Long bookId); -} + Optional findByAsin(String asin); + + @Query("SELECT a, COUNT(bm) FROM AuthorEntity a LEFT JOIN a.bookMetadataEntityList bm GROUP BY a ORDER BY a.name") + List findAllWithBookCount(); +} diff --git a/booklore-api/src/main/java/org/booklore/service/AuthorMetadataService.java b/booklore-api/src/main/java/org/booklore/service/AuthorMetadataService.java new file mode 100644 index 000000000..56b159b40 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/AuthorMetadataService.java @@ -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 authorParserMap; + private final AuditService auditService; + private final FileService fileService; + private final DuckDuckGoCoverService duckDuckGoCoverService; + + public List getAllAuthors() { + List results = authorRepository.findAllWithBookCount(); + List 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 searchAuthorMetadata(String name, String region) { + return authorParserMap.values().stream() + .flatMap(provider -> { + List 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 autoMatchAuthors(List 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 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 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 searchAuthorPhotos(String name) { + String searchTerm = name + " author photo portrait"; + List 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(); + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java b/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java index bd4b6960f..c9ffeaf51 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java @@ -136,6 +136,32 @@ public class DuckDuckGoCoverService implements BookCoverProvider { return allImages; } + public List 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 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 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 fetchImagesFromApi(String query, String searchToken, Map cookies, String referrerUrl, String jsonParams) { List priority = new ArrayList<>(); List others = new ArrayList<>(); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudnexusAuthorParser.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudnexusAuthorParser.java new file mode 100644 index 000000000..b4388192f --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudnexusAuthorParser.java @@ -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 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 response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + if (response.statusCode() == 200) { + AudnexusAuthorResponse[] authors = objectMapper.readValue(response.body(), AudnexusAuthorResponse[].class); + LinkedHashMap uniqueByAsin = new LinkedHashMap<>(); + for (AudnexusAuthorResponse author : authors) { + uniqueByAsin.putIfAbsent(author.getAsin(), author); + } + List 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 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 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()); + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/AuthorParser.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AuthorParser.java new file mode 100644 index 000000000..fd44a4ea9 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AuthorParser.java @@ -0,0 +1,14 @@ +package org.booklore.service.metadata.parser; + +import org.booklore.model.dto.AuthorSearchResult; + +import java.util.List; + +public interface AuthorParser { + + List searchAuthors(String name, String region); + + AuthorSearchResult getAuthorByAsin(String asin, String region); + + AuthorSearchResult quickSearch(String name, String region); +} diff --git a/booklore-api/src/main/java/org/booklore/util/FileService.java b/booklore-api/src/main/java/org/booklore/util/FileService.java index cd5c35013..844962001 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileService.java +++ b/booklore-api/src/main/java/org/booklore/util/FileService.java @@ -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 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 // ======================================== diff --git a/booklore-api/src/main/resources/db/migration/V124__Add_author_metadata_columns.sql b/booklore-api/src/main/resources/db/migration/V124__Add_author_metadata_columns.sql new file mode 100644 index 000000000..4c0178c2e --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V124__Add_author_metadata_columns.sql @@ -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); diff --git a/booklore-api/src/test/java/org/booklore/service/AuthorMetadataServiceTest.java b/booklore-api/src/test/java/org/booklore/service/AuthorMetadataServiceTest.java new file mode 100644 index 000000000..0942118f8 --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/AuthorMetadataServiceTest.java @@ -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 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 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 results = service.searchAuthorMetadata("Unknown", "us"); + + assertThat(results).isEmpty(); + } + + @Test + void searchAuthorMetadata_returnsEmptyListWhenEmpty() { + when(authorParser.searchAuthors("Nobody", "us")).thenReturn(Collections.emptyList()); + + List 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()); + } +} diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java index 5ac87bae0..058919ba3 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java @@ -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); diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/parser/AudnexusAuthorParserTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/parser/AudnexusAuthorParserTest.java new file mode 100644 index 000000000..02ef11dca --- /dev/null +++ b/booklore-api/src/test/java/org/booklore/service/metadata/parser/AudnexusAuthorParserTest.java @@ -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 mockResponse = mock(HttpResponse.class); + when(mockResponse.statusCode()).thenReturn(200); + when(mockResponse.body()).thenReturn(json); + doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any()); + + List 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 mockResponse = mock(HttpResponse.class); + when(mockResponse.statusCode()).thenReturn(500); + doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any()); + + List 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 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 mockResponse = mock(HttpResponse.class); + when(mockResponse.statusCode()).thenReturn(200); + when(mockResponse.body()).thenReturn(json); + doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any()); + + List 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 mockResponse = mock(HttpResponse.class); + when(mockResponse.statusCode()).thenReturn(200); + when(mockResponse.body()).thenReturn("[]"); + doReturn(mockResponse).when(httpClient).send(any(HttpRequest.class), any()); + + ArgumentCaptor 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 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 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 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 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"); + } +} diff --git a/booklore-ui/src/app/app.routes.ts b/booklore-ui/src/app/app.routes.ts index fa1b08f2e..e278a497e 100644 --- a/booklore-ui/src/app/app.routes.ts +++ b/booklore-ui/src/app/app.routes.ts @@ -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]}, diff --git a/booklore-ui/src/app/core/custom-reuse-strategy.ts b/booklore-ui/src/app/core/custom-reuse-strategy.ts index f738f54c4..209bb49a3 100644 --- a/booklore-ui/src/app/core/custom-reuse-strategy.ts +++ b/booklore-ui/src/app/core/custom-reuse-strategy.ts @@ -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); } diff --git a/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.html b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.html new file mode 100644 index 000000000..ebf18bf05 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.html @@ -0,0 +1,285 @@ + + @if (loading) { +
+ + +
+ } + + @if (!loading) { +
+

{{ t('browseAllAuthors') }}

+ +
+
+ + +
+ +
+ + + + + + + + @if (!isMobile) { + + +
+ + + +
+ {{ authorScaleService.scaleFactor.toFixed(2) }}x +
+
+
+ } + + +
+
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ +
+ + + +
+ + @if (activeFilterCount > 0) { + + + } +
+
+
+
+
+ + @if (filteredAuthors$ | async; as authorList) { + @if (authorList.length === 0) { +
+ +

{{ t('noAuthorsFound') }}

+
+ } @else { + +
+ @for (author of scroll.viewPortItems; track author.id; let i = $index) { +
+ + +
+ } +
+
+ } + } + + @if (userService.userState$ | async; as userState) { + + } + } +
diff --git a/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.scss b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.scss new file mode 100644 index 000000000..c429eeb51 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.scss @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.ts b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.ts new file mode 100644 index 000000000..e89cb7a4b --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-browser/author-browser.component.ts @@ -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 = { + '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(); + + @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(''); + sortBy$ = new BehaviorSubject('name'); + sortDirection$ = new BehaviorSubject('asc'); + allAuthors$ = new BehaviorSubject([]); + filters$ = new BehaviorSubject({...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; + private enrichedAuthors$ = new BehaviorSubject([]); + + 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(); + const genreSet = new Set(); + 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(); + 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(); + const libraryNameSet = new Set(); + const categorySet = new Set(); + const seriesSet = new Set(); + 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; + } + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.html b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.html new file mode 100644 index 000000000..baafcd97f --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.html @@ -0,0 +1,48 @@ +
+
+ @if (hasPhoto) { + + } @else { +
+ +
+ } + + {{ author.bookCount }} + + @if (isCheckboxEnabled) { + + + } + +
+ @if (isMatched) { + + } +

{{ author.name }}

+ +
+
+
diff --git a/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.scss b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.scss new file mode 100644 index 000000000..bd53e5501 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.scss @@ -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; +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.ts b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.ts new file mode 100644 index 000000000..efd7832bf --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-card/author-card.component.ts @@ -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(); + @Output() quickMatched = new EventEmitter(); + @Output() checkboxClick = new EventEmitter<{ index: number; author: AuthorSummary; selected: boolean; shiftKey: boolean }>(); + @Output() viewAuthor = new EventEmitter(); + @Output() editAuthor = new EventEmitter(); + @Output() deleteAuthor = new EventEmitter(); + @Output() menuToggled = new EventEmitter(); + @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') + }); + } + }); + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.html b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.html new file mode 100644 index 000000000..257748a35 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.html @@ -0,0 +1,148 @@ + + @if (loading) { +
+ + +

{{ t('loading') }}

+
+ } + + @if (!loading && author) { +
+ + + + + {{ t('booksTab') }} + + @if (canEditMetadata) { + + + {{ t('editTab') }} + + + + {{ t('matchTab') }} + + } + + + +
+
+ @if (hasPhoto) { + + } @else { +
+ +
+ } +
+
+
+

{{ author.name }}

+ @if (author.asin) { + + + + + + + } + @if (canEditMetadata) { + + + } +
+ + @if (author.description) { +
+
+
{{ author.description }}
+
+ @if (isExpanded || isOverflowing) { + + + } +
+ } +
+
+ + @if (authorBooks$ | async; as books) { +
+

{{ t('booksBy', {name: author.name}) }} ({{ books.length }})

+ @if (books.length === 0) { +
+ +

{{ t('noBooksFound') }}

+
+ } @else { + +
+ @for (book of scroll.viewPortItems; track book.id; let i = $index) { +
+ + +
+ } +
+
+ } +
+ } +
+ + @if (canEditMetadata) { + + + + + + + + + } +
+
+
+ } +
diff --git a/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.scss b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.scss new file mode 100644 index 000000000..27fc9cac9 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.scss @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.ts b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.ts new file mode 100644 index 000000000..76296d27d --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-detail/author-detail.component.ts @@ -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; + + author: AuthorDetails | null = null; + loading = true; + tab = 'books'; + isExpanded = false; + isOverflowing = false; + hasPhoto = true; + photoTimestamp = Date.now(); + quickMatching = false; + + authorBooks$!: Observable; + + 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; + } + }); + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.html b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.html new file mode 100644 index 000000000..915d9f911 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.html @@ -0,0 +1,134 @@ + +
+
+ @if (hasPhoto) { + + + } @else { +
+ +
+ } + + @if (isUploading) { + + } + +
+ + + + + + + @if (!form.get('photoLocked')?.value) { + + + } + @if (form.get('photoLocked')?.value) { + + + } +
+
+ +
+
+ +
+ + @if (!form.get('nameLocked')?.value) { + + } + @if (form.get('nameLocked')?.value) { + + } +
+
+ +
+ +
+ + @if (!form.get('asinLocked')?.value) { + + } + @if (form.get('asinLocked')?.value) { + + } +
+
+ +
+ +
+ + @if (!form.get('descriptionLocked')?.value) { + + } + @if (form.get('descriptionLocked')?.value) { + + } +
+
+ + +
+
+
diff --git a/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.scss b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.scss new file mode 100644 index 000000000..3e040738f --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.scss @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.ts b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.ts new file mode 100644 index 000000000..f80363076 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-editor/author-editor.component.ts @@ -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(); + + 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(); + } + } + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.html b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.html new file mode 100644 index 000000000..befa2dd5c --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.html @@ -0,0 +1,96 @@ + +
+
+
+
+ + +
+
+ + + +
+
+ + +
+
+
+ + @if (searching) { +
+ + + {{ t('searching') }} +
+ } + + @if (!searching && hasSearched && results.length === 0) { +
+ +

{{ t('noResults') }}

+

{{ t('noResultsHint') }}

+
+ } + + @if (!searching && !hasSearched) { +
+ +

{{ t('readyToSearch') }}

+

{{ t('readyToSearchHint') }}

+
+ } + + @if (!searching && results.length > 0) { +
+ {{ t('resultsFound', {count: results.length}) }} +
+
+ @for (result of results; track result.asin) { +
+
+ @if (result.imageUrl) { + + } @else { +
+ +
+ } +
+
+

{{ result.name }}

+ ASIN: {{ result.asin }} + @if (result.description) { +

{{ result.description }}

+ } +
+
+ + +
+
+ } +
+ } +
+
diff --git a/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.scss b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.scss new file mode 100644 index 000000000..dedf47363 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.scss @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.ts b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.ts new file mode 100644 index 000000000..ca619ba81 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-match/author-match.component.ts @@ -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(); + + 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 + }); + } + }); + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.html b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.html new file mode 100644 index 000000000..e418bfd1a --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.html @@ -0,0 +1,101 @@ + +
+
+
+
+
+ + +
+ +
+ + + + +
+
+
+
+ +
+ @if (!hasSearched) { +
+
+ +
+

{{ t('readyTitle') }}

+

{{ t('readyHint') }}

+
+ } @else if (searching) { +
+ +

{{ t('searching') }}

+
+ } @else if (photos.length === 0) { +
+
+ +
+

{{ t('noResults') }}

+

{{ t('noResultsHint') }}

+
+ } @else { +
+ + + {{ t('resultsFound', { count: photos.length }) }} + +
+ +
+ @for (photo of photos; track photo.url; let i = $index) { +
+
+ + + @if (photo.width && photo.height) { +
+ {{ photo.width }} x {{ photo.height }} +
+ } +
+ + +
+
+
+ } +
+ } +
+
+
diff --git a/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.scss b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.scss new file mode 100644 index 000000000..c27832239 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.scss @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.ts b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.ts new file mode 100644 index 000000000..c5213c203 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/components/author-photo-search/author-photo-search.component.ts @@ -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; + } +} diff --git a/booklore-ui/src/app/features/author-browser/model/author.model.ts b/booklore-ui/src/app/features/author-browser/model/author.model.ts new file mode 100644 index 000000000..65482e2b5 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/model/author.model.ts @@ -0,0 +1,80 @@ +export interface AuthorSummary { + id: number; + name: string; + asin?: string; + bookCount: number; + hasPhoto: boolean; +} + +export interface EnrichedAuthor extends AuthorSummary { + libraryIds: Set; + 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; +} diff --git a/booklore-ui/src/app/features/author-browser/service/author-scale-preference.service.ts b/booklore-ui/src/app/features/author-browser/service/author-scale-preference.service.ts new file mode 100644 index 000000000..75c816a5a --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/service/author-scale-preference.service.ts @@ -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(); + + 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(this.STORAGE_KEY); + if (saved !== null && !isNaN(saved)) { + this.scaleFactor = saved; + } + } +} diff --git a/booklore-ui/src/app/features/author-browser/service/author-selection.service.ts b/booklore-ui/src/app/features/author-browser/service/author-selection.service.ts new file mode 100644 index 000000000..00faf6c15 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/service/author-selection.service.ts @@ -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>(new Set()); + private currentAuthors: AuthorSummary[] = []; + private lastSelectedIndex: number | null = null; + + selectedAuthors$: Observable> = this.selectedAuthorsSubject.asObservable(); + + get selectedAuthors(): Set { + 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); + } +} diff --git a/booklore-ui/src/app/features/author-browser/service/author.service.ts b/booklore-ui/src/app/features/author-browser/service/author.service.ts new file mode 100644 index 000000000..6b7297381 --- /dev/null +++ b/booklore-ui/src/app/features/author-browser/service/author.service.ts @@ -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(null); + allAuthors$ = this.allAuthorsSubject.asObservable(); + + getAllAuthors(): Observable { + return this.http.get(this.baseUrl).pipe( + tap(authors => this.allAuthorsSubject.next(authors)) + ); + } + + getAuthorDetails(authorId: number): Observable { + return this.http.get(`${this.baseUrl}/${authorId}`); + } + + getAuthorByName(name: string): Observable { + return this.http.get(`${this.baseUrl}/by-name`, {params: {name}}); + } + + searchAuthorMetadata(authorId: number, query: string, region: string): Observable { + return this.http.get(`${this.baseUrl}/${authorId}/search-metadata`, { + params: {q: query, region} + }); + } + + matchAuthor(authorId: number, request: AuthorMatchRequest): Observable { + return this.http.post(`${this.baseUrl}/${authorId}/match`, request); + } + + quickMatchAuthor(authorId: number, region: string = 'us'): Observable { + return this.http.post(`${this.baseUrl}/${authorId}/quick-match`, null, { + params: {region} + }); + } + + autoMatchAuthors(authorIds: number[]): Observable { + 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 { + return this.http.put(`${this.baseUrl}/${authorId}`, request); + } + + unmatchAuthors(authorIds: number[]): Observable { + return this.http.post(`${this.baseUrl}/unmatch`, authorIds); + } + + deleteAuthors(authorIds: number[]): Observable { + return this.http.delete(this.baseUrl, {body: authorIds}); + } + + searchAuthorPhotos(authorId: number, query: string): Observable { + return this.http.get(`${this.baseUrl}/${authorId}/search-photos`, { + params: {q: query} + }); + } + + uploadAuthorPhotoFromUrl(authorId: number, imageUrl: string): Observable { + return this.http.post(`${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; + } +} diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 1a6299749..b5d4f7488 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -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 { diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts index 0a157b90d..79b8739b3 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.ts @@ -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', diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html index f2f9c6a77..22185db5e 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.html @@ -83,9 +83,9 @@ } - @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') {

- {{ (item.bookCount$ | async)?.toString() || '0' }} + {{ formatCount(item.bookCount$ | async) }}

} diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts index 471c365be..826d08cfe 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts @@ -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; diff --git a/booklore-ui/src/i18n/en/author-browser.json b/booklore-ui/src/i18n/en/author-browser.json new file mode 100644 index 000000000..4b19e62c1 --- /dev/null +++ b/booklore-ui/src/i18n/en/author-browser.json @@ -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." + } + } +} diff --git a/booklore-ui/src/i18n/en/index.ts b/booklore-ui/src/i18n/en/index.ts index f5a986576..72f1d0a41 100644 --- a/booklore-ui/src/i18n/en/index.ts +++ b/booklore-ui/src/i18n/en/index.ts @@ -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; diff --git a/booklore-ui/src/i18n/en/layout.json b/booklore-ui/src/i18n/en/layout.json index bd6943e33..fdada6224 100644 --- a/booklore-ui/src/i18n/en/layout.json +++ b/booklore-ui/src/i18n/en/layout.json @@ -26,6 +26,7 @@ "magicShelves": "Magic Shelves", "unshelved": "Unshelved", "series": "Series", + "authors": "Authors", "notebook": "Notebook", "update": "(Update)" }, diff --git a/booklore-ui/src/i18n/es/author-browser.json b/booklore-ui/src/i18n/es/author-browser.json new file mode 100644 index 000000000..92e57cf41 --- /dev/null +++ b/booklore-ui/src/i18n/es/author-browser.json @@ -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." + } + } +} diff --git a/booklore-ui/src/i18n/es/index.ts b/booklore-ui/src/i18n/es/index.ts index f5a986576..72f1d0a41 100644 --- a/booklore-ui/src/i18n/es/index.ts +++ b/booklore-ui/src/i18n/es/index.ts @@ -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; diff --git a/booklore-ui/src/i18n/es/layout.json b/booklore-ui/src/i18n/es/layout.json index 350bffb7f..7f3a4d0be 100644 --- a/booklore-ui/src/i18n/es/layout.json +++ b/booklore-ui/src/i18n/es/layout.json @@ -26,6 +26,7 @@ "magicShelves": "Estantes mágicos", "unshelved": "Sin estante", "series": "Series", + "authors": "Autores", "notebook": "Cuaderno", "update": "(Actualizar)" },