diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java index c8d84e502..6e4b4f17c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookController.java @@ -10,8 +10,11 @@ import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest; import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest; import com.adityachandel.booklore.model.dto.response.BookDeletionResponse; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; import com.adityachandel.booklore.model.enums.ResetProgressType; import com.adityachandel.booklore.service.book.BookService; +import com.adityachandel.booklore.service.book.BookUpdateService; import com.adityachandel.booklore.service.metadata.BookMetadataService; import com.adityachandel.booklore.service.recommender.BookRecommendationService; import io.swagger.v3.oas.annotations.Operation; @@ -40,6 +43,7 @@ import java.util.Set; public class BookController { private final BookService bookService; + private final BookUpdateService bookUpdateService; private final BookRecommendationService bookRecommendationService; private final BookMetadataService bookMetadataService; @@ -54,8 +58,8 @@ public class BookController { @Operation(summary = "Get a book by ID", description = "Retrieve details of a specific book by its ID.") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "Book details returned successfully"), - @ApiResponse(responseCode = "404", description = "Book not found") + @ApiResponse(responseCode = "200", description = "Book details returned successfully"), + @ApiResponse(responseCode = "404", description = "Book not found") }) @GetMapping("/{bookId}") @CheckBookAccess(bookIdParam = "bookId") @@ -67,8 +71,8 @@ public class BookController { @Operation(summary = "Delete books", description = "Delete one or more books by their IDs. Requires admin or delete permission.") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "Books deleted successfully"), - @ApiResponse(responseCode = "403", description = "Forbidden") + @ApiResponse(responseCode = "200", description = "Books deleted successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden") }) @PreAuthorize("@securityUtil.canDeleteBook() or @securityUtil.isAdmin()") @DeleteMapping @@ -105,8 +109,8 @@ public class BookController { @Operation(summary = "Download book", description = "Download the book file. Requires download permission or admin.") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "Book downloaded successfully"), - @ApiResponse(responseCode = "403", description = "Forbidden") + @ApiResponse(responseCode = "200", description = "Book downloaded successfully"), + @ApiResponse(responseCode = "403", description = "Forbidden") }) @GetMapping("/{bookId}/download") @PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()") @@ -165,50 +169,46 @@ public class BookController { @Operation(summary = "Update read status", description = "Update the read status for one or more books.") @ApiResponse(responseCode = "200", description = "Read status updated successfully") - @PutMapping("/read-status") - public ResponseEntity> updateReadStatus( - @Parameter(description = "Read status update request") @RequestBody @Valid ReadStatusUpdateRequest request) { - List updatedBooks = bookService.updateReadStatus(request.ids(), request.status()); - return ResponseEntity.ok(updatedBooks); + @PostMapping("/status") + public List updateReadStatus(@RequestBody @Valid ReadStatusUpdateRequest request) { + return bookService.updateReadStatus(request.getBookIds(), request.getStatus()); } @Operation(summary = "Reset reading progress", description = "Reset the reading progress for one or more books.") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "Progress reset successfully"), - @ApiResponse(responseCode = "400", description = "No book IDs provided") + @ApiResponse(responseCode = "200", description = "Progress reset successfully"), + @ApiResponse(responseCode = "400", description = "No book IDs provided") }) @PostMapping("/reset-progress") - public ResponseEntity> resetProgress( + public ResponseEntity> resetProgress( @Parameter(description = "List of book IDs to reset progress for") @RequestBody List bookIds, @Parameter(description = "Type of progress reset") @RequestParam ResetProgressType type) { if (bookIds == null || bookIds.isEmpty()) { throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided"); } - List updatedBooks = bookService.resetProgress(bookIds, type); - return ResponseEntity.ok(updatedBooks); + return ResponseEntity.ok(bookUpdateService.resetProgress(bookIds, type)); } @Operation(summary = "Update personal rating", description = "Update the personal rating for one or more books.") @ApiResponse(responseCode = "200", description = "Personal rating updated successfully") @PutMapping("/personal-rating") - public ResponseEntity> updatePersonalRating( + public ResponseEntity> updatePersonalRating( @Parameter(description = "Personal rating update request") @RequestBody @Valid PersonalRatingUpdateRequest request) { - List updatedBooks = bookService.updatePersonalRating(request.ids(), request.rating()); - return ResponseEntity.ok(updatedBooks); + return ResponseEntity.ok(bookUpdateService.updatePersonalRating(request.ids(), request.rating())); } @Operation(summary = "Reset personal rating", description = "Reset the personal rating for one or more books.") @ApiResponses({ - @ApiResponse(responseCode = "200", description = "Personal rating reset successfully"), - @ApiResponse(responseCode = "400", description = "No book IDs provided") + @ApiResponse(responseCode = "200", description = "Personal rating reset successfully"), + @ApiResponse(responseCode = "400", description = "No book IDs provided") }) @PostMapping("/reset-personal-rating") - public ResponseEntity> resetPersonalRating( + public ResponseEntity> resetPersonalRating( @Parameter(description = "List of book IDs to reset personal rating for") @RequestBody List bookIds) { if (bookIds == null || bookIds.isEmpty()) { throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided"); } - List updatedBooks = bookService.resetPersonalRating(bookIds); + List updatedBooks = bookUpdateService.resetPersonalRating(bookIds); return ResponseEntity.ok(updatedBooks); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java b/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java index cf93fbbe7..3f88dc531 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/crons/CronService.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.crons; import com.adityachandel.booklore.model.dto.BookloreTelemetry; import com.adityachandel.booklore.service.TelemetryService; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; @@ -17,18 +18,21 @@ public class CronService { private final TelemetryService telemetryService; private final RestClient restClient; + private final AppSettingService appSettingService; @Scheduled(fixedDelay = 24, timeUnit = TimeUnit.HOURS, initialDelay = 24) public void sendTelemetryData() { - try { - BookloreTelemetry telemetry = telemetryService.collectTelemetry(); - restClient.post() - .uri("https://telemetry.booklore.dev/api/v1/ingest") - .body(telemetry) - .retrieve() - .body(String.class); - } catch (Exception ignored) { + if (appSettingService.getAppSettings().isTelemetryEnabled()) { + try { + BookloreTelemetry telemetry = telemetryService.collectTelemetry(); + restClient.post() + .uri("https://telemetry.booklore.dev/api/v1/ingest") + .body(telemetry) + .retrieve() + .body(String.class); + } catch (Exception ignored) { + } } } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadStatusUpdateRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadStatusUpdateRequest.java index ae7780aba..16712ef1f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadStatusUpdateRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/ReadStatusUpdateRequest.java @@ -1,6 +1,16 @@ package com.adityachandel.booklore.model.dto.request; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + import java.util.List; -public record ReadStatusUpdateRequest(List ids, String status) { +@Data +public class ReadStatusUpdateRequest { + @NotEmpty(message = "Book IDs cannot be empty") + private List bookIds; + + @NotNull(message = "Status cannot be null") + private String status; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/BookStatusUpdateResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/BookStatusUpdateResponse.java new file mode 100644 index 000000000..0d9391f7d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/BookStatusUpdateResponse.java @@ -0,0 +1,21 @@ +package com.adityachandel.booklore.model.dto.response; + +import com.adityachandel.booklore.model.enums.ReadStatus; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.Instant; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class BookStatusUpdateResponse { + private Long bookId; + private ReadStatus readStatus; + private Instant readStatusModifiedTime; + private Instant dateFinished; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PersonalRatingUpdateResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PersonalRatingUpdateResponse.java new file mode 100644 index 000000000..4d898bab1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/PersonalRatingUpdateResponse.java @@ -0,0 +1,16 @@ +package com.adityachandel.booklore.model.dto.response; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PersonalRatingUpdateResponse { + private Long bookId; + private Integer personalRating; +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java index bd998be97..7a8a6be43 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java @@ -33,6 +33,7 @@ public enum AppSettingKey { CBX_CACHE_SIZE_IN_MB ("cbx_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)), PDF_CACHE_SIZE_IN_MB ("pdf_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)), MAX_FILE_UPLOAD_SIZE_IN_MB ("max_file_upload_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)), + TELEMETRY_ENABLED ("telemetryEnabled", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)), // No specific permissions required SIDEBAR_LIBRARY_SORTING ("sidebar_library_sorting", true, false, List.of()), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java index 12a6e4b0d..9091b95c0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java @@ -25,6 +25,7 @@ public class AppSettings { private boolean remoteAuthEnabled; private boolean metadataDownloadOnBookdrop; private boolean oidcEnabled; + private boolean telemetryEnabled; private OidcProviderDetails oidcProviderDetails; private OidcAutoProvisionDetails oidcAutoProvisionDetails; private MetadataProviderSettings metadataProviderSettings; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index 4c24b1765..494d84955 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -90,22 +90,6 @@ public interface BookRepository extends JpaRepository, JpaSpec """) List findBooksWithMetadataAndAuthors(@Param("bookIds") List bookIds); - @Query(value = """ - SELECT DISTINCT b FROM BookEntity b - LEFT JOIN b.metadata m - WHERE (b.deleted IS NULL OR b.deleted = false) AND ( - m.searchText LIKE CONCAT('%', :text, '%') - ) - """, - countQuery = """ - SELECT COUNT(DISTINCT b.id) FROM BookEntity b - LEFT JOIN b.metadata m - WHERE (b.deleted IS NULL OR b.deleted = false) AND ( - m.searchText LIKE CONCAT('%', :text, '%') - ) - """) - Page searchByMetadata(@Param("text") String text, Pageable pageable); - @Modifying @Transactional @Query("DELETE FROM BookEntity b WHERE b.deleted IS TRUE") @@ -136,20 +120,23 @@ public interface BookRepository extends JpaRepository, JpaSpec @Param("libraryPath") LibraryPathEntity libraryPath); @Query(value = """ - SELECT * - FROM book - WHERE library_id = :libraryId - AND library_path_id = :libraryPathId - AND file_sub_path = :fileSubPath - AND file_name = :fileName - LIMIT 1 - """, nativeQuery = true) + SELECT * + FROM book + WHERE library_id = :libraryId + AND library_path_id = :libraryPathId + AND file_sub_path = :fileSubPath + AND file_name = :fileName + LIMIT 1 + """, nativeQuery = true) Optional findByLibraryIdAndLibraryPathIdAndFileSubPathAndFileName( @Param("libraryId") Long libraryId, @Param("libraryPathId") Long libraryPathId, @Param("fileSubPath") String fileSubPath, @Param("fileName") String fileName); + @Query("SELECT COUNT(b.id) FROM BookEntity b WHERE b.id IN :bookIds AND (b.deleted IS NULL OR b.deleted = false)") + long countByIdIn(@Param("bookIds") List bookIds); + @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.bookType = :type AND (b.deleted IS NULL OR b.deleted = false)") long countByBookType(@Param("type") BookFileType type); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java index ca6a358a3..86789b2b9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserBookProgressRepository.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.dto.CompletionTimelineDto; import com.adityachandel.booklore.model.entity.UserBookProgressEntity; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @@ -60,4 +61,81 @@ public interface UserBookProgressRepository extends JpaRepository findCompletionTimelineByUser(@Param("userId") Long userId, @Param("year") int year); + + @Modifying + @Query(""" + UPDATE UserBookProgressEntity ubp + SET ubp.readStatus = :readStatus, + ubp.readStatusModifiedTime = :modifiedTime, + ubp.dateFinished = :dateFinished + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + int bulkUpdateReadStatus( + @Param("userId") Long userId, + @Param("bookIds") List bookIds, + @Param("readStatus") com.adityachandel.booklore.model.enums.ReadStatus readStatus, + @Param("modifiedTime") java.time.Instant modifiedTime, + @Param("dateFinished") java.time.Instant dateFinished + ); + + @Query(""" + SELECT ubp.book.id FROM UserBookProgressEntity ubp + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + Set findExistingProgressBookIds(@Param("userId") Long userId, @Param("bookIds") Set bookIds); + + @Modifying + @Query(""" + UPDATE UserBookProgressEntity ubp + SET ubp.readStatus = NULL, + ubp.readStatusModifiedTime = :modifiedTime, + ubp.lastReadTime = NULL, + ubp.dateFinished = NULL, + ubp.pdfProgress = NULL, + ubp.pdfProgressPercent = NULL, + ubp.epubProgress = NULL, + ubp.epubProgressPercent = NULL, + ubp.cbxProgress = NULL, + ubp.cbxProgressPercent = NULL + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + int bulkResetBookloreProgress(@Param("userId") Long userId, @Param("bookIds") List bookIds, @Param("modifiedTime") java.time.Instant modifiedTime); + + @Modifying + @Query(""" + UPDATE UserBookProgressEntity ubp + SET ubp.koreaderProgress = NULL, + ubp.koreaderProgressPercent = NULL, + ubp.koreaderDeviceId = NULL, + ubp.koreaderDevice = NULL, + ubp.koreaderLastSyncTime = NULL + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + int bulkResetKoreaderProgress(@Param("userId") Long userId, @Param("bookIds") List bookIds); + + @Modifying + @Query(""" + UPDATE UserBookProgressEntity ubp + SET ubp.koboProgressPercent = NULL, + ubp.koboLocation = NULL, + ubp.koboLocationType = NULL, + ubp.koboLocationSource = NULL, + ubp.koboProgressReceivedTime = NULL + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + int bulkResetKoboProgress(@Param("userId") Long userId, @Param("bookIds") List bookIds); + + @Modifying + @Query(""" + UPDATE UserBookProgressEntity ubp + SET ubp.personalRating = :rating + WHERE ubp.user.id = :userId + AND ubp.book.id IN :bookIds + """) + int bulkUpdatePersonalRating(@Param("userId") Long userId, @Param("bookIds") List bookIds, @Param("rating") Integer rating); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java index 975753921..86bc212cf 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java @@ -73,7 +73,7 @@ public class AppSettingService { } boolean hasPermission = requiredPermissions.stream().anyMatch(permission -> - UserPermissionUtils.hasPermission(user.getPermissions(), permission) + UserPermissionUtils.hasPermission(user.getPermissions(), permission) ); if (!hasPermission) { @@ -131,6 +131,7 @@ public class AppSettingService { builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>")); builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true"))); builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false"))); + builder.telemetryEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.TELEMETRY_ENABLED, "true"))); builder.cbxCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120"))); builder.pdfCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.PDF_CACHE_SIZE_IN_MB, "5120"))); builder.maxFileUploadSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100"))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java index 92f1ea79b..4dde851e9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java @@ -4,31 +4,29 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.model.dto.*; -import com.adityachandel.booklore.model.dto.progress.CbxProgress; -import com.adityachandel.booklore.model.dto.progress.EpubProgress; -import com.adityachandel.booklore.model.dto.progress.KoProgress; -import com.adityachandel.booklore.model.dto.progress.KoboProgress; -import com.adityachandel.booklore.model.dto.progress.PdfProgress; +import com.adityachandel.booklore.model.dto.progress.*; import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.response.BookDeletionResponse; -import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.entity.UserBookProgressEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.ReadStatus; -import com.adityachandel.booklore.model.enums.ResetProgressType; import com.adityachandel.booklore.repository.*; -import com.adityachandel.booklore.service.kobo.KoboReadingStateService; -import com.adityachandel.booklore.service.user.UserProgressService; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import com.adityachandel.booklore.service.user.UserProgressService; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.EnumUtils; -import org.springframework.core.io.*; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -39,7 +37,6 @@ import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.time.Instant; import java.util.*; import java.util.stream.Collectors; @@ -53,17 +50,15 @@ public class BookService { private final EpubViewerPreferencesRepository epubViewerPreferencesRepository; private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository; private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; - private final ShelfRepository shelfRepository; private final FileService fileService; private final BookMapper bookMapper; - private final UserRepository userRepository; private final UserBookProgressRepository userBookProgressRepository; private final AuthenticationService authenticationService; private final BookQueryService bookQueryService; private final UserProgressService userProgressService; private final BookDownloadService bookDownloadService; private final MonitoringRegistrationService monitoringRegistrationService; - private final KoboReadingStateService koboReadingStateService; + private final BookUpdateService bookUpdateService; private void setBookProgress(Book book, UserBookProgressEntity progress) { @@ -248,336 +243,22 @@ public class BookService { } public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - BookLoreUser user = authenticationService.getAuthenticatedUser(); - - if (bookEntity.getBookType() == BookFileType.PDF) { - if (bookViewerSettings.getPdfSettings() != null) { - PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository - .findByBookIdAndUserId(bookId, user.getId()) - .orElseGet(() -> { - PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder() - .bookId(bookId) - .userId(user.getId()) - .build(); - return pdfViewerPreferencesRepository.save(newPrefs); - }); - PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings(); - pdfPrefs.setZoom(pdfSettings.getZoom()); - pdfPrefs.setSpread(pdfSettings.getSpread()); - pdfViewerPreferencesRepository.save(pdfPrefs); - } - if (bookViewerSettings.getNewPdfSettings() != null) { - NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId()) - .orElseGet(() -> { - NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder() - .bookId(bookId) - .userId(user.getId()) - .build(); - return newPdfViewerPreferencesRepository.save(entity); - }); - NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings(); - pdfPrefs.setPageSpread(pdfSettings.getPageSpread()); - pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode()); - newPdfViewerPreferencesRepository.save(pdfPrefs); - } - } else if (bookEntity.getBookType() == BookFileType.EPUB) { - EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository - .findByBookIdAndUserId(bookId, user.getId()) - .orElseGet(() -> { - EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder() - .bookId(bookId) - .userId(user.getId()) - .build(); - return epubViewerPreferencesRepository.save(newPrefs); - }); - - EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings(); - epubPrefs.setFont(epubSettings.getFont()); - epubPrefs.setFontSize(epubSettings.getFontSize()); - epubPrefs.setTheme(epubSettings.getTheme()); - epubPrefs.setFlow(epubSettings.getFlow()); - epubPrefs.setSpread(epubSettings.getSpread()); - epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing()); - epubPrefs.setLineHeight(epubSettings.getLineHeight()); - epubViewerPreferencesRepository.save(epubPrefs); - - } else if (bookEntity.getBookType() == BookFileType.CBX) { - CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository - .findByBookIdAndUserId(bookId, user.getId()) - .orElseGet(() -> { - CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder() - .bookId(bookId) - .userId(user.getId()) - .build(); - return cbxViewerPreferencesRepository.save(newPrefs); - }); - - CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings(); - cbxPrefs.setPageSpread(cbxSettings.getPageSpread()); - cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode()); - cbxPrefs.setFitMode(cbxSettings.getFitMode()); - cbxPrefs.setScrollMode(cbxSettings.getScrollMode()); - cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor()); - cbxViewerPreferencesRepository.save(cbxPrefs); - - } else { - throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); - } + bookUpdateService.updateBookViewerSetting(bookId, bookViewerSettings); } @Transactional public void updateReadProgress(ReadProgressRequest request) { - BookEntity book = bookRepository.findById(request.getBookId()) - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId())); - - BookLoreUser user = authenticationService.getAuthenticatedUser(); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), book.getId()) - .orElseGet(UserBookProgressEntity::new); - - BookLoreUserEntity userEntity = userRepository.findById(user.getId()) - .orElseThrow(() -> new UsernameNotFoundException("User not found")); - progress.setUser(userEntity); - - progress.setBook(book); - progress.setLastReadTime(Instant.now()); - - Float percentage = null; - switch (book.getBookType()) { - case EPUB -> { - if (request.getEpubProgress() != null) { - progress.setEpubProgress(request.getEpubProgress().getCfi()); - percentage = request.getEpubProgress().getPercentage(); - } - } - case PDF -> { - if (request.getPdfProgress() != null) { - progress.setPdfProgress(request.getPdfProgress().getPage()); - percentage = request.getPdfProgress().getPercentage(); - } - } - case CBX -> { - if (request.getCbxProgress() != null) { - progress.setCbxProgress(request.getCbxProgress().getPage()); - percentage = request.getCbxProgress().getPercentage(); - } - } - } - - if (percentage != null) { - progress.setReadStatus(getStatus(percentage)); - setProgressPercent(progress, book.getBookType(), percentage); - } - - if (request.getDateFinished() != null) { - progress.setDateFinished(request.getDateFinished()); - } - - userBookProgressRepository.save(progress); - } - - private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) { - switch (type) { - case EPUB -> progress.setEpubProgressPercent(percentage); - case PDF -> progress.setPdfProgressPercent(percentage); - case CBX -> progress.setCbxProgressPercent(percentage); - } - } - - private ReadStatus getStatus(Float percentage) { - if (percentage >= 99.5f) return ReadStatus.READ; - if (percentage > 0.5f) return ReadStatus.READING; - return ReadStatus.UNREAD; + bookUpdateService.updateReadProgress(request); } @Transactional - public List updateReadStatus(List bookIds, String status) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status); - - List books = bookRepository.findAllById(bookIds); - if (books.size() != bookIds.size()) { - throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found"); - } - - BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")); - for (BookEntity book : books) { - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), book.getId()) - .orElse(new UserBookProgressEntity()); - - progress.setUser(userEntity); - progress.setBook(book); - progress.setReadStatus(readStatus); - progress.setReadStatusModifiedTime(Instant.now()); - - if (readStatus == ReadStatus.READ) { - progress.setDateFinished(Instant.now()); - } else { - progress.setDateFinished(null); - } - - userBookProgressRepository.save(progress); - } - - return books.stream() - .map(bookEntity -> { - Book book = bookMapper.toBook(bookEntity); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), bookEntity.getId()) - .orElse(null); - - this.enrichBookWithProgress(book, progress); - return book; - }) - .collect(Collectors.toList()); - } - - public List resetProgress(List bookIds, ResetProgressType type) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - List updatedBooks = new ArrayList<>(); - Optional userEntity = userRepository.findById(user.getId()); - - for (Long bookId : bookIds) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), bookId) - .orElse(new UserBookProgressEntity()); - - progress.setBook(bookEntity); - progress.setUser(userEntity.orElseThrow()); - - if (progress.getReadStatus() != null) { - progress.setReadStatusModifiedTime(Instant.now()); - } - - progress.setReadStatus(null); - progress.setLastReadTime(null); - progress.setDateFinished(null); - if (type == ResetProgressType.BOOKLORE) { - progress.setPdfProgress(null); - progress.setPdfProgressPercent(null); - progress.setEpubProgress(null); - progress.setEpubProgressPercent(null); - progress.setCbxProgress(null); - progress.setCbxProgressPercent(null); - } else if (type == ResetProgressType.KOREADER) { - progress.setKoreaderProgress(null); - progress.setKoreaderProgressPercent(null); - progress.setKoreaderDeviceId(null); - progress.setKoreaderDevice(null); - progress.setKoreaderLastSyncTime(null); - } else if (type == ResetProgressType.KOBO) { - progress.setKoboProgressPercent(null); - progress.setKoboLocation(null); - progress.setKoboLocationType(null); - progress.setKoboLocationSource(null); - progress.setKoboProgressReceivedTime(null); - koboReadingStateService.deleteReadingState(bookId); - } - userBookProgressRepository.save(progress); - updatedBooks.add(bookMapper.toBook(bookEntity)); - } - - return updatedBooks; - } - - @Transactional - public List updatePersonalRating(List bookIds, Integer rating) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - - List books = bookRepository.findAllById(bookIds); - if (books.size() != bookIds.size()) { - throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found"); - } - - BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")); - for (BookEntity book : books) { - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), book.getId()) - .orElse(new UserBookProgressEntity()); - - progress.setUser(userEntity); - progress.setBook(book); - progress.setPersonalRating(rating); - userBookProgressRepository.save(progress); - } - - return books.stream() - .map(bookEntity -> { - Book book = bookMapper.toBook(bookEntity); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), bookEntity.getId()) - .orElse(null); - - this.enrichBookWithProgress(book, progress); - return book; - }) - .collect(Collectors.toList()); - } - - public List resetPersonalRating(List bookIds) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - List updatedBooks = new ArrayList<>(); - Optional userEntity = userRepository.findById(user.getId()); - - for (Long bookId : bookIds) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - UserBookProgressEntity progress = userBookProgressRepository - .findByUserIdAndBookId(user.getId(), bookId) - .orElse(new UserBookProgressEntity()); - - progress.setBook(bookEntity); - progress.setUser(userEntity.orElseThrow()); - progress.setPersonalRating(null); - - userBookProgressRepository.save(progress); - updatedBooks.add(bookMapper.toBook(bookEntity)); - } - - return updatedBooks; + public List updateReadStatus(List bookIds, String status) { + return bookUpdateService.updateReadStatus(bookIds, status); } @Transactional public List assignShelvesToBooks(Set bookIds, Set shelfIdsToAssign, Set shelfIdsToUnassign) { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId())); - - Set userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet()); - - if (!userShelfIds.containsAll(shelfIdsToAssign)) { - throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user."); - } - if (!userShelfIds.containsAll(shelfIdsToUnassign)) { - throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user."); - } - - List bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds); - List shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign); - for (BookEntity bookEntity : bookEntities) { - bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId())); - bookEntity.getShelves().addAll(shelvesToAssign); - } - bookRepository.saveAll(bookEntities); - - Map progressMap = userProgressService.fetchUserProgress( - user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet())); - - return bookEntities.stream().map(bookEntity -> { - Book book = bookMapper.toBook(bookEntity); - book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId())); - book.setFilePath(FileUtils.getBookFullPath(bookEntity)); - enrichBookWithProgress(book, progressMap.get(bookEntity.getId())); - return book; - }).collect(Collectors.toList()); + return bookUpdateService.assignShelvesToBooks(bookIds, shelfIdsToAssign, shelfIdsToUnassign); } public Resource getBookThumbnail(long bookId) { @@ -639,7 +320,11 @@ public class BookService { Path fullFilePath = book.getFullFilePath(); try { if (Files.exists(fullFilePath)) { - monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent()); + try { + monitoringRegistrationService.unregisterSpecificPath(fullFilePath.getParent()); + } catch (Exception ex) { + log.warn("Failed to unregister monitoring for path: {}", fullFilePath.getParent(), ex); + } Files.delete(fullFilePath); log.info("Deleted book file: {}", fullFilePath); @@ -736,4 +421,5 @@ public class BookService { .filter(shelf -> userId.equals(shelf.getUserId())) .collect(Collectors.toSet()); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java new file mode 100644 index 000000000..b70512707 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookUpdateService.java @@ -0,0 +1,419 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.*; +import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.ReadStatus; +import com.adityachandel.booklore.model.enums.ResetProgressType; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.kobo.KoboReadingStateService; +import com.adityachandel.booklore.service.user.UserProgressService; +import com.adityachandel.booklore.util.FileUtils; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.EnumUtils; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; + +@Slf4j +@AllArgsConstructor +@Service +public class BookUpdateService { + + private final BookRepository bookRepository; + private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository; + private final EpubViewerPreferencesRepository epubViewerPreferencesRepository; + private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository; + private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; + private final ShelfRepository shelfRepository; + private final BookMapper bookMapper; + private final UserRepository userRepository; + private final UserBookProgressRepository userBookProgressRepository; + private final AuthenticationService authenticationService; + private final BookQueryService bookQueryService; + private final UserProgressService userProgressService; + private final KoboReadingStateService koboReadingStateService; + + public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + BookLoreUser user = authenticationService.getAuthenticatedUser(); + + if (bookEntity.getBookType() == BookFileType.PDF) { + if (bookViewerSettings.getPdfSettings() != null) { + PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository + .findByBookIdAndUserId(bookId, user.getId()) + .orElseGet(() -> { + PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder() + .bookId(bookId) + .userId(user.getId()) + .build(); + return pdfViewerPreferencesRepository.save(newPrefs); + }); + PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings(); + pdfPrefs.setZoom(pdfSettings.getZoom()); + pdfPrefs.setSpread(pdfSettings.getSpread()); + pdfViewerPreferencesRepository.save(pdfPrefs); + } + if (bookViewerSettings.getNewPdfSettings() != null) { + NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId()) + .orElseGet(() -> { + NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder() + .bookId(bookId) + .userId(user.getId()) + .build(); + return newPdfViewerPreferencesRepository.save(entity); + }); + NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings(); + pdfPrefs.setPageSpread(pdfSettings.getPageSpread()); + pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode()); + newPdfViewerPreferencesRepository.save(pdfPrefs); + } + } else if (bookEntity.getBookType() == BookFileType.EPUB) { + EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository + .findByBookIdAndUserId(bookId, user.getId()) + .orElseGet(() -> { + EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder() + .bookId(bookId) + .userId(user.getId()) + .build(); + return epubViewerPreferencesRepository.save(newPrefs); + }); + + EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings(); + epubPrefs.setFont(epubSettings.getFont()); + epubPrefs.setFontSize(epubSettings.getFontSize()); + epubPrefs.setTheme(epubSettings.getTheme()); + epubPrefs.setFlow(epubSettings.getFlow()); + epubPrefs.setSpread(epubSettings.getSpread()); + epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing()); + epubPrefs.setLineHeight(epubSettings.getLineHeight()); + epubViewerPreferencesRepository.save(epubPrefs); + + } else if (bookEntity.getBookType() == BookFileType.CBX) { + CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository + .findByBookIdAndUserId(bookId, user.getId()) + .orElseGet(() -> { + CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder() + .bookId(bookId) + .userId(user.getId()) + .build(); + return cbxViewerPreferencesRepository.save(newPrefs); + }); + + CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings(); + cbxPrefs.setPageSpread(cbxSettings.getPageSpread()); + cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode()); + cbxPrefs.setFitMode(cbxSettings.getFitMode()); + cbxPrefs.setScrollMode(cbxSettings.getScrollMode()); + cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor()); + cbxViewerPreferencesRepository.save(cbxPrefs); + + } else { + throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(); + } + } + + @Transactional + public void updateReadProgress(ReadProgressRequest request) { + BookEntity book = bookRepository.findById(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId())); + + BookLoreUser user = authenticationService.getAuthenticatedUser(); + + UserBookProgressEntity progress = userBookProgressRepository + .findByUserIdAndBookId(user.getId(), book.getId()) + .orElseGet(UserBookProgressEntity::new); + + BookLoreUserEntity userEntity = userRepository.findById(user.getId()) + .orElseThrow(() -> new UsernameNotFoundException("User not found")); + progress.setUser(userEntity); + + progress.setBook(book); + progress.setLastReadTime(Instant.now()); + + Float percentage = null; + switch (book.getBookType()) { + case EPUB -> { + if (request.getEpubProgress() != null) { + progress.setEpubProgress(request.getEpubProgress().getCfi()); + percentage = request.getEpubProgress().getPercentage(); + } + } + case PDF -> { + if (request.getPdfProgress() != null) { + progress.setPdfProgress(request.getPdfProgress().getPage()); + percentage = request.getPdfProgress().getPercentage(); + } + } + case CBX -> { + if (request.getCbxProgress() != null) { + progress.setCbxProgress(request.getCbxProgress().getPage()); + percentage = request.getCbxProgress().getPercentage(); + } + } + } + + if (percentage != null) { + progress.setReadStatus(getStatus(percentage)); + setProgressPercent(progress, book.getBookType(), percentage); + } + + if (request.getDateFinished() != null) { + progress.setDateFinished(request.getDateFinished()); + } + + userBookProgressRepository.save(progress); + } + + @Transactional + public List updateReadStatus(List bookIds, String status) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status); + + Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); + + Instant now = Instant.now(); + Instant dateFinished = readStatus == ReadStatus.READ ? now : null; + + if (!existingProgressBookIds.isEmpty()) { + userBookProgressRepository.bulkUpdateReadStatus(user.getId(), new ArrayList<>(existingProgressBookIds), readStatus, now, dateFinished); + } + + Set newProgressBookIds = bookIds.stream() + .filter(id -> !existingProgressBookIds.contains(id)) + .collect(Collectors.toSet()); + + if (!newProgressBookIds.isEmpty()) { + BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")); + + List newProgressEntities = newProgressBookIds.stream() + .map(bookId -> { + UserBookProgressEntity progress = new UserBookProgressEntity(); + progress.setUser(userEntity); + + BookEntity bookEntity = new BookEntity(); + bookEntity.setId(bookId); + progress.setBook(bookEntity); + + progress.setReadStatus(readStatus); + progress.setReadStatusModifiedTime(now); + progress.setDateFinished(dateFinished); + return progress; + }) + .collect(Collectors.toList()); + + userBookProgressRepository.saveAll(newProgressEntities); + } + + return bookIds.stream() + .map(bookId -> BookStatusUpdateResponse.builder() + .bookId(bookId) + .readStatus(readStatus) + .readStatusModifiedTime(now) + .dateFinished(dateFinished) + .build()) + .collect(Collectors.toList()); + } + + @Transactional + public List resetProgress(List bookIds, ResetProgressType type) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + + Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); + + Instant now = Instant.now(); + + if (!existingProgressBookIds.isEmpty()) { + if (type == ResetProgressType.BOOKLORE) { + userBookProgressRepository.bulkResetBookloreProgress(user.getId(), new ArrayList<>(existingProgressBookIds), now); + } else if (type == ResetProgressType.KOREADER) { + userBookProgressRepository.bulkResetKoreaderProgress(user.getId(), new ArrayList<>(existingProgressBookIds)); + } else if (type == ResetProgressType.KOBO) { + userBookProgressRepository.bulkResetKoboProgress(user.getId(), new ArrayList<>(existingProgressBookIds)); + existingProgressBookIds.forEach(koboReadingStateService::deleteReadingState); + } + } + + return bookIds.stream() + .map(bookId -> BookStatusUpdateResponse.builder() + .bookId(bookId) + .readStatus(null) + .readStatusModifiedTime(existingProgressBookIds.contains(bookId) ? now : null) + .dateFinished(null) + .build()) + .collect(Collectors.toList()); + } + + @Transactional + public List updatePersonalRating(List bookIds, Integer rating) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + + Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); + + if (!existingProgressBookIds.isEmpty()) { + userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), rating); + } + + Set newProgressBookIds = bookIds.stream() + .filter(id -> !existingProgressBookIds.contains(id)) + .collect(Collectors.toSet()); + + if (!newProgressBookIds.isEmpty()) { + BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found")); + + List newProgressEntities = newProgressBookIds.stream() + .map(bookId -> { + UserBookProgressEntity progress = new UserBookProgressEntity(); + progress.setUser(userEntity); + + BookEntity bookEntity = new BookEntity(); + bookEntity.setId(bookId); + progress.setBook(bookEntity); + + progress.setPersonalRating(rating); + return progress; + }) + .collect(Collectors.toList()); + + userBookProgressRepository.saveAll(newProgressEntities); + } + + return bookIds.stream() + .map(bookId -> PersonalRatingUpdateResponse.builder() + .bookId(bookId) + .personalRating(rating) + .build()) + .collect(Collectors.toList()); + } + + @Transactional + public List resetPersonalRating(List bookIds) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + + Set existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds); + + if (!existingProgressBookIds.isEmpty()) { + userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), null); + } + + return bookIds.stream() + .map(bookId -> PersonalRatingUpdateResponse.builder() + .bookId(bookId) + .personalRating(null) + .build()) + .collect(Collectors.toList()); + } + + @Transactional + public List assignShelvesToBooks(Set bookIds, Set shelfIdsToAssign, Set shelfIdsToUnassign) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId())); + + Set userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet()); + + if (!userShelfIds.containsAll(shelfIdsToAssign)) { + throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user."); + } + if (!userShelfIds.containsAll(shelfIdsToUnassign)) { + throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user."); + } + + List bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds); + List shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign); + for (BookEntity bookEntity : bookEntities) { + bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId())); + bookEntity.getShelves().addAll(shelvesToAssign); + } + bookRepository.saveAll(bookEntities); + + Map progressMap = userProgressService.fetchUserProgress( + user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet())); + + return bookEntities.stream().map(bookEntity -> { + Book book = bookMapper.toBook(bookEntity); + book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId())); + book.setFilePath(FileUtils.getBookFullPath(bookEntity)); + enrichBookWithProgress(book, progressMap.get(bookEntity.getId())); + return book; + }).collect(Collectors.toList()); + } + + private Set validateBooksAndGetExistingProgress(Long userId, List bookIds) { + long existingBooksCount = bookRepository.countByIdIn(bookIds); + if (existingBooksCount != bookIds.size()) { + throw ApiError.BOOK_NOT_FOUND.createException("One or more books not found"); + } + + return userBookProgressRepository.findExistingProgressBookIds(userId, new HashSet<>(bookIds)); + } + + private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) { + switch (type) { + case EPUB -> progress.setEpubProgressPercent(percentage); + case PDF -> progress.setPdfProgressPercent(percentage); + case CBX -> progress.setCbxProgressPercent(percentage); + } + } + + private ReadStatus getStatus(Float percentage) { + if (percentage >= 99.5f) return ReadStatus.READ; + if (percentage > 0.5f) return ReadStatus.READING; + return ReadStatus.UNREAD; + } + + private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) { + if (progress != null) { + setBookProgress(book, progress); + book.setLastReadTime(progress.getLastReadTime()); + book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus())); + book.setDateFinished(progress.getDateFinished()); + book.setPersonalRating(progress.getPersonalRating()); + } + } + + private void setBookProgress(Book book, UserBookProgressEntity progress) { + if (progress.getKoboProgressPercent() != null) { + book.setKoboProgress(com.adityachandel.booklore.model.dto.progress.KoboProgress.builder() + .percentage(progress.getKoboProgressPercent()) + .build()); + } + + switch (book.getBookType()) { + case EPUB -> { + book.setEpubProgress(com.adityachandel.booklore.model.dto.progress.EpubProgress.builder() + .cfi(progress.getEpubProgress()) + .percentage(progress.getEpubProgressPercent()) + .build()); + book.setKoreaderProgress(com.adityachandel.booklore.model.dto.progress.KoProgress.builder() + .percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null) + .build()); + } + case PDF -> book.setPdfProgress(com.adityachandel.booklore.model.dto.progress.PdfProgress.builder() + .page(progress.getPdfProgress()) + .percentage(progress.getPdfProgressPercent()) + .build()); + case CBX -> book.setCbxProgress(com.adityachandel.booklore.model.dto.progress.CbxProgress.builder() + .page(progress.getCbxProgress()) + .percentage(progress.getCbxProgressPercent()) + .build()); + } + } + + private Set filterShelvesByUserId(Set shelves, Long userId) { + if (shelves == null) return Collections.emptySet(); + return shelves.stream() + .filter(shelf -> userId.equals(shelf.getUserId())) + .collect(Collectors.toSet()); + } +} + diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java index 64495e5ee..68b40cb31 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java @@ -6,9 +6,9 @@ import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.book.BookDownloadService; import com.adityachandel.booklore.service.book.BookQueryService; import com.adityachandel.booklore.service.book.BookService; +import com.adityachandel.booklore.service.book.BookUpdateService; import com.adityachandel.booklore.service.user.UserProgressService; import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; -import com.adityachandel.booklore.service.kobo.KoboReadingStateService; import com.adityachandel.booklore.util.FileService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,17 +41,15 @@ class BookServiceDeleteTests { EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class); CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class); NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class); - ShelfRepository shelfRepository = Mockito.mock(ShelfRepository.class); FileService fileService = Mockito.mock(FileService.class); BookMapper bookMapper = Mockito.mock(BookMapper.class); - UserRepository userRepository = Mockito.mock(UserRepository.class); UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class); AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class); BookQueryService bookQueryService = Mockito.mock(BookQueryService.class); UserProgressService userProgressService = Mockito.mock(UserProgressService.class); BookDownloadService bookDownloadService = Mockito.mock(BookDownloadService.class); MonitoringRegistrationService monitoringRegistrationService = Mockito.mock(MonitoringRegistrationService.class); - KoboReadingStateService koboReadingStateService = Mockito.mock(KoboReadingStateService.class); + BookUpdateService bookUpdateService = Mockito.mock(BookUpdateService.class); bookService = new BookService( bookRepository, @@ -59,17 +57,15 @@ class BookServiceDeleteTests { epubViewerPreferencesRepository, cbxViewerPreferencesRepository, newPdfViewerPreferencesRepository, - shelfRepository, fileService, bookMapper, - userRepository, userBookProgressRepository, authenticationService, bookQueryService, userProgressService, bookDownloadService, monitoringRegistrationService, - koboReadingStateService + bookUpdateService ); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java new file mode 100644 index 000000000..193de3676 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookServiceTest.java @@ -0,0 +1,394 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.*; +import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; +import com.adityachandel.booklore.model.dto.response.BookDeletionResponse; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService; +import com.adityachandel.booklore.service.user.UserProgressService; +import com.adityachandel.booklore.util.FileService; +import com.adityachandel.booklore.util.FileUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class) +class BookServiceTest { + + @Mock private BookRepository bookRepository; + @Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; + @Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository; + @Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; + @Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; + @Mock private FileService fileService; + @Mock private BookMapper bookMapper; + @Mock private UserBookProgressRepository userBookProgressRepository; + @Mock private AuthenticationService authenticationService; + @Mock private BookQueryService bookQueryService; + @Mock private UserProgressService userProgressService; + @Mock private BookDownloadService bookDownloadService; + @Mock private MonitoringRegistrationService monitoringRegistrationService; + @Mock private BookUpdateService bookUpdateService; + + @InjectMocks + private BookService bookService; + + private BookLoreUser testUser; + + @BeforeEach + void setUp() { + BookLoreUser.UserPermissions perms = new BookLoreUser.UserPermissions(); + perms.setAdmin(true); + testUser = BookLoreUser.builder() + .id(1L) + .permissions(perms) + .assignedLibraries(List.of()) + .build(); + } + + @Test + void getBookDTOs_adminUser_returnsBooksWithProgress() { + Book book = Book.builder().id(1L).bookType(BookFileType.PDF).shelves(Set.of()).build(); + when(bookQueryService.getAllBooks(anyBoolean())).thenReturn(List.of(book)); + when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(1L, new UserBookProgressEntity())); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + + List result = bookService.getBookDTOs(true); + + assertEquals(1, result.size()); + verify(bookQueryService).getAllBooks(true); + } + + @Test + void getBooksByIds_returnsMappedBooksWithProgress() { + BookEntity entity = new BookEntity(); + entity.setId(2L); + entity.setBookType(BookFileType.EPUB); + LibraryPathEntity libPath = new LibraryPathEntity(); + libPath.setPath("/tmp/library"); + LibraryEntity library = new LibraryEntity(); + library.setLibraryPaths(List.of(libPath)); + entity.setLibrary(library); + when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of(entity)); + when(userProgressService.fetchUserProgress(anyLong(), anySet())).thenReturn(Map.of(2L, new UserBookProgressEntity())); + Book mappedBook = Book.builder().id(2L).bookType(BookFileType.EPUB).metadata(BookMetadata.builder().build()).build(); + when(bookMapper.toBook(entity)).thenReturn(mappedBook); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + + try (MockedStatic fileUtilsMock = mockStatic(FileUtils.class)) { + fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.epub"); + List result = bookService.getBooksByIds(Set.of(2L), false); + + assertEquals(1, result.size()); + assertEquals(2L, result.get(0).getId()); + } + } + + @Test + void getBook_existingBook_returnsBookWithProgress() { + BookEntity entity = new BookEntity(); + entity.setId(3L); + entity.setBookType(BookFileType.PDF); + LibraryPathEntity libPath = new LibraryPathEntity(); + libPath.setPath("/tmp/library"); + LibraryEntity library = new LibraryEntity(); + library.setLibraryPaths(List.of(libPath)); + entity.setLibrary(library); + when(bookRepository.findById(3L)).thenReturn(Optional.of(entity)); + when(userBookProgressRepository.findByUserIdAndBookId(anyLong(), eq(3L))).thenReturn(Optional.of(new UserBookProgressEntity())); + Book mappedBook = Book.builder().id(3L).bookType(BookFileType.PDF).metadata(BookMetadata.builder().build()).shelves(Set.of()).build(); + when(bookMapper.toBook(entity)).thenReturn(mappedBook); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + + try (MockedStatic fileUtilsMock = mockStatic(FileUtils.class)) { + fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.pdf"); + Book result = bookService.getBook(3L, true); + assertEquals(3L, result.getId()); + verify(bookRepository).findById(3L); + } + } + + @Test + void getBook_notFound_throwsException() { + when(bookRepository.findById(99L)).thenReturn(Optional.empty()); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + assertThrows(APIException.class, () -> bookService.getBook(99L, true)); + } + + @Test + void getBookViewerSetting_epub_returnsEpubSettings() { + BookEntity entity = new BookEntity(); + entity.setId(4L); + entity.setBookType(BookFileType.EPUB); + when(bookRepository.findById(4L)).thenReturn(Optional.of(entity)); + EpubViewerPreferencesEntity epubPref = new EpubViewerPreferencesEntity(); + epubPref.setFont("Arial"); + when(epubViewerPreferencesRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref)); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + + BookViewerSettings settings = bookService.getBookViewerSetting(4L); + + assertNotNull(settings.getEpubSettings()); + assertEquals("Arial", settings.getEpubSettings().getFont()); + } + + @Test + void getBookViewerSetting_unsupportedType_throwsException() { + BookEntity entity = new BookEntity(); + entity.setId(5L); + entity.setBookType(null); + when(bookRepository.findById(5L)).thenReturn(Optional.of(entity)); + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + assertThrows(APIException.class, () -> bookService.getBookViewerSetting(5L)); + } + + @Test + void updateBookViewerSetting_delegatesToUpdateService() { + BookViewerSettings settings = BookViewerSettings.builder().build(); + bookService.updateBookViewerSetting(1L, settings); + verify(bookUpdateService).updateBookViewerSetting(1L, settings); + } + + @Test + void updateReadProgress_delegatesToUpdateService() { + ReadProgressRequest req = new ReadProgressRequest(); + bookService.updateReadProgress(req); + verify(bookUpdateService).updateReadProgress(req); + } + + @Test + void updateReadStatus_delegatesToUpdateService() { + List ids = List.of(1L, 2L); + List responses = List.of(new BookStatusUpdateResponse()); + when(bookUpdateService.updateReadStatus(ids, "READ")).thenReturn(responses); + + List result = bookService.updateReadStatus(ids, "READ"); + + assertEquals(responses, result); + } + + @Test + void assignShelvesToBooks_delegatesToUpdateService() { + Set bookIds = Set.of(1L); + Set assign = Set.of(2L); + Set unassign = Set.of(3L); + List books = List.of(Book.builder().id(1L).build()); + when(bookUpdateService.assignShelvesToBooks(bookIds, assign, unassign)).thenReturn(books); + + List result = bookService.assignShelvesToBooks(bookIds, assign, unassign); + + assertEquals(books, result); + } + + @Test + void getBookThumbnail_fileExists_returnsUrlResource() throws Exception { + when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/cover.jpg"); + Path path = Paths.get("/tmp/cover.jpg"); + Files.createFile(path); + try { + Resource res = bookService.getBookThumbnail(1L); + assertTrue(res instanceof UrlResource); + } finally { + Files.deleteIfExists(path); + } + } + + @Test + void getBookThumbnail_fileMissing_returnsDefault() throws Exception { + when(fileService.getThumbnailFile(1L)).thenReturn("/tmp/nonexistent.jpg"); + Resource res = bookService.getBookThumbnail(1L); + assertTrue(res instanceof UrlResource); + } + + @Test + void getBookThumbnail_malformedPath_throwsRuntimeException() { + when(fileService.getThumbnailFile(123L)).thenReturn("\0illegal:path"); + assertThrows(RuntimeException.class, () -> bookService.getBookThumbnail(123L)); + } + + @Test + void getBookCover_fileExists_returnsUrlResource() throws Exception { + when(fileService.getCoverFile(1L)).thenReturn("/tmp/cover2.jpg"); + Path path = Paths.get("/tmp/cover2.jpg"); + Files.createFile(path); + try { + Resource res = bookService.getBookCover(1L); + assertTrue(res instanceof UrlResource); + } finally { + Files.deleteIfExists(path); + } + } + + @Test + void getBookCover_fileMissing_returnsClassPathResource() { + when(fileService.getCoverFile(1L)).thenReturn("/tmp/nonexistent2.jpg"); + Resource res = bookService.getBookCover(1L); + assertTrue(res instanceof ClassPathResource); + } + + @Test + void getBookCover_malformedPath_throwsRuntimeException() { + when(fileService.getCoverFile(123L)).thenReturn("\0illegal:path"); + assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L)); + } + + @Test + void getBackgroundImage_returnsResource() { + Resource mockResource = mock(Resource.class); + when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource); + + when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); + + Resource res = bookService.getBackgroundImage(); + + assertEquals(mockResource, res); + } + + @Test + void downloadBook_delegatesToDownloadService() { + ResponseEntity response = ResponseEntity.ok(mock(Resource.class)); + when(bookDownloadService.downloadBook(1L)).thenReturn(response); + + ResponseEntity result = bookService.downloadBook(1L); + + assertEquals(response, result); + } + + @Test + void getBookContent_returnsByteArrayResource() throws Exception { + BookEntity entity = new BookEntity(); + entity.setId(10L); + when(bookRepository.findById(10L)).thenReturn(Optional.of(entity)); + Path path = Paths.get("/tmp/bookcontent.txt"); + Files.write(path, "hello".getBytes()); + try (MockedStatic fileUtilsMock = mockStatic(FileUtils.class)) { + fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn(path.toString()); + ResponseEntity response = bookService.getBookContent(10L); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertArrayEquals("hello".getBytes(), response.getBody().getByteArray()); + } finally { + Files.deleteIfExists(path); + } + } + + @Test + void getBookContent_bookNotFound_throwsException() { + when(bookRepository.findById(404L)).thenReturn(Optional.empty()); + assertThrows(APIException.class, () -> bookService.getBookContent(404L)); + } + + @Test + void getBookContent_fileIoError_throwsIOException() throws Exception { + BookEntity entity = new BookEntity(); + entity.setId(12L); + when(bookRepository.findById(12L)).thenReturn(Optional.of(entity)); + try (MockedStatic fileUtilsMock = mockStatic(FileUtils.class)) { + fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/nonexistentfile.txt"); + assertThrows(java.io.FileNotFoundException.class, () -> bookService.getBookContent(12L)); + } + } + + @Test + void deleteBooks_deletesFilesAndEntities() throws Exception { + BookEntity entity = new BookEntity(); + entity.setId(11L); + LibraryEntity library = new LibraryEntity(); + LibraryPathEntity libPath = new LibraryPathEntity(); + libPath.setPath("/tmp/library"); + library.setLibraryPaths(List.of(libPath)); + entity.setLibrary(library); + Path filePath = Paths.get("/tmp/bookfile.txt"); + Files.createDirectories(filePath.getParent()); + Files.write(filePath, "abc".getBytes()); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(entity)); + doNothing().when(bookRepository).deleteAll(anyList()); + BookEntity spyEntity = spy(entity); + doReturn(filePath).when(spyEntity).getFullFilePath(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(spyEntity)); + + BookDeletionResponse response = bookService.deleteBooks(Set.of(11L)).getBody(); + + assertNotNull(response); + assertTrue(response.getFailedFileDeletions().isEmpty()); + assertEquals(Set.of(11L), response.getDeleted()); + Files.deleteIfExists(filePath); + } + + @Test + void deleteBooks_fileDoesNotExist_deletesEntityOnly() { + BookEntity entity = new BookEntity(); + entity.setId(13L); + LibraryEntity library = new LibraryEntity(); + LibraryPathEntity libPath = new LibraryPathEntity(); + libPath.setPath("/tmp/library"); + library.setLibraryPaths(List.of(libPath)); + entity.setLibrary(library); + + BookEntity spyEntity = spy(entity); + doReturn(Paths.get("/tmp/nonexistentfile.txt")).when(spyEntity).getFullFilePath(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(spyEntity)); + doNothing().when(bookRepository).deleteAll(anyList()); + + BookDeletionResponse response = bookService.deleteBooks(Set.of(13L)).getBody(); + + assertNotNull(response); + assertTrue(response.getFailedFileDeletions().isEmpty()); + assertEquals(Set.of(13L), response.getDeleted()); + } + + @Test + void deleteEmptyParentDirsUpToLibraryFolders_deletesEmptyDirs() throws Exception { + Path root = Files.createTempDirectory("libroot"); + Path subdir = Files.createDirectory(root.resolve("subdir")); + Path file = subdir.resolve(".DS_Store"); + Files.createFile(file); + + Set roots = Set.of(root); + bookService.deleteEmptyParentDirsUpToLibraryFolders(subdir, roots); + + assertFalse(Files.exists(subdir)); + Files.deleteIfExists(root); + } + + @Test + void filterShelvesByUserId_returnsOnlyUserShelves() { + Shelf shelf1 = Shelf.builder().id(1L).userId(1L).build(); + Shelf shelf2 = Shelf.builder().id(2L).userId(2L).build(); + Set shelves = Set.of(shelf1, shelf2); + + Set result = org.springframework.test.util.ReflectionTestUtils.invokeMethod( + bookService, "filterShelvesByUserId", shelves, 1L); + + assertEquals(1, result.size()); + assertTrue(result.contains(shelf1)); + } +} \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java new file mode 100644 index 000000000..98416452e --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/book/BookUpdateServiceTest.java @@ -0,0 +1,343 @@ +package com.adityachandel.booklore.service.book; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.*; +import com.adityachandel.booklore.model.dto.progress.EpubProgress; +import com.adityachandel.booklore.model.dto.progress.PdfProgress; +import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; +import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse; +import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse; +import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.model.enums.ReadStatus; +import com.adityachandel.booklore.model.enums.ResetProgressType; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.kobo.KoboReadingStateService; +import com.adityachandel.booklore.service.user.UserProgressService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +class BookUpdateServiceTest { + + @Mock private BookRepository bookRepository; + @Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; + @Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository; + @Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; + @Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; + @Mock private ShelfRepository shelfRepository; + @Mock private BookMapper bookMapper; + @Mock private UserRepository userRepository; + @Mock private UserBookProgressRepository userBookProgressRepository; + @Mock private AuthenticationService authenticationService; + @Mock private BookQueryService bookQueryService; + @Mock private UserProgressService userProgressService; + @Mock private KoboReadingStateService koboReadingStateService; + + @InjectMocks + private BookUpdateService bookUpdateService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + bookUpdateService = new BookUpdateService( + bookRepository, + pdfViewerPreferencesRepository, + epubViewerPreferencesRepository, + cbxViewerPreferencesRepository, + newPdfViewerPreferencesRepository, + shelfRepository, + bookMapper, + userRepository, + userBookProgressRepository, + authenticationService, + bookQueryService, + userProgressService, + koboReadingStateService + ); + } + + @Test + void updateBookViewerSetting_pdf_shouldUpdatePdfPrefs() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + book.setBookType(BookFileType.PDF); + BookLoreUser user = mock(BookLoreUser.class); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(2L); + + PdfViewerPreferencesEntity pdfPrefs = new PdfViewerPreferencesEntity(); + when(pdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(pdfPrefs)); + BookViewerSettings settings = BookViewerSettings.builder() + .pdfSettings(PdfViewerPreferences.builder() + .zoom("1.5") + .spread("spread") + .build()) + .build(); + + bookUpdateService.updateBookViewerSetting(bookId, settings); + + verify(pdfViewerPreferencesRepository).save(pdfPrefs); + assertEquals("1.5", pdfPrefs.getZoom()); + assertEquals("spread", pdfPrefs.getSpread()); + } + + @Test + void updateBookViewerSetting_epub_shouldUpdateEpubPrefs() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + book.setBookType(BookFileType.EPUB); + BookLoreUser user = mock(BookLoreUser.class); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(2L); + + EpubViewerPreferencesEntity epubPrefs = new EpubViewerPreferencesEntity(); + when(epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs)); + BookViewerSettings settings = BookViewerSettings.builder() + .epubSettings(EpubViewerPreferences.builder() + .font("font") + .fontSize(12) + .theme("theme") + .flow("flow") + .spread("spread") + .letterSpacing(1.2f) + .lineHeight(1.3f) + .build()) + .build(); + + bookUpdateService.updateBookViewerSetting(bookId, settings); + + verify(epubViewerPreferencesRepository).save(epubPrefs); + assertEquals("font", epubPrefs.getFont()); + assertEquals(12, epubPrefs.getFontSize()); + assertEquals("theme", epubPrefs.getTheme()); + assertEquals("flow", epubPrefs.getFlow()); + assertEquals("spread", epubPrefs.getSpread()); + assertEquals(1.2f, epubPrefs.getLetterSpacing()); + assertEquals(1.3f, epubPrefs.getLineHeight()); + } + + @Test + void updateBookViewerSetting_unsupportedType_shouldThrow() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + book.setBookType(null); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(authenticationService.getAuthenticatedUser()).thenReturn(mock(BookLoreUser.class)); + BookViewerSettings settings = BookViewerSettings.builder().build(); + + assertThrows(APIException.class, () -> bookUpdateService.updateBookViewerSetting(bookId, settings)); + } + + @Test + void updateReadProgress_epub_shouldUpdateProgress() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + book.setBookType(BookFileType.EPUB); + BookLoreUser user = mock(BookLoreUser.class); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(2L); + + UserBookProgressEntity progress = new UserBookProgressEntity(); + when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); + + ReadProgressRequest req = new ReadProgressRequest(); + req.setBookId(bookId); + EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build(); + req.setEpubProgress(epubProgress); + + bookUpdateService.updateReadProgress(req); + + verify(userBookProgressRepository).save(progress); + assertEquals("cfi", progress.getEpubProgress()); + assertEquals(ReadStatus.READ, progress.getReadStatus()); + assertEquals(100f, progress.getEpubProgressPercent()); + } + + @Test + void updateReadProgress_pdf_shouldUpdateProgress() { + long bookId = 1L; + BookEntity book = new BookEntity(); + book.setId(bookId); + book.setBookType(BookFileType.PDF); + BookLoreUser user = mock(BookLoreUser.class); + when(bookRepository.findById(bookId)).thenReturn(Optional.of(book)); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(2L); + + UserBookProgressEntity progress = new UserBookProgressEntity(); + when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress)); + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity)); + + ReadProgressRequest req = new ReadProgressRequest(); + req.setBookId(bookId); + PdfProgress pdfProgress = PdfProgress.builder().page(5).percentage(50f).build(); + req.setPdfProgress(pdfProgress); + + bookUpdateService.updateReadProgress(req); + + verify(userBookProgressRepository).save(progress); + assertEquals(5, progress.getPdfProgress()); + assertEquals(ReadStatus.READING, progress.getReadStatus()); + assertEquals(50f, progress.getPdfProgressPercent()); + } + + @Test + void updateReadStatus_shouldUpdateExistingAndCreateNew() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + List bookIds = Arrays.asList(1L, 2L, 3L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(3L); + Set existing = new HashSet<>(Arrays.asList(1L, 2L)); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity)); + + List result = bookUpdateService.updateReadStatus(bookIds, "READ"); + verify(userBookProgressRepository).bulkUpdateReadStatus(eq(1L), eq(new ArrayList<>(existing)), eq(ReadStatus.READ), any(), any()); + verify(userBookProgressRepository).saveAll(anyList()); + assertEquals(3, result.size()); + assertEquals(ReadStatus.READ, result.get(0).getReadStatus()); + } + + @Test + void resetProgress_shouldCallBulkReset() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + List bookIds = Arrays.asList(1L, 2L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); + Set existing = new HashSet<>(bookIds); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + List result = bookUpdateService.resetProgress(bookIds, ResetProgressType.BOOKLORE); + verify(userBookProgressRepository).bulkResetBookloreProgress(eq(1L), eq(new ArrayList<>(bookIds)), any()); + assertEquals(2, result.size()); + } + + @Test + void updatePersonalRating_shouldUpdateAndCreate() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + List bookIds = Arrays.asList(1L, 2L, 3L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(3L); + Set existing = new HashSet<>(Arrays.asList(1L, 2L)); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity)); + + List result = bookUpdateService.updatePersonalRating(bookIds, 5); + verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(existing)), eq(5)); + verify(userBookProgressRepository).saveAll(anyList()); + assertEquals(3, result.size()); + assertEquals(5, result.get(0).getPersonalRating()); + } + + @Test + void resetPersonalRating_shouldUpdateExisting() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + List bookIds = Arrays.asList(1L, 2L); + when(bookRepository.countByIdIn(bookIds)).thenReturn(2L); + Set existing = new HashSet<>(bookIds); + when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing); + + List result = bookUpdateService.resetPersonalRating(bookIds); + verify(userBookProgressRepository).bulkUpdatePersonalRating(eq(1L), eq(new ArrayList<>(bookIds)), isNull()); + assertEquals(2, result.size()); + assertNull(result.get(0).getPersonalRating()); + } + + @Test + void assignShelvesToBooks_shouldAssignAndReturnBooks() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L); + ShelfEntity shelf2 = new ShelfEntity(); shelf2.setId(20L); + userEntity.setShelves(new HashSet<>(Arrays.asList(shelf1, shelf2))); + when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity)); + + Set bookIds = new HashSet<>(Arrays.asList(1L, 2L)); + Set assignIds = new HashSet<>(Collections.singletonList(10L)); + Set unassignIds = new HashSet<>(Collections.singletonList(20L)); + + BookEntity bookEntity1 = spy(new BookEntity()); + bookEntity1.setId(1L); + bookEntity1.setShelves(new HashSet<>()); + LibraryPathEntity libraryPath1 = new LibraryPathEntity(); + libraryPath1.setPath("/mock/path/1"); + doReturn(libraryPath1).when(bookEntity1).getLibraryPath(); + bookEntity1.setFileSubPath("sub1"); + bookEntity1.setFileName("file1.pdf"); + + BookEntity bookEntity2 = spy(new BookEntity()); + bookEntity2.setId(2L); + bookEntity2.setShelves(new HashSet<>()); + LibraryPathEntity libraryPath2 = new LibraryPathEntity(); + libraryPath2.setPath("/mock/path/2"); + doReturn(libraryPath2).when(bookEntity2).getLibraryPath(); + bookEntity2.setFileSubPath("sub2"); + bookEntity2.setFileName("file2.pdf"); + + when(bookQueryService.findAllWithMetadataByIds(bookIds)).thenReturn(Arrays.asList(bookEntity1, bookEntity2)); + ShelfEntity assignShelf = new ShelfEntity(); assignShelf.setId(10L); + when(shelfRepository.findAllById(assignIds)).thenReturn(Collections.singletonList(assignShelf)); + Book mockBook = mock(Book.class); + when(bookMapper.toBook(any())).thenReturn(mockBook); + + when(userProgressService.fetchUserProgress(eq(1L), anySet())).thenReturn(Collections.emptyMap()); + + List result = bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds); + verify(bookRepository).saveAll(anyList()); + assertEquals(2, result.size()); + } + + @Test + void assignShelvesToBooks_shouldThrowIfUnauthorized() { + BookLoreUser user = mock(BookLoreUser.class); + when(authenticationService.getAuthenticatedUser()).thenReturn(user); + when(user.getId()).thenReturn(1L); + + BookLoreUserEntity userEntity = new BookLoreUserEntity(); + ShelfEntity shelf1 = new ShelfEntity(); shelf1.setId(10L); + userEntity.setShelves(new HashSet<>(Collections.singletonList(shelf1))); + when(userRepository.findById(1L)).thenReturn(Optional.of(userEntity)); + + Set bookIds = new HashSet<>(Collections.singletonList(1L)); + Set assignIds = new HashSet<>(Collections.singletonList(99L)); + Set unassignIds = new HashSet<>(); + + assertThrows(APIException.class, () -> bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds)); + } +} diff --git a/booklore-ui/src/app/core/services/post-login-initializer.service.ts b/booklore-ui/src/app/core/services/post-login-initializer.service.ts new file mode 100644 index 000000000..838a053a8 --- /dev/null +++ b/booklore-ui/src/app/core/services/post-login-initializer.service.ts @@ -0,0 +1,29 @@ +import {inject, Injectable} from '@angular/core'; +import {IconService} from '../../shared/services/icon.service'; +import {forkJoin, Observable, of} from 'rxjs'; +import {catchError, map} from 'rxjs/operators'; + +@Injectable({ + providedIn: 'root' +}) +export class PostLoginInitializerService { + + private iconService = inject(IconService); + + initialize(): Observable { + return forkJoin([ + this.preloadIcons(), + ]).pipe( + map(() => undefined) + ); + } + + private preloadIcons(): Observable { + return this.iconService.preloadAllIcons().pipe( + catchError((err) => { + console.error('Failed to preload icons:', err); + return of(void 0); + }) + ); + } +} diff --git a/booklore-ui/src/app/features/book/service/book-patch.service.ts b/booklore-ui/src/app/features/book/service/book-patch.service.ts new file mode 100644 index 000000000..07d6f15bc --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-patch.service.ts @@ -0,0 +1,200 @@ +import {inject, Injectable} from '@angular/core'; +import {HttpClient, HttpParams} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {tap} from 'rxjs/operators'; +import {Book, ReadStatus} from '../model/book.model'; +import {BookStateService} from './book-state.service'; +import {API_CONFIG} from '../../../core/config/api-config'; +import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; +import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from './book.service'; + +@Injectable({ + providedIn: 'root', +}) +export class BookPatchService { + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; + + private http = inject(HttpClient); + private bookStateService = inject(BookStateService); + + updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { + const requestPayload = { + bookIds: Array.from(bookIds), + shelvesToAssign: Array.from(shelvesToAssign), + shelvesToUnassign: Array.from(shelvesToUnassign), + }; + return this.http.post(`${this.url}/shelves`, requestPayload).pipe( + tap(updatedBooks => { + const currentState = this.bookStateService.getCurrentBookState(); + const currentBooks = currentState.books || []; + updatedBooks.forEach(updatedBook => { + const index = currentBooks.findIndex(b => b.id === updatedBook.id); + if (index !== -1) { + currentBooks[index] = updatedBook; + } + }); + this.bookStateService.updateBookState({...currentState, books: [...currentBooks]}); + }) + ); + } + + savePdfProgress(bookId: number, page: number, percentage: number): Observable { + const body = { + bookId: bookId, + pdfProgress: { + page: page, + percentage: percentage + } + }; + return this.http.post(`${this.url}/progress`, body); + } + + saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable { + const body = { + bookId: bookId, + epubProgress: { + cfi: cfi, + percentage: percentage + } + }; + return this.http.post(`${this.url}/progress`, body); + } + + saveCbxProgress(bookId: number, page: number, percentage: number): Observable { + const body = { + bookId: bookId, + cbxProgress: { + page: page, + percentage: percentage + } + }; + return this.http.post(`${this.url}/progress`, body); + } + + updateDateFinished(bookId: number, dateFinished: string | null): Observable { + const body = { + bookId: bookId, + dateFinished: dateFinished + }; + return this.http.post(`${this.url}/progress`, body).pipe( + tap(() => { + const currentState = this.bookStateService.getCurrentBookState(); + if (currentState.books) { + const updatedBooks = currentState.books.map(book => { + if (book.id === bookId) { + return {...book, dateFinished: dateFinished || undefined}; + } + return book; + }); + this.bookStateService.updateBookState({ + ...currentState, + books: updatedBooks + }); + } + }) + ); + } + + resetProgress(bookIds: number | number[], type: ResetProgressType): Observable { + const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; + const params = new HttpParams().set('type', ResetProgressTypes[type]); + + return this.http.post(`${this.url}/reset-progress`, ids, {params}).pipe( + tap(responses => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + const response = responses.find(r => r.bookId === book.id); + if (response) { + return { + ...book, + readStatus: response.readStatus, + readStatusModifiedTime: response.readStatusModifiedTime, + dateFinished: response.dateFinished + }; + } + return book; + }); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + }) + ); + } + + updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable { + const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; + const requestBody = { + bookIds: ids, + status: status + }; + + return this.http.post(`${this.url}/status`, requestBody).pipe( + tap(responses => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + const response = responses.find(r => r.bookId === book.id); + if (response) { + return { + ...book, + readStatus: response.readStatus, + readStatusModifiedTime: response.readStatusModifiedTime, + dateFinished: response.dateFinished + }; + } + return book; + }); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + }) + ); + } + + resetPersonalRating(bookIds: number | number[]): Observable { + const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; + + return this.http.post(`${this.url}/reset-personal-rating`, ids).pipe( + tap(responses => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + const response = responses.find(r => r.bookId === book.id); + if (response) { + return { + ...book, + personalRating: response.personalRating + }; + } + return book; + }); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + }) + ); + } + + updatePersonalRating(bookIds: number | number[], rating: number): Observable { + const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; + + return this.http.put(`${this.url}/personal-rating`, {ids, rating}).pipe( + tap(responses => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + const response = responses.find(r => r.bookId === book.id); + if (response) { + return { + ...book, + personalRating: response.personalRating + }; + } + return book; + }); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + }) + ); + } + + updateLastReadTime(bookId: number): void { + const timestamp = new Date().toISOString(); + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => + book.id === bookId ? {...book, lastReadTime: timestamp} : book + ); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + } +} + diff --git a/booklore-ui/src/app/features/book/service/book-socket.service.ts b/booklore-ui/src/app/features/book/service/book-socket.service.ts new file mode 100644 index 000000000..e2f294715 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-socket.service.ts @@ -0,0 +1,71 @@ +import {inject, Injectable} from '@angular/core'; +import {BookStateService} from './book-state.service'; +import {Book, BookMetadata} from '../model/book.model'; + +@Injectable({ + providedIn: 'root', +}) +export class BookSocketService { + private bookStateService = inject(BookStateService); + + handleNewlyCreatedBook(book: Book): void { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = currentState.books ? [...currentState.books] : []; + const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id); + if (bookIndex > -1) { + updatedBooks[bookIndex] = book; + } else { + updatedBooks.push(book); + } + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + } + + handleRemovedBookIds(removedBookIds: number[]): void { + const currentState = this.bookStateService.getCurrentBookState(); + const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id)); + this.bookStateService.updateBookState({...currentState, books: filteredBooks}); + } + + handleBookUpdate(updatedBook: Book): void { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => + book.id === updatedBook.id ? updatedBook : book + ); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + } + + handleMultipleBookUpdates(updatedBooks: Book[]): void { + const currentState = this.bookStateService.getCurrentBookState(); + const currentBooks = currentState.books || []; + + const updatedMap = new Map(updatedBooks.map(book => [book.id, book])); + + const mergedBooks = currentBooks.map(book => + updatedMap.has(book.id) ? updatedMap.get(book.id)! : book + ); + + this.bookStateService.updateBookState({...currentState, books: mergedBooks}); + } + + handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + return book.id === bookId ? {...book, metadata: updatedMetadata} : book; + }); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + } + + handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void { + if (!patches || patches.length === 0) return; + const currentState = this.bookStateService.getCurrentBookState(); + const books = currentState.books || []; + patches.forEach(p => { + const index = books.findIndex(b => b.id === p.id); + if (index !== -1 && books[index].metadata) { + books[index].metadata.coverUpdatedOn = p.coverUpdatedOn; + } + }); + this.bookStateService.updateBookState({...currentState, books}); + } +} + diff --git a/booklore-ui/src/app/features/book/service/book-state.service.ts b/booklore-ui/src/app/features/book/service/book-state.service.ts new file mode 100644 index 000000000..114849374 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-state.service.ts @@ -0,0 +1,40 @@ +import {Injectable} from '@angular/core'; +import {BehaviorSubject, Observable} from 'rxjs'; +import {BookState} from '../model/state/book-state.model'; + +@Injectable({ + providedIn: 'root', +}) +export class BookStateService { + private bookStateSubject = new BehaviorSubject({ + books: null, + loaded: false, + error: null, + }); + + public readonly bookState$ = this.bookStateSubject.asObservable(); + + getCurrentBookState(): BookState { + return this.bookStateSubject.value; + } + + updateBookState(state: BookState): void { + this.bookStateSubject.next(state); + } + + updatePartialBookState(partialState: Partial): void { + this.bookStateSubject.next({ + ...this.bookStateSubject.value, + ...partialState + }); + } + + resetBookState(): void { + this.bookStateSubject.next({ + books: null, + loaded: true, + error: null, + }); + } +} + diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index 8f6e720ba..f5a212dee 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -1,17 +1,31 @@ import {inject, Injectable} from '@angular/core'; -import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs'; +import {first, Observable, of, throwError} from 'rxjs'; import {HttpClient, HttpParams} from '@angular/common/http'; -import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators'; -import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus, AdditionalFileType, AdditionalFile} from '../model/book.model'; +import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, tap} from 'rxjs/operators'; +import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; import {API_CONFIG} from '../../../core/config/api-config'; import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; -import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model'; import {MessageService} from 'primeng/api'; -import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; +import {ResetProgressType} from '../../../shared/constants/reset-progress-type'; import {AuthService} from '../../../shared/service/auth.service'; import {FileDownloadService} from '../../../shared/service/file-download.service'; import {Router} from '@angular/router'; +import {BookStateService} from './book-state.service'; +import {BookSocketService} from './book-socket.service'; +import {BookPatchService} from './book-patch.service'; + +export interface BookStatusUpdateResponse { + bookId: number; + readStatus: ReadStatus; + readStatusModifiedTime: string; + dateFinished?: string; +} + +export interface PersonalRatingUpdateResponse { + bookId: number; + personalRating?: number; +} @Injectable({ providedIn: 'root', @@ -25,12 +39,9 @@ export class BookService { private authService = inject(AuthService); private fileDownloadService = inject(FileDownloadService); private router = inject(Router); - - private bookStateSubject = new BehaviorSubject({ - books: null, - loaded: false, - error: null, - }); + private bookStateService = inject(BookStateService); + private bookSocketService = inject(BookSocketService); + private bookPatchService = inject(BookPatchService); private loading$: Observable | null = null; @@ -39,16 +50,12 @@ export class BookService { distinctUntilChanged() ).subscribe(token => { if (token === null) { - this.bookStateSubject.next({ - books: null, - loaded: true, - error: null, - }); + this.bookStateService.resetBookState(); this.loading$ = null; } else { - const current = this.bookStateSubject.value; + const current = this.bookStateService.getCurrentBookState(); if (current.loaded && !current.books) { - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ books: null, loaded: false, error: null, @@ -59,7 +66,9 @@ export class BookService { }); } - bookState$ = this.bookStateSubject.asObservable().pipe( + /*------------------ State Management ------------------*/ + + bookState$ = this.bookStateService.bookState$.pipe( tap(state => { if (!state.loaded && !state.error && !this.loading$) { this.loading$ = this.fetchBooks().pipe( @@ -72,21 +81,21 @@ export class BookService { ); getCurrentBookState(): BookState { - return this.bookStateSubject.value; + return this.bookStateService.getCurrentBookState(); } private fetchBooks(): Observable { return this.http.get(this.url).pipe( tap(books => { - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ books: books || [], loaded: true, error: null, }); }), catchError(error => { - const curr = this.bookStateSubject.value; - this.bookStateSubject.next({ + const curr = this.bookStateService.getCurrentBookState(); + this.bookStateService.updateBookState({ books: curr.books, loaded: true, error: error.message, @@ -99,14 +108,14 @@ export class BookService { refreshBooks(): void { this.http.get(this.url).pipe( tap(books => { - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ books: books || [], loaded: true, error: null, }); }), catchError(error => { - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ books: null, loaded: true, error: error.message, @@ -116,118 +125,39 @@ export class BookService { ).subscribe(); } + removeBooksByLibraryId(libraryId: number): void { + const currentState = this.bookStateService.getCurrentBookState(); + const currentBooks = currentState.books || []; + const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId); + this.bookStateService.updateBookState({...currentState, books: filteredBooks}); + } + + removeBooksFromShelf(shelfId: number): void { + const currentState = this.bookStateService.getCurrentBookState(); + const currentBooks = currentState.books || []; + const updatedBooks = currentBooks.map(book => ({ + ...book, + shelves: book.shelves?.filter(shelf => shelf.id !== shelfId), + })); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); + } + + /*------------------ Book Retrieval ------------------*/ + getBookByIdFromState(bookId: number): Book | undefined { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); return currentState.books?.find(book => +book.id === +bookId); } getBooksByIdsFromState(bookIds: number[]): Book[] { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); if (!currentState.books || bookIds.length === 0) return []; const idSet = new Set(bookIds.map(id => +id)); return currentState.books.filter(book => idSet.has(+book.id)); } - updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { - const requestPayload = { - bookIds: Array.from(bookIds), - shelvesToAssign: Array.from(shelvesToAssign), - shelvesToUnassign: Array.from(shelvesToUnassign), - }; - return this.http.post(`${this.url}/shelves`, requestPayload).pipe( - map(updatedBooks => { - const currentState = this.bookStateSubject.value; - const currentBooks = currentState.books || []; - updatedBooks.forEach(updatedBook => { - const index = currentBooks.findIndex(b => b.id === updatedBook.id); - if (index !== -1) { - currentBooks[index] = updatedBook; - } - }); - this.bookStateSubject.next({...currentState, books: [...currentBooks]}); - return updatedBooks; - }), - catchError(error => { - const currentState = this.bookStateSubject.value; - this.bookStateSubject.next({...currentState, error: error.message}); - throw error; - }) - ); - } - - removeBooksByLibraryId(libraryId: number): void { - const currentState = this.bookStateSubject.value; - const currentBooks = currentState.books || []; - const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId); - this.bookStateSubject.next({...currentState, books: filteredBooks}); - } - - removeBooksFromShelf(shelfId: number): void { - const currentState = this.bookStateSubject.value; - const currentBooks = currentState.books || []; - const updatedBooks = currentBooks.map(book => ({ - ...book, - shelves: book.shelves?.filter(shelf => shelf.id !== shelfId), - })); - this.bookStateSubject.next({...currentState, books: updatedBooks}); - } - - getBookSetting(bookId: number): Observable { - return this.http.get(`${this.url}/${bookId}/viewer-setting`); - } - - updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable { - return this.http.put(`${this.url}/${bookId}/viewer-setting`, bookSetting); - } - - updateLastReadTime(bookId: number) { - const timestamp = new Date().toISOString(); - const currentState = this.bookStateSubject.value; - const updatedBooks = (currentState.books || []).map(book => - book.id === bookId ? {...book, lastReadTime: timestamp} : book - ); - this.bookStateSubject.next({...currentState, books: updatedBooks}); - } - - readBook(bookId: number, reader?: 'ngx' | 'streaming'): void { - const book = this.bookStateSubject.value.books?.find(b => b.id === bookId); - if (!book) { - console.error('Book not found'); - return; - } - - let url: string; - - switch (book.bookType) { - case 'PDF': - url = !reader || reader === 'ngx' - ? `/pdf-reader/book/${book.id}` - : `/cbx-reader/book/${book.id}`; - break; - - case 'EPUB': - url = `/epub-reader/book/${book.id}`; - break; - - case 'CBX': - url = `/cbx-reader/book/${book.id}`; - break; - - default: - console.error('Unsupported book type:', book.bookType); - return; - } - - this.router.navigate([url]); - this.updateLastReadTime(book.id); - } - - getFileContent(bookId: number): Observable { - return this.http.get(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'}); - } - - getBookByIdFromAPI(bookId: number, withDescription: boolean) { + getBookByIdFromAPI(bookId: number, withDescription: boolean): Observable { return this.http.get(`${this.url}/${bookId}`, { params: { withDescription: withDescription.toString() @@ -235,18 +165,44 @@ export class BookService { }); } + getBooksInSeries(bookId: number): Observable { + return this.bookStateService.bookState$.pipe( + filter(state => state.loaded), + first(), + map(state => { + const allBooks = state.books || []; + const currentBook = allBooks.find(b => b.id === bookId); + + if (!currentBook || !currentBook.metadata?.seriesName) { + return []; + } + + const seriesName = currentBook.metadata.seriesName.toLowerCase(); + return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName); + }) + ); + } + + getBookRecommendations(bookId: number, limit: number = 20): Observable { + return this.http.get(`${this.url}/${bookId}/recommendations`, { + params: {limit: limit.toString()} + }); + } + + /*------------------ Book Operations ------------------*/ + deleteBooks(ids: Set): Observable { const idList = Array.from(ids); const params = new HttpParams().set('ids', idList.join(',')); return this.http.delete(this.url, {params}).pipe( tap(response => { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); const remainingBooks = (currentState.books || []).filter( book => !ids.has(book.id) ); - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ books: remainingBooks, loaded: true, error: null, @@ -277,11 +233,72 @@ export class BookService { ); } + updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { + return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign).pipe( + catchError(error => { + const currentState = this.bookStateService.getCurrentBookState(); + this.bookStateService.updateBookState({...currentState, error: error.message}); + throw error; + }) + ); + } + + /*------------------ Reading & Viewer Settings ------------------*/ + + readBook(bookId: number, reader: 'ngx' | 'streaming' = 'ngx'): void { + const book = this.bookStateService + .getCurrentBookState() + .books?.find(b => b.id === bookId); + + if (!book) { + console.error('Book not found'); + return; + } + + const baseUrl = + book.bookType === 'PDF' + ? reader === 'ngx' + ? 'pdf-reader' + : 'cbx-reader' + : book.bookType === 'EPUB' + ? 'epub-reader' + : book.bookType === 'CBX' + ? 'cbx-reader' + : null; + + if (!baseUrl) { + console.error('Unsupported book type:', book.bookType); + return; + } + + this.router.navigate([`/${baseUrl}/book/${book.id}`]); + this.updateLastReadTime(book.id); + } + + getBookSetting(bookId: number): Observable { + return this.http.get(`${this.url}/${bookId}/viewer-setting`); + } + + updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable { + return this.http.put(`${this.url}/${bookId}/viewer-setting`, bookSetting); + } + + /*------------------ File Operations ------------------*/ + + getFileContent(bookId: number): Observable { + return this.http.get(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'}); + } + + downloadFile(book: Book): void { + const downloadUrl = `${this.url}/${book.id}/download`; + this.fileDownloadService.downloadFile(downloadUrl, book.fileName!); + } + deleteAdditionalFile(bookId: number, fileId: number): Observable { const deleteUrl = `${this.url}/${bookId}/files/${fileId}`; return this.http.delete(deleteUrl).pipe( tap(() => { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); const updatedBooks = (currentState.books || []).map(book => { if (book.id === bookId) { return { @@ -293,7 +310,7 @@ export class BookService { return book; }); - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ ...currentState, books: updatedBooks }); @@ -325,7 +342,7 @@ export class BookService { return this.http.post(`${this.url}/${bookId}/files`, formData).pipe( tap((newFile) => { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); const updatedBooks = (currentState.books || []).map(book => { if (book.id === bookId) { const updatedBook = {...book}; @@ -339,7 +356,7 @@ export class BookService { return book; }); - this.bookStateSubject.next({ + this.bookStateService.updateBookState({ ...currentState, books: updatedBooks }); @@ -361,96 +378,53 @@ export class BookService { ); } - downloadFile(book: Book): void { - const downloadUrl = `${this.url}/${book.id}/download`; - this.fileDownloadService.downloadFile(downloadUrl, book.fileName!); - } - downloadAdditionalFile(book: Book, fileId: number): void { const additionalFile = book.alternativeFormats!.find((f: AdditionalFile) => f.id === fileId); const downloadUrl = `${this.url}/${additionalFile!.id}/files/${fileId}/download`; this.fileDownloadService.downloadFile(downloadUrl, additionalFile!.fileName!); } + /*------------------ Progress & Status Tracking ------------------*/ + + updateLastReadTime(bookId: number): void { + this.bookPatchService.updateLastReadTime(bookId); + } + savePdfProgress(bookId: number, page: number, percentage: number): Observable { - const body = { - bookId: bookId, - pdfProgress: { - page: page, - percentage: percentage - } - } - return this.http.post(`${this.url}/progress`, body); + return this.bookPatchService.savePdfProgress(bookId, page, percentage); } saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable { - const body = { - bookId: bookId, - epubProgress: { - cfi: cfi, - percentage: percentage - } - }; - return this.http.post(`${this.url}/progress`, body); + return this.bookPatchService.saveEpubProgress(bookId, cfi, percentage); } saveCbxProgress(bookId: number, page: number, percentage: number): Observable { - const body = { - bookId: bookId, - cbxProgress: { - page: page, - percentage: percentage - } - }; - return this.http.post(`${this.url}/progress`, body); + return this.bookPatchService.saveCbxProgress(bookId, page, percentage); } updateDateFinished(bookId: number, dateFinished: string | null): Observable { - const body = { - bookId: bookId, - dateFinished: dateFinished - }; - return this.http.post(`${this.url}/progress`, body).pipe( - tap(() => { - // Update the book in the state - const currentState = this.bookStateSubject.value; - if (currentState.books) { - const updatedBooks = currentState.books.map(book => { - if (book.id === bookId) { - return {...book, dateFinished: dateFinished || undefined}; - } - return book; - }); - this.bookStateSubject.next({ - ...currentState, - books: updatedBooks - }); - } - }) - ); + return this.bookPatchService.updateDateFinished(bookId, dateFinished); } - regenerateCovers(): Observable { - return this.http.post(`${this.url}/regenerate-covers`, {}); + resetProgress(bookIds: number | number[], type: ResetProgressType): Observable { + return this.bookPatchService.resetProgress(bookIds, type); } - regenerateCover(bookId: number): Observable { - return this.http.post(`${this.url}/${bookId}/regenerate-cover`, {}); + updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable { + return this.bookPatchService.updateBookReadStatus(bookIds, status); } - regenerateCoversForBooks(bookIds: number[]): Observable { - return this.http.post(`${this.url}/bulk-regenerate-covers`, { bookIds }); + /*------------------ Personal Rating ------------------*/ + + resetPersonalRating(bookIds: number | number[]): Observable { + return this.bookPatchService.resetPersonalRating(bookIds); } - bulkUploadCover(bookIds: number[], file: File): Observable { - const formData = new FormData(); - formData.append('file', file); - formData.append('bookIds', bookIds.join(',')); - return this.http.post(`${this.url}/bulk-upload-cover`, formData); + updatePersonalRating(bookIds: number | number[], rating: number): Observable { + return this.bookPatchService.updatePersonalRating(bookIds, rating); } - - /*------------------ All the metadata related calls go here ------------------*/ + /*------------------ Metadata Operations ------------------*/ fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable { return this.http.post(`${this.url}/${bookId}/metadata/prospective`, request); @@ -458,12 +432,7 @@ export class BookService { updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable { const params = new HttpParams().set('mergeCategories', mergeCategories.toString()); - return this.http.put(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe( - map(updatedMetadata => { - this.handleBookMetadataUpdate(bookId!, updatedMetadata); - return updatedMetadata; - }) - ); + return this.http.put(`${this.url}/${bookId}/metadata`, wrapper, {params}); } updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable { @@ -479,12 +448,12 @@ export class BookService { }; return this.http.put(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe( tap((updatedMetadataList) => { - const currentState = this.bookStateSubject.value; + const currentState = this.bookStateService.getCurrentBookState(); const updatedBooks = (currentState.books || []).map(book => { const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id); return updatedMetadata ? {...book, metadata: updatedMetadata} : book; }); - this.bookStateSubject.next({...currentState, books: updatedBooks}); + this.bookStateService.updateBookState({...currentState, books: updatedBooks}); }), map(() => void 0), catchError((error) => { @@ -493,73 +462,43 @@ export class BookService { ); } - getUploadCoverUrl(bookId: number): string { - return this.url + '/' + bookId + "/metadata/cover/upload" - } + toggleFieldLocks(bookIds: number[] | Set, fieldActions: Record): Observable { + const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds); - uploadCoverFromUrl(bookId: number, url: string): Observable { - return this.http - .post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}) - .pipe( - tap(updatedMetadata => - this.handleBookMetadataUpdate(bookId, updatedMetadata) - ) - ); - } + const requestBody = { + bookIds: Array.from(bookIdSet), + fieldActions + }; - getBookRecommendations(bookId: number, limit: number = 20): Observable { - return this.http.get(`${this.url}/${bookId}/recommendations`, { - params: {limit: limit.toString()} - }); - } - - getBooksInSeries(bookId: number): Observable { - return this.bookStateSubject.asObservable().pipe( - filter(state => state.loaded), - first(), - map(state => { - const allBooks = state.books || []; - const currentBook = allBooks.find(b => b.id === bookId); - - if (!currentBook || !currentBook.metadata?.seriesName) { - return []; - } - - const seriesName = currentBook.metadata.seriesName.toLowerCase(); - return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName); - }) - ); - } - - resetProgress(bookIds: number | number[], type: ResetProgressType): Observable { - const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; - const params = new HttpParams().set('type', ResetProgressTypes[type]); - return this.http.post(`${this.url}/reset-progress`, ids, {params}).pipe( - tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book))) - ); - } - - updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable { - const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; - return this.http.put(`${this.url}/read-status`, {ids, status}).pipe( - tap(updatedBooks => { - updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook)); - }) - ); - } - - resetPersonalRating(bookIds: number | number[]): Observable { - const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; - return this.http.post(`${this.url}/reset-personal-rating`, ids).pipe( - tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book))) - ); - } - - updatePersonalRating(bookIds: number | number[], rating: number): Observable { - const ids = Array.isArray(bookIds) ? bookIds : [bookIds]; - return this.http.put(`${this.url}/personal-rating`, {ids, rating}).pipe( - tap(updatedBooks => { - updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook)); + return this.http.put(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe( + tap(() => { + const currentState = this.bookStateService.getCurrentBookState(); + const updatedBooks = (currentState.books || []).map(book => { + if (!bookIdSet.has(book.id)) return book; + const updatedMetadata = {...book.metadata}; + for (const [field, action] of Object.entries(fieldActions)) { + const lockField = field.endsWith('Locked') ? field : `${field}Locked`; + if (lockField in updatedMetadata) { + (updatedMetadata as any)[lockField] = action === 'LOCK'; + } + } + return { + ...book, + metadata: updatedMetadata + }; + }); + this.bookStateService.updateBookState({ + ...currentState, + books: updatedBooks as Book[] + }); + }), + catchError(error => { + this.messageService.add({ + severity: 'error', + summary: 'Field Lock Update Failed', + detail: 'Failed to update metadata field locks. Please try again.', + }); + throw error; }) ); } @@ -582,113 +521,64 @@ export class BookService { ); } + /*------------------ Cover Operations ------------------*/ - /*------------------ All the websocket handlers go below ------------------*/ + getUploadCoverUrl(bookId: number): string { + return this.url + '/' + bookId + "/metadata/cover/upload" + } + + uploadCoverFromUrl(bookId: number, url: string): Observable { + return this.http + .post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}) + .pipe( + tap(updatedMetadata => + this.handleBookMetadataUpdate(bookId, updatedMetadata) + ) + ); + } + + regenerateCovers(): Observable { + return this.http.post(`${this.url}/regenerate-covers`, {}); + } + + regenerateCover(bookId: number): Observable { + return this.http.post(`${this.url}/${bookId}/regenerate-cover`, {}); + } + + regenerateCoversForBooks(bookIds: number[]): Observable { + return this.http.post(`${this.url}/bulk-regenerate-covers`, {bookIds}); + } + + bulkUploadCover(bookIds: number[], file: File): Observable { + const formData = new FormData(); + formData.append('file', file); + formData.append('bookIds', bookIds.join(',')); + return this.http.post(`${this.url}/bulk-upload-cover`, formData); + } + + /*------------------ Websocket Handlers ------------------*/ handleNewlyCreatedBook(book: Book): void { - const currentState = this.bookStateSubject.value; - const updatedBooks = currentState.books ? [...currentState.books] : []; - const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id); - if (bookIndex > -1) { - updatedBooks[bookIndex] = book; - } else { - updatedBooks.push(book); - } - this.bookStateSubject.next({...currentState, books: updatedBooks}); + this.bookSocketService.handleNewlyCreatedBook(book); } handleRemovedBookIds(removedBookIds: number[]): void { - const currentState = this.bookStateSubject.value; - const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id)); - this.bookStateSubject.next({...currentState, books: filteredBooks}); + this.bookSocketService.handleRemovedBookIds(removedBookIds); } - handleBookUpdate(updatedBook: Book) { - const currentState = this.bookStateSubject.value; - const updatedBooks = (currentState.books || []).map(book => - book.id === updatedBook.id ? updatedBook : book - ); - this.bookStateSubject.next({...currentState, books: updatedBooks}); + handleBookUpdate(updatedBook: Book): void { + this.bookSocketService.handleBookUpdate(updatedBook); } handleMultipleBookUpdates(updatedBooks: Book[]): void { - const currentState = this.bookStateSubject.value; - const currentBooks = currentState.books || []; - - const updatedMap = new Map(updatedBooks.map(book => [book.id, book])); - - const mergedBooks = currentBooks.map(book => - updatedMap.has(book.id) ? updatedMap.get(book.id)! : book - ); - - this.bookStateSubject.next({...currentState, books: mergedBooks}); + this.bookSocketService.handleMultipleBookUpdates(updatedBooks); } - handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata) { - const currentState = this.bookStateSubject.value; - const updatedBooks = (currentState.books || []).map(book => { - return book.id == bookId ? {...book, metadata: updatedMetadata} : book - }); - this.bookStateSubject.next({...currentState, books: updatedBooks}) + handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata): void { + this.bookSocketService.handleBookMetadataUpdate(bookId, updatedMetadata); } - - /** - * Incoming payload: [{ id: number, coverUpdatedOn: "2025-12-25T00:48:17Z" }, ...] - * Apply minimal patch to local state so UI updates the cover image (and can use cache-busting). - */ handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void { - if (!patches || patches.length === 0) return; - const currentState = this.bookStateSubject.value; - const books = currentState.books || []; - patches.forEach(p => { - const index = books.findIndex(b=>b.id === p.id); - if (index !== -1 && books[index].metadata) { - books[index].metadata.coverUpdatedOn = p.coverUpdatedOn; - } - }); - this.bookStateSubject.next({...currentState, books}); + this.bookSocketService.handleMultipleBookCoverPatches(patches); } - - toggleFieldLocks(bookIds: number[] | Set, fieldActions: Record): Observable { - const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds); - - const requestBody = { - bookIds: Array.from(bookIdSet), - fieldActions - }; - - return this.http.put(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe( - tap(() => { - const currentState = this.bookStateSubject.value; - const updatedBooks = (currentState.books || []).map(book => { - if (!bookIdSet.has(book.id)) return book; - const updatedMetadata = {...book.metadata}; - for (const [field, action] of Object.entries(fieldActions)) { - const lockField = field.endsWith('Locked') ? field : `${field}Locked`; - if (lockField in updatedMetadata) { - (updatedMetadata as any)[lockField] = action === 'LOCK'; - } - } - return { - ...book, - metadata: updatedMetadata - }; - }); - this.bookStateSubject.next({ - ...currentState, - books: updatedBooks as Book[] - }); - }), - catchError(error => { - this.messageService.add({ - severity: 'error', - summary: 'Field Lock Update Failed', - detail: 'Failed to update metadata field locks. Please try again.', - }); - throw error; - }) - ); - } - } diff --git a/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.html b/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.html index 11c791e3b..62594c238 100644 --- a/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.html +++ b/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.html @@ -213,5 +213,33 @@ + + +
+
+

+ + Telemetry + +

+
+
+
+
+
+ + + +
+

+ + Help improve Booklore by sharing anonymous usage statistics. This data lets the developers see which features are most used, identify bugs, and spot performance issues so they know what to work on next. No personal information, book content, or any identifiable data is ever sent. Data + is sent to the Booklore server automatically once every 24 hours. It’s completely safe and very helpful to the developers.

+
+
+
+
diff --git a/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.ts b/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.ts index 672cf9bd0..e6e09258d 100644 --- a/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.ts +++ b/booklore-ui/src/app/features/settings/global-preferences/global-preferences.component.ts @@ -11,6 +11,7 @@ import {AppSettingKey, AppSettings, CoverCroppingSettings} from '../../../shared import {filter, take} from 'rxjs/operators'; import {InputText} from 'primeng/inputtext'; import {Slider} from 'primeng/slider'; +import {ExternalDocLinkComponent} from '../../../shared/components/external-doc-link/external-doc-link.component'; @Component({ selector: 'app-global-preferences', @@ -20,7 +21,8 @@ import {Slider} from 'primeng/slider'; ToggleSwitch, FormsModule, InputText, - Slider + Slider, + ExternalDocLinkComponent ], templateUrl: './global-preferences.component.html', styleUrl: './global-preferences.component.scss' @@ -30,6 +32,7 @@ export class GlobalPreferencesComponent implements OnInit { toggles = { autoBookSearch: false, similarBookRecommendation: false, + enableTelemetry: true, }; coverCroppingSettings: CoverCroppingSettings = { @@ -63,6 +66,7 @@ export class GlobalPreferencesComponent implements OnInit { } this.toggles.autoBookSearch = settings.autoBookSearch ?? false; this.toggles.similarBookRecommendation = settings.similarBookRecommendation ?? false; + this.toggles.enableTelemetry = settings?.telemetryEnabled ?? true; }); } @@ -71,6 +75,7 @@ export class GlobalPreferencesComponent implements OnInit { const toggleKeyMap: Record = { autoBookSearch: AppSettingKey.AUTO_BOOK_SEARCH, similarBookRecommendation: AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, + enableTelemetry: AppSettingKey.TELEMETRY_ENABLED, }; const keyToSend = toggleKeyMap[settingKey]; if (keyToSend) { diff --git a/booklore-ui/src/app/features/stats/component/read-status-chart/read-status-chart.component.ts b/booklore-ui/src/app/features/stats/component/read-status-chart/read-status-chart.component.ts index 08c0daf01..e79b1e31e 100644 --- a/booklore-ui/src/app/features/stats/component/read-status-chart/read-status-chart.component.ts +++ b/booklore-ui/src/app/features/stats/component/read-status-chart/read-status-chart.component.ts @@ -13,10 +13,17 @@ interface ReadingStatusStats { percentage: number; } -const CHART_COLORS = [ - '#28a745', '#17a2b8', '#ffc107', '#6f42c1', - '#fd7e14', '#6c757d', '#dc3545', '#343a40', '#e9ecef' -] as const; +const STATUS_COLOR_MAP: Record = { + 'Unread': '#6c757d', // Gray + 'Currently Reading': '#17a2b8', // Cyan + 'Re-reading': '#6f42c1', // Purple + 'Read': '#28a745', // Green + 'Partially Read': '#ffc107', // Yellow + 'Paused': '#fd7e14', // Orange + "Won't Read": '#dc3545', // Red + 'Abandoned': '#e74c3c', // Light Red + 'No Status': '#343a40' // Dark Gray +} as const; const CHART_DEFAULTS = { borderColor: '#ffffff', @@ -89,7 +96,7 @@ export class ReadStatusChartComponent implements OnInit, OnDestroy { labels: [], datasets: [{ data: [], - backgroundColor: [...CHART_COLORS], + backgroundColor: [...Object.values(STATUS_COLOR_MAP)], ...CHART_DEFAULTS }] }); @@ -122,7 +129,7 @@ export class ReadStatusChartComponent implements OnInit, OnDestroy { try { const labels = stats.map(s => s.status); const dataValues = stats.map(s => s.count); - const colors = this.getColorsForData(stats.length); + const colors = stats.map(s => STATUS_COLOR_MAP[s.status] || '#6c757d'); this.chartDataSubject.next({ labels, @@ -137,14 +144,6 @@ export class ReadStatusChartComponent implements OnInit, OnDestroy { } } - private getColorsForData(dataLength: number): string[] { - const colors = [...CHART_COLORS]; - while (colors.length < dataLength) { - colors.push(...CHART_COLORS); - } - return colors.slice(0, dataLength); - } - private calculateReadingStatusStats(): ReadingStatusStats[] { const currentState = this.bookService.getCurrentBookState(); @@ -246,4 +245,3 @@ export class ReadStatusChartComponent implements OnInit, OnDestroy { return `${label}: ${value} books (${percentage}%)`; } } - diff --git a/booklore-ui/src/app/features/stats/component/reading-progress-chart/reading-progress-chart.component.ts b/booklore-ui/src/app/features/stats/component/reading-progress-chart/reading-progress-chart.component.ts index af1be6053..7af8d6f31 100644 --- a/booklore-ui/src/app/features/stats/component/reading-progress-chart/reading-progress-chart.component.ts +++ b/booklore-ui/src/app/features/stats/component/reading-progress-chart/reading-progress-chart.component.ts @@ -14,7 +14,12 @@ interface ReadingProgressStats { } const CHART_COLORS = [ - '#6c757d', '#ffc107', '#fd7e14', '#17a2b8', '#6f42c1', '#28a745' + '#6c757d', // Gray - Not Started (0%) + '#ffc107', // Yellow - Just Started (1-25%) + '#fd7e14', // Orange - Getting Into It (26-50%) + '#17a2b8', // Cyan - Halfway Through (51-75%) + '#6f42c1', // Purple - Almost Finished (76-99%) + '#28a745' // Green - Completed (100%) ] as const; const CHART_DEFAULTS = { diff --git a/booklore-ui/src/app/shared/components/external-doc-link/external-doc-link.component.ts b/booklore-ui/src/app/shared/components/external-doc-link/external-doc-link.component.ts index c86419348..f2f4552fc 100644 --- a/booklore-ui/src/app/shared/components/external-doc-link/external-doc-link.component.ts +++ b/booklore-ui/src/app/shared/components/external-doc-link/external-doc-link.component.ts @@ -3,7 +3,7 @@ import {Tooltip} from 'primeng/tooltip'; export type DocType = 'kobo' | 'opds' | 'metadataManager' | 'koReader' | 'email' | 'amazonCookie' | 'fetchConfig' | 'hardcover' | 'taskManagement' | 'fileNamePatterns' - | 'authentication'; + | 'authentication' | 'telemetry'; @Component({ selector: 'app-external-doc-link', @@ -39,6 +39,7 @@ export class ExternalDocLinkComponent { taskManagement: `${this.BASE_URL}/tools/task-manager`, fileNamePatterns: `${this.BASE_URL}/metadata/file-naming-patterns`, authentication: `${this.BASE_URL}/authentication/overview#setting-up-oidc`, + telemetry: `${this.BASE_URL}/tools/telemetry` }; @Input() docType!: DocType; diff --git a/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts b/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts index a2d9d5473..ba6a9b890 100644 --- a/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts +++ b/booklore-ui/src/app/shared/components/icon-display/icon-display.component.ts @@ -12,7 +12,7 @@ import {DomSanitizer, SafeHtml} from '@angular/platform-browser'; template: ` @if (icon) { @if (icon.type === 'PRIME_NG') { - + } @else {
{ + const fontSize = this.size.endsWith('px') + ? `${parseInt(this.size) * 0.85}px` + : `calc(${this.size} * 0.85)`; + + return { + fontSize: fontSize, + width: this.size, + height: this.size, + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + ...this.iconStyle + }; + } } diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.html b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.html index 8ea7b8db8..2fdbee3e1 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.html +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menu.component.html @@ -44,16 +44,20 @@ @if (versionInfo) {
- - {{ versionInfo.current }} - + @if (isSemanticVersion(versionInfo.current)) { + + {{ versionInfo.current }} + + } @else { + {{ versionInfo.current }} + }
- @if (versionInfo.latest && versionInfo.latest !== versionInfo.current) { + @if (isSemanticVersion(versionInfo.current) && versionInfo.latest && versionInfo.latest !== versionInfo.current) {
(array: T[], field: 'name' | 'id', order: 'asc' | 'desc'): T[] { return [...array].sort((a, b) => { const aVal = (a as any)[field] ?? ''; 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 288eac810..0658be95b 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 @@ -56,7 +56,7 @@ {{ item.label }} diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.scss b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.scss index 2cd1cb9d4..f3b8e473e 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.scss +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.scss @@ -71,7 +71,7 @@ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - margin-left: 0.5rem; + margin-left: 0.35rem; } .menu-item-end-content { diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.html b/booklore-ui/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.html index 9e6e82fa2..4544550f3 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.html +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/version-changelog-dialog/version-changelog-dialog.component.html @@ -11,7 +11,7 @@ } @if (!loading && changelog.length > 0) { -
+
@for (release of changelog; track release) {

diff --git a/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.html b/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.html index 4bfc5644f..1b67a1038 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.html +++ b/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.html @@ -59,7 +59,12 @@ (click)="shouldShowStatsMenu ? statsMenu.toggle($event) : handleStatsButtonClick($event)" [pTooltip]="statsTooltip" tooltipPosition="bottom"> - + + + + + + @if (shouldShowStatsMenu) { @@ -213,7 +218,12 @@ class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded" (click)="shouldShowStatsMenu ? statsMenuMobile.toggle($event) : handleStatsButtonClick($event)" > - + + + + + + Charts @if (shouldShowStatsMenu) { diff --git a/booklore-ui/src/app/shared/model/app-settings.model.ts b/booklore-ui/src/app/shared/model/app-settings.model.ts index e91ca2d92..05ffd65a1 100644 --- a/booklore-ui/src/app/shared/model/app-settings.model.ts +++ b/booklore-ui/src/app/shared/model/app-settings.model.ts @@ -135,6 +135,7 @@ export interface AppSettings { koboSettings: KoboSettings; coverCroppingSettings: CoverCroppingSettings; metadataDownloadOnBookdrop: boolean; + telemetryEnabled: boolean; } export enum AppSettingKey { @@ -155,5 +156,6 @@ export enum AppSettingKey { METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP', METADATA_PUBLIC_REVIEWS_SETTINGS = 'METADATA_PUBLIC_REVIEWS_SETTINGS', KOBO_SETTINGS = 'KOBO_SETTINGS', - COVER_CROPPING_SETTINGS = 'COVER_CROPPING_SETTINGS' + COVER_CROPPING_SETTINGS = 'COVER_CROPPING_SETTINGS', + TELEMETRY_ENABLED = 'TELEMETRY_ENABLED', } diff --git a/booklore-ui/src/app/shared/service/auth.service.ts b/booklore-ui/src/app/shared/service/auth.service.ts index 826a53ea4..97bdfa9e7 100644 --- a/booklore-ui/src/app/shared/service/auth.service.ts +++ b/booklore-ui/src/app/shared/service/auth.service.ts @@ -6,6 +6,7 @@ import {API_CONFIG} from '../../core/config/api-config'; import {createRxStompConfig} from '../websocket/rx-stomp.config'; import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc'; import {Router} from '@angular/router'; +import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; @Injectable({ providedIn: 'root', @@ -14,23 +15,25 @@ export class AuthService { private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/auth`; private rxStompService?: RxStompService; + private postLoginInitialized = false; private http = inject(HttpClient); private injector = inject(Injector); private oAuthService = inject(OAuthService); private oAuthStorage = inject(OAuthStorage); private router = inject(Router); + private postLoginInitializer = inject(PostLoginInitializerService); public tokenSubject = new BehaviorSubject(this.getOidcAccessToken() || this.getInternalAccessToken()); public token$ = this.tokenSubject.asObservable(); - internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> { return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe( tap((response) => { if (response.accessToken && response.refreshToken) { this.saveInternalTokens(response.accessToken, response.refreshToken); this.initializeWebSocketConnection(); + this.handleSuccessfulAuth(); } }) ); @@ -53,6 +56,7 @@ export class AuthService { if (response.accessToken && response.refreshToken) { this.saveInternalTokens(response.accessToken, response.refreshToken); this.initializeWebSocketConnection(); + this.handleSuccessfulAuth(); } }) ); @@ -93,9 +97,8 @@ export class AuthService { this.oAuthStorage.removeItem("refresh_token"); this.oAuthStorage.removeItem("id_token"); this.tokenSubject.next(null); + this.postLoginInitialized = false; this.getRxStompService().deactivate(); - - // Force reload so user's data is not cached for next user that logs in window.location.href = '/login'; } @@ -114,6 +117,19 @@ export class AuthService { const config = createRxStompConfig(this); stompService.updateConfig(config); stompService.activate(); + + if (!this.postLoginInitialized) { + this.handleSuccessfulAuth(); + } + } + + private handleSuccessfulAuth() { + if (this.postLoginInitialized) return; + this.postLoginInitialized = true; + this.postLoginInitializer.initialize().subscribe({ + next: () => console.log('AuthService: Post-login initialization completed'), + error: (err) => console.error('AuthService: Post-login initialization failed:', err) + }); } } diff --git a/booklore-ui/src/app/shared/services/dialog-launcher.service.ts b/booklore-ui/src/app/shared/services/dialog-launcher.service.ts index e9ef82ee7..32119ffc6 100644 --- a/booklore-ui/src/app/shared/services/dialog-launcher.service.ts +++ b/booklore-ui/src/app/shared/services/dialog-launcher.service.ts @@ -145,7 +145,7 @@ export class DialogLauncherService { openVersionChangelogDialog(): DynamicDialogRef | null { return this.openDialog(VersionChangelogDialogComponent, { header: "What's New", - styleClass: 'dialog-maximal', + styleClass: 'dialog-medium', }); } diff --git a/booklore-ui/src/assets/layout/styles/layout/_topbar.scss b/booklore-ui/src/assets/layout/styles/layout/_topbar.scss index a746c878a..f09d58b34 100644 --- a/booklore-ui/src/assets/layout/styles/layout/_topbar.scss +++ b/booklore-ui/src/assets/layout/styles/layout/_topbar.scss @@ -164,3 +164,9 @@ .half-title { color: var(--primary-color); } + +.multi-color-chart-icon { + width: 1.3rem; + height: 1.3rem; + display: inline-block; +} diff --git a/booklore-ui/src/main.ts b/booklore-ui/src/main.ts index cefe2c07c..e0fa0c2ac 100644 --- a/booklore-ui/src/main.ts +++ b/booklore-ui/src/main.ts @@ -19,8 +19,6 @@ import {initializeAuthFactory} from './app/core/security/auth-initializer'; import {StartupService} from './app/shared/service/startup.service'; import {provideCharts, withDefaultRegisterables} from 'ng2-charts'; import ChartDataLabels from 'chartjs-plugin-datalabels'; -import {IconService} from './app/shared/services/icon.service'; -import {firstValueFrom} from 'rxjs'; export function storageFactory(): OAuthStorage { return localStorage; @@ -38,10 +36,6 @@ bootstrapApplication(AppComponent, { const startup = inject(StartupService); return startup.load(); }), - provideAppInitializer(() => { - const iconService = inject(IconService); - return firstValueFrom(iconService.preloadAllIcons()); - }), provideHttpClient(withInterceptors([AuthInterceptorService])), provideOAuthClient(), {