Refactor book service in BE and FE (#2013)

* Refactor book service in BE and FE

* Add missing method

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2025-12-28 19:37:35 -07:00
committed by GitHub
co-authored by acx10
parent 60095c2173
commit 01446c2537
37 changed files with 2085 additions and 807 deletions
@@ -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<List<Book>> updateReadStatus(
@Parameter(description = "Read status update request") @RequestBody @Valid ReadStatusUpdateRequest request) {
List<Book> updatedBooks = bookService.updateReadStatus(request.ids(), request.status());
return ResponseEntity.ok(updatedBooks);
@PostMapping("/status")
public List<BookStatusUpdateResponse> 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<List<Book>> resetProgress(
public ResponseEntity<List<BookStatusUpdateResponse>> resetProgress(
@Parameter(description = "List of book IDs to reset progress for") @RequestBody List<Long> 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<Book> 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<List<Book>> updatePersonalRating(
public ResponseEntity<List<PersonalRatingUpdateResponse>> updatePersonalRating(
@Parameter(description = "Personal rating update request") @RequestBody @Valid PersonalRatingUpdateRequest request) {
List<Book> 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<List<Book>> resetPersonalRating(
public ResponseEntity<List<PersonalRatingUpdateResponse>> resetPersonalRating(
@Parameter(description = "List of book IDs to reset personal rating for") @RequestBody List<Long> bookIds) {
if (bookIds == null || bookIds.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
}
List<Book> updatedBooks = bookService.resetPersonalRating(bookIds);
List<PersonalRatingUpdateResponse> updatedBooks = bookUpdateService.resetPersonalRating(bookIds);
return ResponseEntity.ok(updatedBooks);
}
}
@@ -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) {
}
}
}
}
@@ -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<Long> ids, String status) {
@Data
public class ReadStatusUpdateRequest {
@NotEmpty(message = "Book IDs cannot be empty")
private List<Long> bookIds;
@NotNull(message = "Status cannot be null")
private String status;
}
@@ -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;
}
@@ -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;
}
@@ -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()),
@@ -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;
@@ -90,22 +90,6 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
""")
List<BookEntity> findBooksWithMetadataAndAuthors(@Param("bookIds") List<Long> 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<BookEntity> 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<BookEntity, Long>, 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<BookEntity> 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<Long> 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);
@@ -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<UserBookProgre
ORDER BY year DESC, month DESC
""")
List<CompletionTimelineDto> 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<Long> 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<Long> findExistingProgressBookIds(@Param("userId") Long userId, @Param("bookIds") Set<Long> 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<Long> 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<Long> 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<Long> 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<Long> bookIds, @Param("rating") Integer rating);
}
@@ -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")));
@@ -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<Book> updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
List<BookEntity> 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<Book> resetProgress(List<Long> bookIds, ResetProgressType type) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> updatedBooks = new ArrayList<>();
Optional<BookLoreUserEntity> 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<Book> updatePersonalRating(List<Long> bookIds, Integer rating) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<BookEntity> 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<Book> resetPersonalRating(List<Long> bookIds) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
List<Book> updatedBooks = new ArrayList<>();
Optional<BookLoreUserEntity> 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<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
return bookUpdateService.updateReadStatus(bookIds, status);
}
@Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
Set<Long> 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<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
for (BookEntity bookEntity : bookEntities) {
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
bookEntity.getShelves().addAll(shelvesToAssign);
}
bookRepository.saveAll(bookEntities);
Map<Long, UserBookProgressEntity> 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());
}
}
}
@@ -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<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
Set<Long> 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<Long> 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<UserBookProgressEntity> 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<BookStatusUpdateResponse> resetProgress(List<Long> bookIds, ResetProgressType type) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> 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<PersonalRatingUpdateResponse> updatePersonalRating(List<Long> bookIds, Integer rating) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
if (!existingProgressBookIds.isEmpty()) {
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), rating);
}
Set<Long> 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<UserBookProgressEntity> 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<PersonalRatingUpdateResponse> resetPersonalRating(List<Long> bookIds) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Set<Long> 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<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
Set<Long> 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<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
for (BookEntity bookEntity : bookEntities) {
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
bookEntity.getShelves().addAll(shelvesToAssign);
}
bookRepository.saveAll(bookEntities);
Map<Long, UserBookProgressEntity> 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<Long> validateBooksAndGetExistingProgress(Long userId, List<Long> 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<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
if (shelves == null) return Collections.emptySet();
return shelves.stream()
.filter(shelf -> userId.equals(shelf.getUserId()))
.collect(Collectors.toSet());
}
}
@@ -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
);
}
@@ -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<Book> 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<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn("/tmp/library/book.epub");
List<Book> 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<FileUtils> 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<Long> ids = List.of(1L, 2L);
List<BookStatusUpdateResponse> responses = List.of(new BookStatusUpdateResponse());
when(bookUpdateService.updateReadStatus(ids, "READ")).thenReturn(responses);
List<BookStatusUpdateResponse> result = bookService.updateReadStatus(ids, "READ");
assertEquals(responses, result);
}
@Test
void assignShelvesToBooks_delegatesToUpdateService() {
Set<Long> bookIds = Set.of(1L);
Set<Long> assign = Set.of(2L);
Set<Long> unassign = Set.of(3L);
List<Book> books = List.of(Book.builder().id(1L).build());
when(bookUpdateService.assignShelvesToBooks(bookIds, assign, unassign)).thenReturn(books);
List<Book> 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<Resource> response = ResponseEntity.ok(mock(Resource.class));
when(bookDownloadService.downloadBook(1L)).thenReturn(response);
ResponseEntity<Resource> 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<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(entity)).thenReturn(path.toString());
ResponseEntity<ByteArrayResource> 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<FileUtils> 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<Path> 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<Shelf> shelves = Set.of(shelf1, shelf2);
Set<Shelf> result = org.springframework.test.util.ReflectionTestUtils.invokeMethod(
bookService, "filterShelvesByUserId", shelves, 1L);
assertEquals(1, result.size());
assertTrue(result.contains(shelf1));
}
}
@@ -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<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> 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<BookStatusUpdateResponse> 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<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<BookStatusUpdateResponse> 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<Long> bookIds = Arrays.asList(1L, 2L, 3L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(3L);
Set<Long> 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<PersonalRatingUpdateResponse> 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<Long> bookIds = Arrays.asList(1L, 2L);
when(bookRepository.countByIdIn(bookIds)).thenReturn(2L);
Set<Long> existing = new HashSet<>(bookIds);
when(userBookProgressRepository.findExistingProgressBookIds(1L, new HashSet<>(bookIds))).thenReturn(existing);
List<PersonalRatingUpdateResponse> 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<Long> bookIds = new HashSet<>(Arrays.asList(1L, 2L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(10L));
Set<Long> 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<Book> 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<Long> bookIds = new HashSet<>(Collections.singletonList(1L));
Set<Long> assignIds = new HashSet<>(Collections.singletonList(99L));
Set<Long> unassignIds = new HashSet<>();
assertThrows(APIException.class, () -> bookUpdateService.assignShelvesToBooks(bookIds, assignIds, unassignIds));
}
}