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:
+23
-23
@@ -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) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-1
@@ -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;
|
||||
}
|
||||
|
||||
+21
@@ -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;
|
||||
}
|
||||
|
||||
+16
@@ -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;
|
||||
}
|
||||
|
||||
+1
@@ -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()),
|
||||
|
||||
+1
@@ -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;
|
||||
|
||||
+11
-24
@@ -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);
|
||||
|
||||
|
||||
+78
@@ -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);
|
||||
}
|
||||
|
||||
+2
-1
@@ -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")));
|
||||
|
||||
+23
-337
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+419
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user