Introduce multi-format book support, including audiobooks (#2486)
* fix: support reading alternative book formats using bookType query param * feat: add streaming reader support for alternative EPUB formats * refactor: extract tabs section into MetadataTabsComponent * feat: implement per-file reading progress tracking * feat: add configurable format priority with cascading fallback * refactor: redesign library creator with single-page layout * refactor: unify reading progress into ReadingProgressService * refactor: improve delete options with clearer file format and book deletion * refactor: improve book format matching with normalization and fuzzy fallback * feat: add folder-based audiobook support with ZIP downloads and preparing state * fix: display unique format types in metadata viewer * refactor: auto-attach files to single book in folder during rescan * feat: implement folder-centric book file grouping with fuzzy matching * refactor: consolidate book grouping with organization mode support * fix: use folder hash for folder-based audiobooks in auto-attach * fix: delete only BookFileEntity on file removal, not entire book * fix: set folderBased flag and correct file size for auto-attached audiobook folders * fix: use count query to avoid lazy initialization in file delete handler * fix: preserve book metadata when file is moved by detecting hash match * fix: skip books with no files in restoration to avoid NPE * fix: round all progress percentages to one decimal place before sending to UI * style: improve library creator dialog spacing and layout * fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility * fix: FileMoveService now handles multi-file BookEntity properly * style: redesign metadata-picker and file-mover UI components * style: redesign file-naming-pattern UI and improve theme contrast * style: relax spacing in library-creator component * style: tighten directory-picker layout for consistency * fix: PathPatternResolver now respects folderBased flag for audiobooks * style: move checkmark column to left side and add pending status in file-mover * refactor: consolidate BookFileType into BookType and add audiobook styling * feat: show 'Continue Reading' button for in-progress books * fix: preserve dots in folder names during grouping and prevent duplicate attachments * style: reduce gap between download-all button and primary file section * style: shorten 'Continue Reading' button to 'Read' on mobile * feat: add DISK_TYPE config to disable file moves on network storage * style: standardize settings pages with shared styles and consistent spacing * style: revamp settings pages with modern card-based layouts * style: revamp OPDS, auth, and task management settings layouts * fix: update FileMoveService tests to include AppProperties parameter * fix: derive BookFileType from extension when uploading additional book files * feat: show format type and size in download button with dropdown for alternatives * feat: add audiobook streaming player with HTTP Range support * feat: add M4B chapter extraction and chapter navigation * feat: add audiobook bookmarks and sleep timer * refactor: split AudiobookReaderService into focused services * feat: add Media Session API for background audio playback * feat: display file extensions in format tags with distinct colors and add audiobook upload support * feat: require bookFileId for viewer settings API * fix: show split button for audiobooks with readable alternatives * feat: improve reading sessions table with book type badges and better formatting * feat: add audiobook play button in files tab * feat: use file extension for format display and meaningful tab values * feat: add extension field to BookFile DTO * feat: use extension field for book card format pill * fix: use mixed orientation for format priority drag-drop to support multi-line layout * feat: add attach book files feature to consolidate single-file books * fix: increase drag handle size for format priority chips * fix: add missing BookFileRepository mock to BookServiceDeleteTests * feat: add delete buttons to files tab and move shelf to other items menu * feat: add physical books support for cataloging books without digital files * refactor: redesign icon-picker component with improved styling * refactor: redesign metadata-picker component with improved layout and alignment * refactor: move Add Physical Book to top of library menu * refactor: use p-autoComplete for authors/categories in add-physical-book dialog * feat: add square cover search and display support for audiobooks * fix: navigate to first page when opening unread ebooks * fix: exclude API requests from service worker interception * feat: support fileless books with automatic file attachment * fix: bypass service worker for audiobook streaming requests * refactor: remove alphabetical filter sorting, default to count, limit filters to 100 --------- Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
@@ -224,6 +224,9 @@ DATABASE_URL=jdbc:mariadb://mariadb:3306/booklore
|
||||
DB_USER=booklore
|
||||
DB_PASSWORD=ChangeMe_BookLoreApp_2025!
|
||||
|
||||
# 💾 Storage type: LOCAL (default) or NETWORK. Set to NETWORK if using NFS/SMB - this disables file reorganization features to prevent data corruption.
|
||||
DISK_TYPE=LOCAL
|
||||
|
||||
# 🔧 MariaDB Container Settings
|
||||
DB_USER_ID=1000
|
||||
DB_GROUP_ID=1000
|
||||
|
||||
@@ -70,6 +70,9 @@ dependencies {
|
||||
|
||||
implementation 'io.documentnode:epub4j-core:4.2.2'
|
||||
|
||||
// --- Audio Metadata (Audiobook Support) ---
|
||||
implementation 'net.jthink:jaudiotagger:3.0.1'
|
||||
|
||||
// --- UNRAR Support ---
|
||||
implementation 'com.github.junrar:junrar:7.5.7'
|
||||
|
||||
|
||||
@@ -18,6 +18,14 @@ public class AppProperties {
|
||||
private Boolean forceDisableOidc = false;
|
||||
private Telemetry telemetry = new Telemetry();
|
||||
|
||||
/**
|
||||
* Type of disk storage where library files are stored.
|
||||
* Defaults to LOCAL. Set to NETWORK if using NFS, SMB/CIFS, or other network-mounted storage.
|
||||
* Some features like file move/reorganization are disabled on network storage due to
|
||||
* unreliable atomic operations that can cause data corruption or loss.
|
||||
*/
|
||||
private String diskType = "LOCAL";
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class RemoteAuth {
|
||||
|
||||
+15
@@ -183,6 +183,21 @@ public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
@Order(7)
|
||||
public SecurityFilterChain audiobookStreamingSecurityChain(HttpSecurity http, AudiobookStreamingJwtFilter audiobookStreamingJwtFilter) throws Exception {
|
||||
http
|
||||
.securityMatcher("/api/v1/audiobook/*/stream/**", "/api/v1/audiobook/*/track/*/stream/**", "/api/v1/audiobook/*/cover")
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(audiobookStreamingJwtFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(8)
|
||||
public SecurityFilterChain jwtApiSecurityChain(HttpSecurity http) throws Exception {
|
||||
List<String> publicEndpoints = new ArrayList<>(Arrays.asList(COMMON_PUBLIC_ENDPOINTS));
|
||||
if (appProperties.getSwagger().isEnabled()) {
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.adityachandel.booklore.config.security.filter;
|
||||
|
||||
import com.adityachandel.booklore.config.security.JwtUtils;
|
||||
import com.adityachandel.booklore.config.security.service.DynamicOidcJwtProcessor;
|
||||
import com.adityachandel.booklore.config.security.userdetails.UserAuthenticationDetails;
|
||||
import com.adityachandel.booklore.mapper.custom.BookLoreUserTransformer;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* JWT filter for audiobook streaming endpoints that supports both:
|
||||
* 1. Authorization header (Bearer token) - for fetch() requests
|
||||
* 2. Query parameter (token) - for HTML5 audio element compatibility
|
||||
*/
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
public class AudiobookStreamingJwtFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Pattern AUDIOBOOK_STREAMING_ENDPOINT_PATTERN =
|
||||
Pattern.compile("/api/v1/audiobook/\\d+/(stream|track/\\d+/stream|cover).*");
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
private final UserRepository userRepository;
|
||||
private final BookLoreUserTransformer bookLoreUserTransformer;
|
||||
private final AppSettingService appSettingService;
|
||||
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
String path = request.getRequestURI();
|
||||
return !AUDIOBOOK_STREAMING_ENDPOINT_PATTERN.matcher(path).matches();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// Try Authorization header first, then fall back to query parameter
|
||||
String token = extractTokenFromHeader(request);
|
||||
if (token == null) {
|
||||
token = request.getParameter("token");
|
||||
}
|
||||
|
||||
if (token == null || token.isEmpty()) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing authentication token");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateLocalUser(token, request);
|
||||
} else if (appSettingService.getAppSettings().isOidcEnabled()) {
|
||||
authenticateOidcUser(token, request);
|
||||
} else {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
|
||||
return;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed: " + ex.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String extractTokenFromHeader(HttpServletRequest request) {
|
||||
String bearer = request.getHeader("Authorization");
|
||||
return (bearer != null && bearer.startsWith("Bearer ")) ? bearer.substring(7) : null;
|
||||
}
|
||||
|
||||
private void authenticateLocalUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
|
||||
private void authenticateOidcUser(String token, HttpServletRequest request) throws Exception {
|
||||
var processor = dynamicOidcJwtProcessor.getProcessor();
|
||||
var claimsSet = processor.process(token, null);
|
||||
|
||||
if (claimsSet.getExpirationTime() == null ||
|
||||
claimsSet.getExpirationTime().toInstant().isBefore(Instant.now())) {
|
||||
throw new RuntimeException("OIDC token expired or invalid");
|
||||
}
|
||||
|
||||
OidcProviderDetails providerDetails = appSettingService.getAppSettings().getOidcProviderDetails();
|
||||
OidcProviderDetails.ClaimMapping claimMapping = providerDetails.getClaimMapping();
|
||||
String username = claimsSet.getStringClaim(claimMapping.getUsername());
|
||||
BookLoreUserEntity entity = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("OIDC user not found: " + username));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
authentication.setDetails(new UserAuthenticationDetails(request, user.getId()));
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.config.security.annotation.CheckBookAccess;
|
||||
import com.adityachandel.booklore.model.dto.response.AudiobookInfo;
|
||||
import com.adityachandel.booklore.service.reader.AudiobookReaderService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/audiobook")
|
||||
@RequiredArgsConstructor
|
||||
@Tag(name = "Audiobook Reader", description = "Endpoints for streaming audiobooks with HTTP Range support")
|
||||
public class AudiobookReaderController {
|
||||
|
||||
private final AudiobookReaderService audiobookReaderService;
|
||||
|
||||
@Operation(summary = "Get audiobook info",
|
||||
description = "Retrieve metadata including duration, chapters/tracks, and audio details for an audiobook.")
|
||||
@ApiResponse(responseCode = "200", description = "Audiobook info returned successfully")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
@GetMapping("/{bookId}/info")
|
||||
public ResponseEntity<AudiobookInfo> getAudiobookInfo(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., AUDIOBOOK)") @RequestParam(required = false) String bookType) {
|
||||
return ResponseEntity.ok(audiobookReaderService.getAudiobookInfo(bookId, bookType));
|
||||
}
|
||||
|
||||
@Operation(summary = "Stream audiobook audio",
|
||||
description = "Stream the audiobook audio file with HTTP Range support for seeking. " +
|
||||
"Uses token query parameter for authentication to support HTML5 audio element.")
|
||||
@ApiResponse(responseCode = "200", description = "Full audio file returned")
|
||||
@ApiResponse(responseCode = "206", description = "Partial content returned (range request)")
|
||||
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||
@GetMapping("/{bookId}/stream")
|
||||
public void streamAudiobook(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
|
||||
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response) throws IOException {
|
||||
|
||||
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
|
||||
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
|
||||
}
|
||||
|
||||
@Operation(summary = "Stream specific track", description = "Stream a specific track from a folder-based audiobook.")
|
||||
@ApiResponse(responseCode = "200", description = "Full track file returned")
|
||||
@ApiResponse(responseCode = "206", description = "Partial content returned (range request)")
|
||||
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
|
||||
@GetMapping("/{bookId}/track/{trackIndex}/stream")
|
||||
public void streamTrack(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex,
|
||||
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response) throws IOException {
|
||||
|
||||
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
|
||||
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get embedded cover art",
|
||||
description = "Extract and return the embedded cover art from the audiobook file. " +
|
||||
"Uses token query parameter for authentication.")
|
||||
@ApiResponse(responseCode = "200", description = "Cover art returned successfully")
|
||||
@ApiResponse(responseCode = "404", description = "No embedded cover art found")
|
||||
@GetMapping("/{bookId}/cover")
|
||||
public ResponseEntity<byte[]> getEmbeddedCover(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType) {
|
||||
|
||||
byte[] coverData = audiobookReaderService.getEmbeddedCoverArt(bookId, bookType);
|
||||
if (coverData == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
String mimeType = audiobookReaderService.getCoverArtMimeType(bookId, bookType);
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.parseMediaType(mimeType));
|
||||
headers.setContentLength(coverData.length);
|
||||
headers.setCacheControl("public, max-age=86400");
|
||||
|
||||
return new ResponseEntity<>(coverData, headers, HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
+63
-6
@@ -5,6 +5,8 @@ import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendation;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.request.AttachBookFileRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.CreatePhysicalBookRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.PersonalRatingUpdateRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadStatusUpdateRequest;
|
||||
@@ -13,15 +15,19 @@ 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.BookFileAttachmentService;
|
||||
import com.adityachandel.booklore.service.book.BookService;
|
||||
import com.adityachandel.booklore.service.book.BookUpdateService;
|
||||
import com.adityachandel.booklore.service.book.PhysicalBookService;
|
||||
import com.adityachandel.booklore.service.metadata.BookMetadataService;
|
||||
import com.adityachandel.booklore.service.progress.ReadingProgressService;
|
||||
import com.adityachandel.booklore.service.recommender.BookRecommendationService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
@@ -45,7 +51,10 @@ public class BookController {
|
||||
private final BookService bookService;
|
||||
private final BookUpdateService bookUpdateService;
|
||||
private final BookRecommendationService bookRecommendationService;
|
||||
private final BookFileAttachmentService bookFileAttachmentService;
|
||||
private final BookMetadataService bookMetadataService;
|
||||
private final ReadingProgressService readingProgressService;
|
||||
private final PhysicalBookService physicalBookService;
|
||||
|
||||
@Operation(summary = "Get all books", description = "Retrieve a list of all books. Optionally include descriptions.")
|
||||
@ApiResponse(responseCode = "200", description = "List of books returned successfully")
|
||||
@@ -69,6 +78,20 @@ public class BookController {
|
||||
return ResponseEntity.ok(bookService.getBook(bookId, withDescription));
|
||||
}
|
||||
|
||||
@Operation(summary = "Create a physical book", description = "Create a physical book without digital files. Requires library management permission or admin.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "201", description = "Physical book created successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request"),
|
||||
@ApiResponse(responseCode = "403", description = "Forbidden"),
|
||||
@ApiResponse(responseCode = "404", description = "Library not found")
|
||||
})
|
||||
@PostMapping("/physical")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Book> createPhysicalBook(
|
||||
@Parameter(description = "Physical book creation request") @RequestBody @Valid CreatePhysicalBookRequest request) {
|
||||
return ResponseEntity.status(201).body(physicalBookService.createPhysicalBook(request));
|
||||
}
|
||||
|
||||
@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"),
|
||||
@@ -102,8 +125,10 @@ public class BookController {
|
||||
@ApiResponse(responseCode = "200", description = "Book content returned successfully")
|
||||
@GetMapping("/{bookId}/content")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
|
||||
return bookService.getBookContent(bookId);
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., EPUB, PDF, MOBI)") @RequestParam(required = false) String bookType) throws IOException {
|
||||
return bookService.getBookContent(bookId, bookType);
|
||||
}
|
||||
|
||||
@Operation(summary = "Download book", description = "Download the book file. Requires download permission or admin.")
|
||||
@@ -118,12 +143,29 @@ public class BookController {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book.")
|
||||
@Operation(summary = "Download all book files", description = "Download all files for a book as a ZIP archive. For single-file books, downloads the file directly. Requires download permission or admin.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Files downloaded successfully"),
|
||||
@ApiResponse(responseCode = "403", description = "Forbidden"),
|
||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||
})
|
||||
@GetMapping("/{bookId}/download-all")
|
||||
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public void downloadAllBookFiles(
|
||||
@Parameter(description = "ID of the book") @PathVariable("bookId") Long bookId,
|
||||
HttpServletResponse response) {
|
||||
bookService.downloadAllBookFiles(bookId, response);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get viewer settings", description = "Retrieve viewer settings for a specific book file.")
|
||||
@ApiResponse(responseCode = "200", description = "Viewer settings returned successfully")
|
||||
@GetMapping("/{bookId}/viewer-setting")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId,
|
||||
@Parameter(description = "ID of the book file") @RequestParam long bookFileId) {
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId, bookFileId));
|
||||
}
|
||||
|
||||
@Operation(summary = "Update viewer settings", description = "Update viewer settings for a specific book.")
|
||||
@@ -183,7 +225,7 @@ public class BookController {
|
||||
if (bookIds == null || bookIds.isEmpty()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("No book IDs provided");
|
||||
}
|
||||
return ResponseEntity.ok(bookUpdateService.resetProgress(bookIds, type));
|
||||
return ResponseEntity.ok(readingProgressService.resetProgress(bookIds, type));
|
||||
}
|
||||
|
||||
@Operation(summary = "Update personal rating", description = "Update the personal rating for one or more books.")
|
||||
@@ -208,4 +250,19 @@ public class BookController {
|
||||
List<PersonalRatingUpdateResponse> updatedBooks = bookUpdateService.resetPersonalRating(bookIds);
|
||||
return ResponseEntity.ok(updatedBooks);
|
||||
}
|
||||
|
||||
@Operation(summary = "Attach book files", description = "Attach book files from single-file source books to a target book as alternative formats.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Book files attached successfully"),
|
||||
@ApiResponse(responseCode = "400", description = "Invalid request - books must be in same library, sources must have exactly one file each"),
|
||||
@ApiResponse(responseCode = "403", description = "Forbidden - requires library management permission"),
|
||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||
})
|
||||
@PostMapping("/{targetBookId}/attach-file")
|
||||
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
|
||||
public ResponseEntity<Book> attachBookFiles(
|
||||
@Parameter(description = "ID of the target book to attach the files to") @PathVariable Long targetBookId,
|
||||
@Parameter(description = "Request containing source book IDs and delete option") @RequestBody @Valid AttachBookFileRequest request) {
|
||||
return ResponseEntity.ok(bookFileAttachmentService.attachBookFiles(targetBookId, request.getSourceBookIds(), request.isDeleteSourceBooks()));
|
||||
}
|
||||
}
|
||||
|
||||
+5
-6
@@ -14,10 +14,7 @@ import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@@ -52,9 +49,10 @@ public class BookMediaController {
|
||||
public void getPdfPage(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType,
|
||||
HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
pdfReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.")
|
||||
@@ -63,9 +61,10 @@ public class BookMediaController {
|
||||
public void getCbxPage(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Page number to retrieve") @PathVariable int pageNumber,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType,
|
||||
HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
cbxReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream());
|
||||
}
|
||||
|
||||
@Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.")
|
||||
|
||||
+9
-8
@@ -7,10 +7,7 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -25,14 +22,18 @@ public class CbxReaderController {
|
||||
@Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX book.")
|
||||
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
|
||||
@GetMapping("/{bookId}/pages")
|
||||
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return cbxReaderService.getAvailablePages(bookId);
|
||||
public List<Integer> listPages(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
|
||||
return cbxReaderService.getAvailablePages(bookId, bookType);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get page info for a CBX book", description = "Retrieve page information including display names for a CBX book.")
|
||||
@ApiResponse(responseCode = "200", description = "Page info returned successfully")
|
||||
@GetMapping("/{bookId}/page-info")
|
||||
public List<CbxPageInfo> getPageInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return cbxReaderService.getPageInfo(bookId);
|
||||
public List<CbxPageInfo> getPageInfo(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
|
||||
return cbxReaderService.getPageInfo(bookId, bookType);
|
||||
}
|
||||
}
|
||||
+10
-9
@@ -10,10 +10,8 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -32,8 +30,10 @@ public class EpubReaderController {
|
||||
description = "Retrieve parsed metadata, spine, manifest, and TOC for an EPUB book.")
|
||||
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
|
||||
@GetMapping("/{bookId}/info")
|
||||
public ResponseEntity<EpubBookInfo> getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return ResponseEntity.ok(epubReaderService.getBookInfo(bookId));
|
||||
public ResponseEntity<EpubBookInfo> getBookInfo(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType) {
|
||||
return ResponseEntity.ok(epubReaderService.getBookInfo(bookId, bookType));
|
||||
}
|
||||
|
||||
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
|
||||
@@ -41,6 +41,7 @@ public class EpubReaderController {
|
||||
@GetMapping("/{bookId}/file/**")
|
||||
public void getFile(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response) throws IOException {
|
||||
|
||||
@@ -49,10 +50,10 @@ public class EpubReaderController {
|
||||
String filePath = fullPath.substring(prefix.length());
|
||||
filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
|
||||
|
||||
String contentType = epubReaderService.getContentType(bookId, filePath);
|
||||
String contentType = epubReaderService.getContentType(bookId, bookType, filePath);
|
||||
response.setContentType(contentType);
|
||||
|
||||
long fileSize = epubReaderService.getFileSize(bookId, filePath);
|
||||
long fileSize = epubReaderService.getFileSize(bookId, bookType, filePath);
|
||||
if (fileSize > 0) {
|
||||
response.setContentLengthLong(fileSize);
|
||||
}
|
||||
@@ -66,6 +67,6 @@ public class EpubReaderController {
|
||||
|
||||
response.setHeader("Cache-Control", "public, max-age=3600");
|
||||
|
||||
epubReaderService.streamFile(bookId, filePath, response.getOutputStream());
|
||||
epubReaderService.streamFile(bookId, bookType, filePath, response.getOutputStream());
|
||||
}
|
||||
}
|
||||
|
||||
+10
-2
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.book.BookDownloadService;
|
||||
import com.adityachandel.booklore.service.book.BookService;
|
||||
import com.adityachandel.booklore.service.opds.OpdsFeedService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -17,6 +18,7 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Tag(name = "OPDS", description = "Endpoints for OPDS catalog feeds, book downloads, covers, and search description")
|
||||
@@ -31,14 +33,20 @@ public class OpdsController {
|
||||
|
||||
private final OpdsFeedService opdsFeedService;
|
||||
private final BookService bookService;
|
||||
private final BookDownloadService bookDownloadService;
|
||||
|
||||
@Operation(summary = "Download book file", description = "Download the book file by its ID.")
|
||||
@Operation(summary = "Download book file", description = "Download the book file by its ID. Optionally specify a fileId to download a specific format.")
|
||||
@ApiResponses({
|
||||
@ApiResponse(responseCode = "200", description = "Book file downloaded successfully"),
|
||||
@ApiResponse(responseCode = "404", description = "Book not found")
|
||||
})
|
||||
@GetMapping("/{bookId}/download")
|
||||
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId,
|
||||
@Parameter(description = "Optional ID of a specific file format to download") @RequestParam(required = false) Long fileId) {
|
||||
if (fileId != null) {
|
||||
return bookDownloadService.downloadBookFile(bookId, fileId);
|
||||
}
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
|
||||
+9
-8
@@ -7,10 +7,7 @@ import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -25,14 +22,18 @@ public class PdfReaderController {
|
||||
@Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.")
|
||||
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
|
||||
@GetMapping("/{bookId}/pages")
|
||||
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return pdfReaderService.getAvailablePages(bookId);
|
||||
public List<Integer> listPages(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
|
||||
return pdfReaderService.getAvailablePages(bookId, bookType);
|
||||
}
|
||||
|
||||
@Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.")
|
||||
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
|
||||
@GetMapping("/{bookId}/info")
|
||||
public PdfBookInfo getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return pdfReaderService.getBookInfo(bookId);
|
||||
public PdfBookInfo getBookInfo(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType) {
|
||||
return pdfReaderService.getBookInfo(bookId, bookType);
|
||||
}
|
||||
}
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.adityachandel.booklore.convertor;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
@Converter
|
||||
@Slf4j
|
||||
public class FormatPriorityConverter implements AttributeConverter<List<BookFileType>, String> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final TypeReference<List<BookFileType>> LIST_TYPE_REF = new TypeReference<>() {};
|
||||
|
||||
@Override
|
||||
public String convertToDatabaseColumn(List<BookFileType> attribute) {
|
||||
if (attribute == null || attribute.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(attribute);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error converting format priority list to JSON", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> convertToEntityAttribute(String dbData) {
|
||||
if (dbData == null || dbData.isEmpty()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(dbData, LIST_TYPE_REF);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Error converting JSON to format priority list", e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -14,6 +14,7 @@ public interface AdditionalFileMapper {
|
||||
@Mapping(source = "book.id", target = "bookId")
|
||||
@Mapping(source = ".", target = "filePath", qualifiedByName = "mapFilePath")
|
||||
@Mapping(source = "bookFormat", target = "isBook")
|
||||
@Mapping(source = ".", target = "extension", qualifiedByName = "mapExtension")
|
||||
BookFile toAdditionalFile(BookFileEntity entity);
|
||||
|
||||
List<BookFile> toAdditionalFiles(List<BookFileEntity> entities);
|
||||
@@ -27,4 +28,19 @@ public interface AdditionalFileMapper {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Named("mapExtension")
|
||||
default String mapExtension(BookFileEntity entity) {
|
||||
if (entity == null) return null;
|
||||
String fileName;
|
||||
if (entity.isFolderBased()) {
|
||||
var firstFile = entity.getFirstAudioFile();
|
||||
fileName = firstFile != null ? firstFile.getFileName().toString() : null;
|
||||
} else {
|
||||
fileName = entity.getFileName();
|
||||
}
|
||||
if (fileName == null) return null;
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null;
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,8 @@ package com.adityachandel.booklore.mapper;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import org.mapstruct.Context;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
@@ -23,11 +23,7 @@ public interface BookMapper {
|
||||
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
|
||||
@Mapping(source = "metadata", target = "metadata")
|
||||
@Mapping(source = "shelves", target = "shelves")
|
||||
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
|
||||
@Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName")
|
||||
@Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath")
|
||||
@Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath")
|
||||
@Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb")
|
||||
@Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile")
|
||||
@Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
|
||||
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
|
||||
Book toBook(BookEntity bookEntity);
|
||||
@@ -37,11 +33,7 @@ public interface BookMapper {
|
||||
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
|
||||
@Mapping(source = "metadata", target = "metadata")
|
||||
@Mapping(source = "shelves", target = "shelves")
|
||||
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
|
||||
@Mapping(source = "bookFiles", target = "fileName", qualifiedByName = "mapPrimaryFileName")
|
||||
@Mapping(source = "bookFiles", target = "filePath", qualifiedByName = "mapPrimaryFilePath")
|
||||
@Mapping(source = "bookFiles", target = "fileSubPath", qualifiedByName = "mapPrimaryFileSubPath")
|
||||
@Mapping(source = "bookFiles", target = "fileSizeKb", qualifiedByName = "mapPrimaryFileSizeKb")
|
||||
@Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile")
|
||||
@Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
|
||||
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
|
||||
Book toBookWithDescription(BookEntity bookEntity, @Context boolean includeDescription);
|
||||
@@ -82,34 +74,13 @@ public interface BookMapper {
|
||||
.build();
|
||||
}
|
||||
|
||||
@Named("mapPrimaryBookType")
|
||||
default BookFileType mapPrimaryBookType(List<BookFileEntity> bookFiles) {
|
||||
@Named("mapPrimaryFile")
|
||||
default BookFile mapPrimaryFile(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null || bookFiles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return primary == null ? null : primary.getBookType();
|
||||
}
|
||||
|
||||
@Named("mapPrimaryFileName")
|
||||
default String mapPrimaryFileName(List<BookFileEntity> bookFiles) {
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return primary == null ? null : primary.getFileName();
|
||||
}
|
||||
|
||||
@Named("mapPrimaryFilePath")
|
||||
default String mapPrimaryFilePath(List<BookFileEntity> bookFiles) {
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return primary == null ? null : primary.getFullFilePath().toString();
|
||||
}
|
||||
|
||||
@Named("mapPrimaryFileSubPath")
|
||||
default String mapPrimaryFileSubPath(List<BookFileEntity> bookFiles) {
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return primary == null ? null : primary.getFileSubPath();
|
||||
}
|
||||
|
||||
@Named("mapPrimaryFileSizeKb")
|
||||
default Long mapPrimaryFileSizeKb(List<BookFileEntity> bookFiles) {
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return primary == null ? null : primary.getFileSizeKb();
|
||||
return toBookFile(primary);
|
||||
}
|
||||
|
||||
@Named("mapAlternativeFormats")
|
||||
@@ -132,16 +103,29 @@ public interface BookMapper {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/*
|
||||
* TODO: evolve the logic so that the user can select the primary book file format to be used.
|
||||
* For now, we just return the first book file in the list.
|
||||
*/
|
||||
default BookFileEntity getPrimaryBookFile(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null || bookFiles.isEmpty()) return null;
|
||||
return bookFiles.stream()
|
||||
.filter(bf -> bf.isBook())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
List<BookFileEntity> bookFormats = bookFiles.stream()
|
||||
.filter(BookFileEntity::isBook)
|
||||
.toList();
|
||||
|
||||
if (bookFormats.isEmpty()) return null;
|
||||
|
||||
BookFileEntity firstBook = bookFormats.getFirst();
|
||||
LibraryEntity library = firstBook.getBook() != null ? firstBook.getBook().getLibrary() : null;
|
||||
|
||||
if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) {
|
||||
for (BookFileType format : library.getFormatPriority()) {
|
||||
var match = bookFormats.stream()
|
||||
.filter(bf -> bf.getBookType() == format)
|
||||
.findFirst();
|
||||
if (match.isPresent()) {
|
||||
return match.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
return firstBook;
|
||||
}
|
||||
|
||||
default BookFile toBookFile(BookFileEntity entity) {
|
||||
@@ -153,10 +137,27 @@ public interface BookMapper {
|
||||
.filePath(entity.getFullFilePath().toString())
|
||||
.fileSubPath(entity.getFileSubPath())
|
||||
.isBook(entity.isBook())
|
||||
.folderBased(entity.isFolderBased())
|
||||
.bookType(entity.getBookType())
|
||||
.archiveType(entity.getArchiveType())
|
||||
.fileSizeKb(entity.getFileSizeKb())
|
||||
.extension(extractExtension(entity))
|
||||
.description(entity.getDescription())
|
||||
.addedOn(entity.getAddedOn())
|
||||
.build();
|
||||
}
|
||||
|
||||
default String extractExtension(BookFileEntity entity) {
|
||||
if (entity == null) return null;
|
||||
String fileName;
|
||||
if (entity.isFolderBased()) {
|
||||
var firstFile = entity.getFirstAudioFile();
|
||||
fileName = firstFile != null ? firstFile.getFileName().toString() : null;
|
||||
} else {
|
||||
fileName = entity.getFileName();
|
||||
}
|
||||
if (fileName == null) return null;
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +282,7 @@ public class KomgaMapper {
|
||||
case FB2 -> "application/fictionbook2+zip";
|
||||
case MOBI -> "application/x-mobipocket-ebook";
|
||||
case AZW3 -> "application/vnd.amazon.ebook";
|
||||
case AUDIOBOOK -> "audio/mp4";
|
||||
};
|
||||
}
|
||||
|
||||
@@ -297,6 +298,7 @@ public class KomgaMapper {
|
||||
case EPUB -> "EPUB";
|
||||
case CBX -> "DIVINA"; // DIVINA is for comic books
|
||||
case FB2 -> "DIVINA";
|
||||
case AUDIOBOOK -> "AUDIOBOOK";
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.mapper.v2;
|
||||
|
||||
import com.adityachandel.booklore.mapper.ShelfMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
@@ -21,7 +22,9 @@ public interface BookMapperV2 {
|
||||
@Mapping(source = "library.id", target = "libraryId")
|
||||
@Mapping(source = "library.name", target = "libraryName")
|
||||
@Mapping(source = "libraryPath", target = "libraryPath", qualifiedByName = "mapLibraryPathIdOnly")
|
||||
@Mapping(source = "bookFiles", target = "bookType", qualifiedByName = "mapPrimaryBookType")
|
||||
@Mapping(source = "bookFiles", target = "primaryFile", qualifiedByName = "mapPrimaryFile")
|
||||
@Mapping(source = "bookFiles", target = "alternativeFormats", qualifiedByName = "mapAlternativeFormats")
|
||||
@Mapping(source = "bookFiles", target = "supplementaryFiles", qualifiedByName = "mapSupplementaryFiles")
|
||||
@Mapping(target = "metadata", qualifiedByName = "mapMetadata")
|
||||
Book toDTO(BookEntity bookEntity);
|
||||
|
||||
@@ -56,14 +59,87 @@ public interface BookMapperV2 {
|
||||
tags.stream().map(TagEntity::getName).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@Named("mapPrimaryBookType")
|
||||
default BookFileType mapPrimaryBookType(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null || bookFiles.isEmpty()) return null;
|
||||
@Named("mapPrimaryFile")
|
||||
default BookFile mapPrimaryFile(List<BookFileEntity> bookFiles) {
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return toBookFile(primary);
|
||||
}
|
||||
|
||||
@Named("mapAlternativeFormats")
|
||||
default List<BookFile> mapAlternativeFormats(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null) return null;
|
||||
BookFileEntity primary = getPrimaryBookFile(bookFiles);
|
||||
return bookFiles.stream()
|
||||
.filter(BookFileEntity::isBook)
|
||||
.map(BookFileEntity::getBookType)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
.filter(bf -> !bf.equals(primary))
|
||||
.map(this::toBookFile)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Named("mapSupplementaryFiles")
|
||||
default List<BookFile> mapSupplementaryFiles(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null) return null;
|
||||
return bookFiles.stream()
|
||||
.filter(bf -> !bf.isBook())
|
||||
.map(this::toBookFile)
|
||||
.toList();
|
||||
}
|
||||
|
||||
default BookFileEntity getPrimaryBookFile(List<BookFileEntity> bookFiles) {
|
||||
if (bookFiles == null || bookFiles.isEmpty()) return null;
|
||||
|
||||
List<BookFileEntity> bookFormats = bookFiles.stream()
|
||||
.filter(BookFileEntity::isBook)
|
||||
.toList();
|
||||
|
||||
if (bookFormats.isEmpty()) return null;
|
||||
|
||||
BookFileEntity firstBook = bookFormats.getFirst();
|
||||
LibraryEntity library = firstBook.getBook() != null ? firstBook.getBook().getLibrary() : null;
|
||||
|
||||
if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) {
|
||||
for (BookFileType format : library.getFormatPriority()) {
|
||||
var match = bookFormats.stream()
|
||||
.filter(bf -> bf.getBookType() == format)
|
||||
.findFirst();
|
||||
if (match.isPresent()) {
|
||||
return match.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
return firstBook;
|
||||
}
|
||||
|
||||
default BookFile toBookFile(BookFileEntity entity) {
|
||||
if (entity == null) return null;
|
||||
return BookFile.builder()
|
||||
.id(entity.getId())
|
||||
.bookId(entity.getBook().getId())
|
||||
.fileName(entity.getFileName())
|
||||
.filePath(entity.getFullFilePath().toString())
|
||||
.fileSubPath(entity.getFileSubPath())
|
||||
.isBook(entity.isBook())
|
||||
.bookType(entity.getBookType())
|
||||
.archiveType(entity.getArchiveType())
|
||||
.fileSizeKb(entity.getFileSizeKb())
|
||||
.extension(extractExtension(entity))
|
||||
.description(entity.getDescription())
|
||||
.addedOn(entity.getAddedOn())
|
||||
.build();
|
||||
}
|
||||
|
||||
default String extractExtension(BookFileEntity entity) {
|
||||
if (entity == null) return null;
|
||||
String fileName;
|
||||
if (entity.isFolderBased()) {
|
||||
var firstFile = entity.getFirstAudioFile();
|
||||
fileName = firstFile != null ? firstFile.getFileName().toString() : null;
|
||||
} else {
|
||||
fileName = entity.getFileName();
|
||||
}
|
||||
if (fileName == null) return null;
|
||||
int lastDot = fileName.lastIndexOf('.');
|
||||
return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null;
|
||||
}
|
||||
|
||||
@Named("mapLibraryPathIdOnly")
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -15,14 +13,9 @@ import java.util.Set;
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Book {
|
||||
private Long id;
|
||||
private BookFileType bookType;
|
||||
private ArchiveUtils.ArchiveType archiveType;
|
||||
private Long libraryId;
|
||||
private String libraryName;
|
||||
private String fileName;
|
||||
private String filePath;
|
||||
private String fileSubPath;
|
||||
private Long fileSizeKb;
|
||||
private BookFile primaryFile;
|
||||
private String title;
|
||||
private Instant lastReadTime;
|
||||
private Instant addedOn;
|
||||
@@ -31,6 +24,7 @@ public class Book {
|
||||
private PdfProgress pdfProgress;
|
||||
private EpubProgress epubProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private AudiobookProgress audiobookProgress;
|
||||
private KoProgress koreaderProgress;
|
||||
private KoboProgress koboProgress;
|
||||
private Integer personalRating;
|
||||
@@ -40,4 +34,5 @@ public class Book {
|
||||
private LibraryPath libraryPath;
|
||||
private List<BookFile> alternativeFormats;
|
||||
private List<BookFile> supplementaryFiles;
|
||||
private Boolean isPhysical;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -17,8 +18,11 @@ public class BookFile {
|
||||
private String filePath;
|
||||
private String fileSubPath;
|
||||
private boolean isBook;
|
||||
private boolean folderBased;
|
||||
private BookFileType bookType;
|
||||
private ArchiveUtils.ArchiveType archiveType;
|
||||
private Long fileSizeKb;
|
||||
private String extension;
|
||||
private String description;
|
||||
private Instant addedOn;
|
||||
}
|
||||
@@ -15,7 +15,9 @@ public class BookMark {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private Long bookId;
|
||||
private String cfi;
|
||||
private String cfi; // For EPUB bookmarks
|
||||
private Long positionMs; // For audiobook bookmarks
|
||||
private Integer trackIndex; // For folder-based audiobooks
|
||||
private String title;
|
||||
private String color;
|
||||
private String notes;
|
||||
|
||||
@@ -95,6 +95,5 @@ public class BookloreTelemetry {
|
||||
private int totalLibraryPaths;
|
||||
private boolean watchEnabled;
|
||||
private String iconType;
|
||||
private String scanMode;
|
||||
}
|
||||
}
|
||||
|
||||
+14
-2
@@ -1,6 +1,5 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -14,7 +13,20 @@ import lombok.NoArgsConstructor;
|
||||
public class CreateBookMarkRequest {
|
||||
@NotNull
|
||||
private Long bookId;
|
||||
@NotEmpty
|
||||
|
||||
// For EPUB bookmarks
|
||||
private String cfi;
|
||||
|
||||
// For audiobook bookmarks
|
||||
private Long positionMs;
|
||||
private Integer trackIndex;
|
||||
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* Check if this is an audiobook bookmark (has positionMs) vs EPUB bookmark (has cfi)
|
||||
*/
|
||||
public boolean isAudiobookBookmark() {
|
||||
return positionMs != null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.IconType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.enums.LibraryOrganizationMode;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -21,7 +21,7 @@ public class Library {
|
||||
private String fileNamingPattern;
|
||||
private boolean watch;
|
||||
private List<LibraryPath> paths;
|
||||
private LibraryScanMode scanMode;
|
||||
private BookFileType defaultBookFormat;
|
||||
private List<BookFileType> formatPriority;
|
||||
private LibraryOrganizationMode organizationMode;
|
||||
}
|
||||
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.adityachandel.booklore.model.dto.progress;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class AudiobookProgress {
|
||||
@NotNull
|
||||
Long positionMs;
|
||||
Integer trackIndex;
|
||||
Long trackPositionMs;
|
||||
@NotNull
|
||||
Float percentage;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AttachBookFileRequest {
|
||||
@NotNull
|
||||
@NotEmpty
|
||||
private List<Long> sourceBookIds;
|
||||
private boolean deleteSourceBooks;
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record BookFileProgress(
|
||||
@NotNull Long bookFileId,
|
||||
String positionData,
|
||||
String positionHref,
|
||||
@NotNull Float progressPercent
|
||||
) {
|
||||
}
|
||||
+1
@@ -9,4 +9,5 @@ public class CoverFetchRequest {
|
||||
private String isbn;
|
||||
private String title;
|
||||
private String author;
|
||||
private boolean squareCover;
|
||||
}
|
||||
|
||||
+1
-3
@@ -3,7 +3,6 @@ package com.adityachandel.booklore.model.dto.request;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.IconType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
@@ -30,6 +29,5 @@ public class CreateLibraryRequest {
|
||||
private List<LibraryPath> paths;
|
||||
|
||||
private boolean watch;
|
||||
private LibraryScanMode scanMode;
|
||||
private BookFileType defaultBookFormat;
|
||||
private List<BookFileType> formatPriority;
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CreatePhysicalBookRequest {
|
||||
@NotNull(message = "Library ID must not be null.")
|
||||
private Long libraryId;
|
||||
|
||||
private String isbn;
|
||||
private String title;
|
||||
private List<String> authors;
|
||||
private String description;
|
||||
private String publisher;
|
||||
private String publishedDate;
|
||||
private String language;
|
||||
private Integer pageCount;
|
||||
private List<String> categories;
|
||||
}
|
||||
+11
-1
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.progress.AudiobookProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
|
||||
@@ -12,13 +13,22 @@ import java.time.Instant;
|
||||
public class ReadProgressRequest {
|
||||
@NotNull
|
||||
private Long bookId;
|
||||
|
||||
private BookFileProgress fileProgress;
|
||||
|
||||
@Deprecated
|
||||
private EpubProgress epubProgress;
|
||||
@Deprecated
|
||||
private PdfProgress pdfProgress;
|
||||
@Deprecated
|
||||
private CbxProgress cbxProgress;
|
||||
@Deprecated
|
||||
private AudiobookProgress audiobookProgress;
|
||||
|
||||
private Instant dateFinished;
|
||||
|
||||
@AssertTrue(message = "At least one progress field must be provided")
|
||||
public boolean isProgressValid() {
|
||||
return epubProgress != null || pdfProgress != null || cbxProgress != null || dateFinished != null;
|
||||
return fileProgress != null || epubProgress != null || pdfProgress != null || cbxProgress != null || audiobookProgress != null || dateFinished != null;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-5
@@ -26,18 +26,15 @@ public class ReadingSessionRequest {
|
||||
@NotNull
|
||||
private Integer durationSeconds;
|
||||
|
||||
@NotNull
|
||||
private String durationFormatted;
|
||||
|
||||
private Float startProgress;
|
||||
|
||||
@NotNull
|
||||
private Float endProgress;
|
||||
|
||||
@NotNull
|
||||
private Float progressDelta;
|
||||
|
||||
@NotNull
|
||||
private String startLocation;
|
||||
|
||||
@NotNull
|
||||
private String endLocation;
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
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 AudiobookChapter {
|
||||
private Integer index;
|
||||
private String title;
|
||||
private Long startTimeMs;
|
||||
private Long endTimeMs;
|
||||
private Long durationMs;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AudiobookInfo {
|
||||
private Long bookId;
|
||||
private Long bookFileId;
|
||||
private String title;
|
||||
private String author;
|
||||
private String narrator;
|
||||
private Long durationMs;
|
||||
private Integer bitrate;
|
||||
private String codec;
|
||||
private Integer sampleRate;
|
||||
private Integer channels;
|
||||
private boolean folderBased;
|
||||
private List<AudiobookChapter> chapters;
|
||||
private List<AudiobookTrack> tracks;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
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 AudiobookTrack {
|
||||
private Integer index;
|
||||
private String fileName;
|
||||
private String title;
|
||||
private Long durationMs;
|
||||
private Long fileSizeBytes;
|
||||
private Long cumulativeStartMs;
|
||||
}
|
||||
+1
@@ -36,4 +36,5 @@ public class AppSettings {
|
||||
private KoboSettings koboSettings;
|
||||
private CoverCroppingSettings coverCroppingSettings;
|
||||
private MetadataProviderSpecificFields metadataProviderSpecificFields;
|
||||
private String diskType;
|
||||
}
|
||||
+2
@@ -19,6 +19,8 @@ public class LibraryFile {
|
||||
private String fileSubPath;
|
||||
private String fileName;
|
||||
private BookFileType bookFileType;
|
||||
@Builder.Default
|
||||
private boolean folderBased = false;
|
||||
|
||||
public Path getFullPath() {
|
||||
if (fileSubPath == null || fileSubPath.isEmpty()) {
|
||||
|
||||
@@ -45,9 +45,13 @@ public class BookEntity {
|
||||
private LibraryEntity library;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "library_path_id", nullable = false)
|
||||
@JoinColumn(name = "library_path_id")
|
||||
private LibraryPathEntity libraryPath;
|
||||
|
||||
@Column(name = "is_physical")
|
||||
@Builder.Default
|
||||
private Boolean isPhysical = Boolean.FALSE;
|
||||
|
||||
@Column(name = "added_on")
|
||||
private Instant addedOn;
|
||||
|
||||
@@ -83,9 +87,8 @@ public class BookEntity {
|
||||
|
||||
public Path getFullFilePath() {
|
||||
BookFileEntity primaryBookFile = getPrimaryBookFile();
|
||||
if (libraryPath == null || libraryPath.getPath() == null || primaryBookFile.getFileSubPath() == null || primaryBookFile.getFileName() == null) {
|
||||
throw new IllegalStateException(
|
||||
"Cannot construct file path: missing library path, file subpath, or file name");
|
||||
if (primaryBookFile == null || libraryPath == null || libraryPath.getPath() == null || primaryBookFile.getFileSubPath() == null || primaryBookFile.getFileName() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Paths.get(libraryPath.getPath(), primaryBookFile.getFileSubPath(), primaryBookFile.getFileName());
|
||||
@@ -93,22 +96,34 @@ public class BookEntity {
|
||||
|
||||
public List<Path> getFullFilePaths() {
|
||||
if (libraryPath == null || libraryPath.getPath() == null || bookFiles == null || bookFiles.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"Cannot construct file path: missing library path, file subpath, or file name");
|
||||
return List.of();
|
||||
}
|
||||
return bookFiles.stream()
|
||||
.map(bookFile -> Paths.get(libraryPath.getPath(), bookFile.getFileSubPath(), bookFile.getFileName()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// TODO: Add support for specifying the preferred format
|
||||
public BookFileEntity getPrimaryBookFile() {
|
||||
if (bookFiles == null) {
|
||||
bookFiles = new ArrayList<>();
|
||||
}
|
||||
if (bookFiles.isEmpty()) {
|
||||
throw new IllegalStateException("Book file not found");
|
||||
return null;
|
||||
}
|
||||
if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) {
|
||||
for (BookFileType format : library.getFormatPriority()) {
|
||||
var match = bookFiles.stream()
|
||||
.filter(bf -> bf.isBookFormat() && bf.getBookType() == format)
|
||||
.findFirst();
|
||||
if (match.isPresent()) {
|
||||
return match.get();
|
||||
}
|
||||
}
|
||||
}
|
||||
return bookFiles.getFirst();
|
||||
}
|
||||
|
||||
public boolean hasFiles() {
|
||||
return bookFiles != null && !bookFiles.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
+41
-1
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -34,6 +35,10 @@ public class BookFileEntity {
|
||||
@Column(name = "is_book", nullable = false)
|
||||
private boolean isBookFormat;
|
||||
|
||||
@Column(name = "is_folder_based", nullable = false)
|
||||
@Builder.Default
|
||||
private boolean folderBased = false;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "book_type", nullable = false)
|
||||
private BookFileType bookType;
|
||||
@@ -72,4 +77,39 @@ public class BookFileEntity {
|
||||
|
||||
return Paths.get(book.getLibraryPath().getPath(), fileSubPath, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* For folder-based audiobooks, returns the folder path.
|
||||
* For regular files, returns the file path.
|
||||
*/
|
||||
public Path getAudiobookPath() {
|
||||
Path fullPath = getFullFilePath();
|
||||
return folderBased ? fullPath : fullPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* For folder-based audiobooks, returns the first audio file in the folder (for metadata extraction).
|
||||
* For regular files, returns the file itself.
|
||||
*/
|
||||
public Path getFirstAudioFile() {
|
||||
if (!folderBased) {
|
||||
return getFullFilePath();
|
||||
}
|
||||
Path folderPath = getFullFilePath();
|
||||
try {
|
||||
return java.nio.file.Files.list(folderPath)
|
||||
.filter(java.nio.file.Files::isRegularFile)
|
||||
.filter(p -> {
|
||||
String name = p.getFileName().toString().toLowerCase();
|
||||
return name.endsWith(".mp3") || name.endsWith(".m4a") || name.endsWith(".m4b")
|
||||
|| name.endsWith(".flac") || name.endsWith(".ogg") || name.endsWith(".opus")
|
||||
|| name.endsWith(".aac");
|
||||
})
|
||||
.sorted()
|
||||
.findFirst()
|
||||
.orElse(folderPath);
|
||||
} catch (java.io.IOException e) {
|
||||
return folderPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-1
@@ -34,9 +34,17 @@ public class BookMarkEntity {
|
||||
@Column(name = "book_id", insertable = false, updatable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "cfi", nullable = false, length = 1000)
|
||||
// For EPUB bookmarks
|
||||
@Column(name = "cfi", length = 1000)
|
||||
private String cfi;
|
||||
|
||||
// For audiobook bookmarks
|
||||
@Column(name = "position_ms")
|
||||
private Long positionMs;
|
||||
|
||||
@Column(name = "track_index")
|
||||
private Integer trackIndex;
|
||||
|
||||
@Column(name = "title")
|
||||
private String title;
|
||||
|
||||
|
||||
+9
-6
@@ -1,13 +1,15 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.convertor.FormatPriorityConverter;
|
||||
import com.adityachandel.booklore.convertor.SortConverter;
|
||||
import com.adityachandel.booklore.model.dto.Sort;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.IconType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.enums.LibraryOrganizationMode;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@@ -49,14 +51,15 @@ public class LibraryEntity {
|
||||
@Column(name = "file_naming_pattern")
|
||||
private String fileNamingPattern;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "scan_mode", nullable = false)
|
||||
@Convert(converter = FormatPriorityConverter.class)
|
||||
@Column(name = "format_priority")
|
||||
@Builder.Default
|
||||
private LibraryScanMode scanMode = LibraryScanMode.FILE_AS_BOOK;
|
||||
private List<BookFileType> formatPriority = new ArrayList<>();
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "default_book_format")
|
||||
private BookFileType defaultBookFormat;
|
||||
@Column(name = "organization_mode")
|
||||
@Builder.Default
|
||||
private LibraryOrganizationMode organizationMode = LibraryOrganizationMode.AUTO_DETECT;
|
||||
|
||||
@PrePersist
|
||||
public void ensureIconType() {
|
||||
|
||||
+8
-5
@@ -41,19 +41,22 @@ public class ReadingSessionEntity {
|
||||
@Column(name = "duration_seconds", nullable = false)
|
||||
private Integer durationSeconds;
|
||||
|
||||
@Column(name = "start_progress", nullable = false)
|
||||
@Column(name = "duration_formatted")
|
||||
private String durationFormatted;
|
||||
|
||||
@Column(name = "start_progress")
|
||||
private Float startProgress;
|
||||
|
||||
@Column(name = "end_progress", nullable = false)
|
||||
@Column(name = "end_progress")
|
||||
private Float endProgress;
|
||||
|
||||
@Column(name = "progress_delta", nullable = false)
|
||||
@Column(name = "progress_delta")
|
||||
private Float progressDelta;
|
||||
|
||||
@Column(name = "start_location", nullable = false, length = 500)
|
||||
@Column(name = "start_location", length = 500)
|
||||
private String startLocation;
|
||||
|
||||
@Column(name = "end_location", nullable = false, length = 500)
|
||||
@Column(name = "end_location", length = 500)
|
||||
private String endLocation;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "user_book_file_progress",
|
||||
uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "book_file_id"}))
|
||||
public class UserBookFileProgressEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private BookLoreUserEntity user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "book_file_id", nullable = false)
|
||||
private BookFileEntity bookFile;
|
||||
|
||||
@Column(name = "position_data", length = 1000)
|
||||
private String positionData;
|
||||
|
||||
@Column(name = "position_href", length = 1000)
|
||||
private String positionHref;
|
||||
|
||||
@Column(name = "progress_percent")
|
||||
private Float progressPercent;
|
||||
|
||||
@Column(name = "last_read_time")
|
||||
private Instant lastReadTime;
|
||||
}
|
||||
+7
@@ -30,24 +30,31 @@ public class UserBookProgressEntity {
|
||||
@Column(name = "last_read_time")
|
||||
private Instant lastReadTime;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "pdf_progress")
|
||||
private Integer pdfProgress;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "pdf_progress_percent")
|
||||
private Float pdfProgressPercent;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "epub_progress", length = 1000)
|
||||
private String epubProgress;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "epub_progress_href", length = 1000)
|
||||
private String epubProgressHref;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "epub_progress_percent")
|
||||
private Float epubProgressPercent;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "cbx_progress")
|
||||
private Integer cbxProgress;
|
||||
|
||||
@Deprecated
|
||||
@Column(name = "cbx_progress_percent")
|
||||
private Float cbxProgressPercent;
|
||||
|
||||
|
||||
+8
-1
@@ -17,7 +17,14 @@ public enum BookFileExtension {
|
||||
MOBI("mobi", BookFileType.MOBI),
|
||||
AZW3("azw3", BookFileType.AZW3),
|
||||
AZW("azw", BookFileType.AZW3),
|
||||
FB2("fb2", BookFileType.FB2);
|
||||
FB2("fb2", BookFileType.FB2),
|
||||
M4B("m4b", BookFileType.AUDIOBOOK),
|
||||
M4A("m4a", BookFileType.AUDIOBOOK),
|
||||
MP3("mp3", BookFileType.AUDIOBOOK),
|
||||
AAC("aac", BookFileType.AUDIOBOOK),
|
||||
FLAC("flac", BookFileType.AUDIOBOOK),
|
||||
OPUS("opus", BookFileType.AUDIOBOOK),
|
||||
OGG("ogg", BookFileType.AUDIOBOOK);
|
||||
|
||||
private final String extension;
|
||||
private final BookFileType type;
|
||||
|
||||
@@ -14,7 +14,8 @@ public enum BookFileType {
|
||||
CBX(Set.of("cbz", "cbr", "cb7")),
|
||||
FB2(Set.of("fb2")),
|
||||
MOBI(Set.of("mobi")),
|
||||
AZW3(Set.of("azw3", "azw"));
|
||||
AZW3(Set.of("azw3", "azw")),
|
||||
AUDIOBOOK(Set.of("m4b", "m4a", "mp3", "aac", "flac", "opus", "ogg"));
|
||||
|
||||
private final Set<String> extensions;
|
||||
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
/**
|
||||
* Defines how a library organizes book files into folders.
|
||||
* This affects how files are grouped together as a single book.
|
||||
*/
|
||||
public enum LibraryOrganizationMode {
|
||||
|
||||
/**
|
||||
* Each book has its own dedicated folder.
|
||||
* All files within a folder are treated as formats of the same book.
|
||||
* Simple and deterministic - no fuzzy matching needed.
|
||||
* <p>
|
||||
* Example:
|
||||
* <pre>
|
||||
* Library/
|
||||
* └── American Gods/
|
||||
* ├── American Gods.epub
|
||||
* ├── American Gods.m4b
|
||||
* └── American Gods - 10th Anniversary.pdf
|
||||
* </pre>
|
||||
* All three files become one book.
|
||||
*/
|
||||
BOOK_PER_FOLDER,
|
||||
|
||||
/**
|
||||
* System automatically detects grouping using folder-centric fuzzy matching.
|
||||
* Uses folder name as reference, applies similarity matching for variations.
|
||||
* Handles series detection to keep numbered entries separate.
|
||||
* <p>
|
||||
* Use this when your library has mixed organization or you're unsure.
|
||||
*/
|
||||
AUTO_DETECT
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum LibraryScanMode {
|
||||
FILE_AS_BOOK,
|
||||
FOLDER_AS_BOOK
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface BookFileRepository extends JpaRepository<BookFileEntity, Long> {
|
||||
|
||||
@Query("""
|
||||
SELECT bf FROM BookFileEntity bf
|
||||
WHERE bf.book.libraryPath.id = :libraryPathId
|
||||
AND bf.fileSubPath = :fileSubPath
|
||||
AND bf.fileName = :fileName
|
||||
""")
|
||||
Optional<BookFileEntity> findByLibraryPathIdAndFileSubPathAndFileName(
|
||||
@Param("libraryPathId") Long libraryPathId,
|
||||
@Param("fileSubPath") String fileSubPath,
|
||||
@Param("fileName") String fileName);
|
||||
|
||||
@Query("SELECT COUNT(bf) FROM BookFileEntity bf WHERE bf.book.id = :bookId")
|
||||
long countByBookId(@Param("bookId") Long bookId);
|
||||
}
|
||||
+7
@@ -20,6 +20,13 @@ public interface BookMarkRepository extends JpaRepository<BookMarkEntity, Long>
|
||||
@Query("SELECT COUNT(b) > 0 FROM BookMarkEntity b WHERE b.cfi = :cfi AND b.bookId = :bookId AND b.userId = :userId AND b.id != :excludeId")
|
||||
boolean existsByCfiAndBookIdAndUserIdExcludeId(@Param("cfi") String cfi, @Param("bookId") Long bookId, @Param("userId") Long userId, @Param("excludeId") Long excludeId);
|
||||
|
||||
// Audiobook bookmark duplicate check (within 5 seconds of position is considered duplicate)
|
||||
@Query("SELECT COUNT(b) > 0 FROM BookMarkEntity b WHERE b.bookId = :bookId AND b.userId = :userId " +
|
||||
"AND b.positionMs IS NOT NULL " +
|
||||
"AND ABS(b.positionMs - :positionMs) < 5000 " +
|
||||
"AND ((:trackIndex IS NULL AND b.trackIndex IS NULL) OR b.trackIndex = :trackIndex)")
|
||||
boolean existsByPositionMsNearAndBookIdAndUserId(@Param("positionMs") Long positionMs, @Param("trackIndex") Integer trackIndex, @Param("bookId") Long bookId, @Param("userId") Long userId);
|
||||
|
||||
// New: count bookmarks per book
|
||||
long countByBookIdAndUserId(Long bookId, Long userId);
|
||||
}
|
||||
|
||||
@@ -35,6 +35,9 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath LIKE CONCAT(:fileSubPathPrefix, '%') AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllByLibraryPathIdAndFileSubPathStartingWith(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPathPrefix") String fileSubPathPrefix);
|
||||
|
||||
@Query("SELECT DISTINCT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath = :fileSubPath AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
List<BookEntity> findAllByLibraryPathIdAndFileSubPath(@Param("libraryPathId") Long libraryPathId, @Param("fileSubPath") String fileSubPath);
|
||||
|
||||
@Query("SELECT b FROM BookEntity b JOIN b.bookFiles bf WHERE b.libraryPath.id = :libraryPathId AND bf.fileSubPath = :fileSubPath AND bf.fileName = :fileName AND bf.isBookFormat = true AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
Optional<BookEntity> findByLibraryPath_IdAndFileSubPathAndFileName(@Param("libraryPathId") Long libraryPathId,
|
||||
@Param("fileSubPath") String fileSubPath,
|
||||
@@ -143,6 +146,16 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
||||
@Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
|
||||
long countByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("""
|
||||
SELECT b FROM BookEntity b
|
||||
LEFT JOIN b.bookFiles bf
|
||||
WHERE b.library.id = :libraryId
|
||||
AND (b.deleted IS NULL OR b.deleted = false)
|
||||
GROUP BY b
|
||||
HAVING COUNT(bf) = 0
|
||||
""")
|
||||
List<BookEntity> findFilelessBooksByLibraryId(@Param("libraryId") Long libraryId);
|
||||
|
||||
@Query("SELECT b.id as id, m.coverUpdatedOn as coverUpdatedOn FROM BookEntity b LEFT JOIN b.metadata m WHERE b.id IN :bookIds")
|
||||
List<BookCoverUpdateProjection> findCoverUpdateInfoByIds(@Param("bookIds") Collection<Long> bookIds);
|
||||
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface UserBookFileProgressRepository extends JpaRepository<UserBookFileProgressEntity, Long> {
|
||||
|
||||
Optional<UserBookFileProgressEntity> findByUserIdAndBookFileId(Long userId, Long bookFileId);
|
||||
|
||||
@Query("""
|
||||
SELECT ubfp FROM UserBookFileProgressEntity ubfp
|
||||
WHERE ubfp.user.id = :userId
|
||||
AND ubfp.bookFile.book.id = :bookId
|
||||
""")
|
||||
List<UserBookFileProgressEntity> findByUserIdAndBookFileBookId(
|
||||
@Param("userId") Long userId,
|
||||
@Param("bookId") Long bookId
|
||||
);
|
||||
|
||||
@Query("""
|
||||
SELECT ubfp FROM UserBookFileProgressEntity ubfp
|
||||
WHERE ubfp.user.id = :userId
|
||||
AND ubfp.bookFile.book.id = :bookId
|
||||
ORDER BY ubfp.lastReadTime DESC
|
||||
LIMIT 1
|
||||
""")
|
||||
Optional<UserBookFileProgressEntity> findMostRecentByUserIdAndBookId(
|
||||
@Param("userId") Long userId,
|
||||
@Param("bookId") Long bookId
|
||||
);
|
||||
|
||||
@Query("""
|
||||
SELECT ubfp FROM UserBookFileProgressEntity ubfp
|
||||
WHERE ubfp.user.id = :userId
|
||||
AND ubfp.bookFile.book.id IN :bookIds
|
||||
""")
|
||||
List<UserBookFileProgressEntity> findByUserIdAndBookFileBookIdIn(
|
||||
@Param("userId") Long userId,
|
||||
@Param("bookIds") Iterable<Long> bookIds
|
||||
);
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Generic file streaming service with HTTP Range support.
|
||||
* Can be used for streaming audio, video, or any binary files.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class FileStreamingService {
|
||||
|
||||
private static final int BUFFER_SIZE = 8192;
|
||||
|
||||
/**
|
||||
* Stream a file with HTTP Range support for seeking/scrubbing.
|
||||
* Implements HTTP 206 Partial Content for range requests.
|
||||
*
|
||||
* @param filePath Path to the file to stream
|
||||
* @param contentType MIME type of the file
|
||||
* @param request HTTP request (to read Range header)
|
||||
* @param response HTTP response (to write headers and body)
|
||||
*/
|
||||
public void streamWithRangeSupport(Path filePath, String contentType, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
if (!Files.exists(filePath)) {
|
||||
response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
|
||||
return;
|
||||
}
|
||||
|
||||
long fileSize = Files.size(filePath);
|
||||
String rangeHeader = request.getHeader("Range");
|
||||
|
||||
// Always indicate we accept range requests
|
||||
response.setHeader("Accept-Ranges", "bytes");
|
||||
response.setContentType(contentType);
|
||||
response.setHeader("Cache-Control", "public, max-age=3600");
|
||||
|
||||
try {
|
||||
if (rangeHeader == null) {
|
||||
// No Range header - return full file
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
response.setContentLengthLong(fileSize);
|
||||
streamBytes(filePath, 0, fileSize - 1, response.getOutputStream());
|
||||
} else {
|
||||
// Parse Range header
|
||||
RangeInfo range = parseRange(rangeHeader, fileSize);
|
||||
if (range == null) {
|
||||
// Invalid range
|
||||
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
response.setHeader("Content-Range", "bytes */" + fileSize);
|
||||
return;
|
||||
}
|
||||
|
||||
// Return partial content
|
||||
long contentLength = range.end - range.start + 1;
|
||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
response.setContentLengthLong(contentLength);
|
||||
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + fileSize);
|
||||
|
||||
streamBytes(filePath, range.start, range.end, response.getOutputStream());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// Client disconnected (e.g., during seeking) - this is normal, just log at debug level
|
||||
if (isClientDisconnect(e)) {
|
||||
log.debug("Client disconnected during streaming: {}", e.getMessage());
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the exception is due to client disconnect (common during seeking).
|
||||
*/
|
||||
boolean isClientDisconnect(IOException e) {
|
||||
// SocketTimeoutException is common when client disconnects
|
||||
if (e instanceof SocketTimeoutException) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String message = e.getMessage();
|
||||
if (message == null) {
|
||||
// Check the exception class name for common disconnect types
|
||||
String className = e.getClass().getSimpleName();
|
||||
return className.contains("Timeout") || className.contains("Closed");
|
||||
}
|
||||
|
||||
return message.contains("Connection reset") ||
|
||||
message.contains("Broken pipe") ||
|
||||
message.contains("connection was aborted") ||
|
||||
message.contains("An established connection was aborted") ||
|
||||
message.contains("SocketTimeout") ||
|
||||
message.contains("timed out");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse HTTP Range header and return start/end byte positions.
|
||||
* Supports formats: "bytes=start-end", "bytes=start-", "bytes=-suffix"
|
||||
*/
|
||||
RangeInfo parseRange(String rangeHeader, long fileSize) {
|
||||
if (!rangeHeader.startsWith("bytes=")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String rangeSpec = rangeHeader.substring(6).trim();
|
||||
String[] ranges = rangeSpec.split(",");
|
||||
if (ranges.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only handle first range (most common case)
|
||||
String range = ranges[0].trim();
|
||||
String[] parts = range.split("-", -1);
|
||||
if (parts.length != 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
long start, end;
|
||||
|
||||
if (parts[0].isEmpty()) {
|
||||
// Suffix range: "-500" means last 500 bytes
|
||||
long suffix = Long.parseLong(parts[1]);
|
||||
start = Math.max(0, fileSize - suffix);
|
||||
end = fileSize - 1;
|
||||
} else if (parts[1].isEmpty()) {
|
||||
// Open-ended range: "500-" means from byte 500 to end
|
||||
start = Long.parseLong(parts[0]);
|
||||
end = fileSize - 1;
|
||||
} else {
|
||||
// Full range: "500-999"
|
||||
start = Long.parseLong(parts[0]);
|
||||
end = Long.parseLong(parts[1]);
|
||||
}
|
||||
|
||||
// Validate range
|
||||
if (start < 0 || start >= fileSize || end < start) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Clamp end to file size
|
||||
end = Math.min(end, fileSize - 1);
|
||||
|
||||
return new RangeInfo(start, end);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream bytes from start to end (inclusive) using RandomAccessFile for efficient seeking.
|
||||
*/
|
||||
private void streamBytes(Path filePath, long start, long end, OutputStream outputStream) throws IOException {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "r")) {
|
||||
raf.seek(start);
|
||||
|
||||
long bytesToRead = end - start + 1;
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
long totalRead = 0;
|
||||
|
||||
while (totalRead < bytesToRead) {
|
||||
int toRead = (int) Math.min(buffer.length, bytesToRead - totalRead);
|
||||
int read = raf.read(buffer, 0, toRead);
|
||||
if (read == -1) {
|
||||
break;
|
||||
}
|
||||
outputStream.write(buffer, 0, read);
|
||||
totalRead += read;
|
||||
}
|
||||
|
||||
outputStream.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Range information holder.
|
||||
*/
|
||||
record RangeInfo(long start, long end) {}
|
||||
}
|
||||
+1
@@ -67,6 +67,7 @@ public class ReadingSessionService {
|
||||
.startTime(request.getStartTime())
|
||||
.endTime(request.getEndTime())
|
||||
.durationSeconds(request.getDurationSeconds())
|
||||
.durationFormatted(request.getDurationFormatted())
|
||||
.startProgress(request.getStartProgress())
|
||||
.endProgress(request.getEndProgress())
|
||||
.progressDelta(request.getProgressDelta())
|
||||
|
||||
@@ -146,7 +146,6 @@ public class TelemetryService {
|
||||
.bookCount(bookRepository.countByLibraryId(lib.getId()))
|
||||
.watchEnabled(lib.isWatch())
|
||||
.iconType(lib.getIconType() != null ? lib.getIconType().name() : null)
|
||||
.scanMode(lib.getScanMode() != null ? lib.getScanMode().name() : null)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -138,7 +138,7 @@ public class AppSettingService {
|
||||
)
|
||||
);
|
||||
builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true")));
|
||||
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>"));
|
||||
builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >/{title}/{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.komgaApiEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.KOMGA_API_ENABLED, "false")));
|
||||
@@ -153,6 +153,8 @@ public class AppSettingService {
|
||||
boolean finalEnabled = settingEnabled && (forceDisable == null || !forceDisable);
|
||||
builder.oidcEnabled(finalEnabled);
|
||||
|
||||
builder.diskType(appProperties.getDiskType());
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
|
||||
+22
-3
@@ -32,18 +32,24 @@ public class BookCreatorService {
|
||||
|
||||
if (existingBookOpt.isPresent()) {
|
||||
log.warn("Book already exists for file: {}", libraryFile.getFileName());
|
||||
String newHash = FileFingerprint.generateHash(libraryFile.getFullPath());
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
long fileSizeKb = calculateFileSize(libraryFile);
|
||||
String newHash = libraryFile.isFolderBased()
|
||||
? FileFingerprint.generateFolderHash(libraryFile.getFullPath())
|
||||
: FileFingerprint.generateHash(libraryFile.getFullPath());
|
||||
BookEntity existingBook = existingBookOpt.get();
|
||||
BookFileEntity primaryFile = existingBook.getPrimaryBookFile();
|
||||
primaryFile.setCurrentHash(newHash);
|
||||
primaryFile.setInitialHash(newHash);
|
||||
primaryFile.setFileSizeKb(fileSizeKb);
|
||||
primaryFile.setFolderBased(libraryFile.isFolderBased());
|
||||
existingBook.setDeleted(false);
|
||||
return existingBook;
|
||||
}
|
||||
|
||||
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
long fileSizeKb = calculateFileSize(libraryFile);
|
||||
String hash = libraryFile.isFolderBased()
|
||||
? FileFingerprint.generateFolderHash(libraryFile.getFullPath())
|
||||
: FileFingerprint.generateHash(libraryFile.getFullPath());
|
||||
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(libraryFile.getLibraryEntity())
|
||||
@@ -57,8 +63,11 @@ public class BookCreatorService {
|
||||
.fileName(libraryFile.getFileName())
|
||||
.fileSubPath(libraryFile.getFileSubPath())
|
||||
.isBookFormat(true)
|
||||
.folderBased(libraryFile.isFolderBased())
|
||||
.bookType(bookFileType)
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.initialHash(hash)
|
||||
.currentHash(hash)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
bookEntity.getBookFiles().add(bookFileEntity);
|
||||
@@ -71,6 +80,16 @@ public class BookCreatorService {
|
||||
return bookRepository.saveAndFlush(bookEntity);
|
||||
}
|
||||
|
||||
private long calculateFileSize(LibraryFile libraryFile) {
|
||||
if (libraryFile.isFolderBased()) {
|
||||
Long size = FileUtils.getFolderSizeInKb(libraryFile.getFullPath());
|
||||
return size != null ? size : 0L;
|
||||
} else {
|
||||
Long size = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
|
||||
return size != null ? size : 0L;
|
||||
}
|
||||
}
|
||||
|
||||
public void addCategoriesToBook(Set<String> categories, BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getCategories() == null) {
|
||||
bookEntity.getMetadata().setCategories(new HashSet<>());
|
||||
|
||||
+202
-5
@@ -3,7 +3,9 @@ package com.adityachandel.booklore.service.book;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.kobo.KepubConversionService;
|
||||
@@ -23,13 +25,18 @@ import org.springframework.util.FileSystemUtils;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -39,6 +46,7 @@ public class BookDownloadService {
|
||||
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookFileRepository bookFileRepository;
|
||||
private final KepubConversionService kepubConversionService;
|
||||
private final CbxConversionService cbxConversionService;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -48,12 +56,22 @@ public class BookDownloadService {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
|
||||
File bookFile = file.toFile();
|
||||
|
||||
if (!bookFile.exists()) {
|
||||
BookFileEntity primaryFile = bookEntity.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||
}
|
||||
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
|
||||
|
||||
if (!Files.exists(file)) {
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||
}
|
||||
|
||||
// Handle folder-based audiobooks - create ZIP
|
||||
if (primaryFile.isFolderBased() && Files.isDirectory(file)) {
|
||||
return downloadFolderAsZip(file, primaryFile.getFileName());
|
||||
}
|
||||
|
||||
File bookFile = file.toFile();
|
||||
|
||||
// Use FileSystemResource which properly handles file resources and closing
|
||||
Resource resource = new FileSystemResource(bookFile);
|
||||
@@ -77,10 +95,152 @@ public class BookDownloadService {
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<Resource> downloadBookFile(Long bookId, Long fileId) {
|
||||
try {
|
||||
BookFileEntity bookFileEntity = bookFileRepository.findById(fileId)
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileId));
|
||||
|
||||
// Verify the file belongs to the specified book
|
||||
if (!bookFileEntity.getBook().getId().equals(bookId)) {
|
||||
throw ApiError.FILE_NOT_FOUND.createException(fileId);
|
||||
}
|
||||
|
||||
Path file = bookFileEntity.getFullFilePath().toAbsolutePath().normalize();
|
||||
|
||||
if (!Files.exists(file)) {
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId);
|
||||
}
|
||||
|
||||
// Handle folder-based audiobooks - create ZIP
|
||||
if (bookFileEntity.isFolderBased() && Files.isDirectory(file)) {
|
||||
return downloadFolderAsZip(file, bookFileEntity.getFileName());
|
||||
}
|
||||
|
||||
File bookFile = file.toFile();
|
||||
Resource resource = new FileSystemResource(bookFile);
|
||||
|
||||
String encodedFilename = URLEncoder.encode(file.getFileName().toString(), StandardCharsets.UTF_8)
|
||||
.replace("+", "%20");
|
||||
String fallbackFilename = NON_ASCII_PATTERN.matcher(file.getFileName().toString()).replaceAll("_");
|
||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||
fallbackFilename, encodedFilename);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.contentLength(bookFile.length())
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
||||
.header(HttpHeaders.PRAGMA, "no-cache")
|
||||
.header(HttpHeaders.EXPIRES, "0")
|
||||
.body(resource);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to download book file {}: {}", fileId, e.getMessage(), e);
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(fileId);
|
||||
}
|
||||
}
|
||||
|
||||
public void downloadAllBookFiles(Long bookId, HttpServletResponse response) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
List<BookFileEntity> allFiles = bookEntity.getBookFiles();
|
||||
if (allFiles == null || allFiles.isEmpty()) {
|
||||
throw ApiError.FILE_NOT_FOUND.createException(bookId);
|
||||
}
|
||||
|
||||
// If only one file and it's not folder-based, download it directly
|
||||
if (allFiles.size() == 1) {
|
||||
BookFileEntity singleFile = allFiles.get(0);
|
||||
Path filePath = singleFile.getFullFilePath();
|
||||
|
||||
if (!Files.exists(filePath)) {
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||
}
|
||||
|
||||
// For folder-based audiobooks, let it fall through to ZIP creation
|
||||
if (!singleFile.isFolderBased() || !Files.isDirectory(filePath)) {
|
||||
File file = filePath.toFile();
|
||||
setResponseHeaders(response, file);
|
||||
streamFileToResponse(file, response);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort files by filename for consistent ordering
|
||||
allFiles.sort(Comparator.comparing(BookFileEntity::getFileName));
|
||||
|
||||
// Create ZIP with all files
|
||||
String bookTitle = bookEntity.getMetadata() != null && bookEntity.getMetadata().getTitle() != null
|
||||
? bookEntity.getMetadata().getTitle()
|
||||
: "book-" + bookId;
|
||||
String safeTitle = bookTitle.replaceAll("[^a-zA-Z0-9\\-_]", "_");
|
||||
String zipFileName = safeTitle + ".zip";
|
||||
|
||||
response.setContentType("application/zip");
|
||||
String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_");
|
||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||
fallbackFilename, encodedFilename);
|
||||
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
|
||||
|
||||
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
|
||||
for (BookFileEntity bookFile : allFiles) {
|
||||
Path filePath = bookFile.getFullFilePath();
|
||||
|
||||
if (!Files.exists(filePath)) {
|
||||
log.warn("Skipping missing file during ZIP creation: {}", filePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle folder-based audiobooks - add all files from the folder
|
||||
if (bookFile.isFolderBased() && Files.isDirectory(filePath)) {
|
||||
String folderPrefix = bookFile.getFileName() + "/";
|
||||
List<Path> audioFiles = Files.list(filePath)
|
||||
.filter(Files::isRegularFile)
|
||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||
.toList();
|
||||
|
||||
for (Path audioFile : audioFiles) {
|
||||
String entryName = folderPrefix + audioFile.getFileName().toString();
|
||||
ZipEntry zipEntry = new ZipEntry(entryName);
|
||||
zipEntry.setSize(Files.size(audioFile));
|
||||
zos.putNextEntry(zipEntry);
|
||||
|
||||
try (InputStream fis = Files.newInputStream(audioFile)) {
|
||||
fis.transferTo(zos);
|
||||
}
|
||||
|
||||
zos.closeEntry();
|
||||
}
|
||||
} else {
|
||||
// Regular file
|
||||
ZipEntry zipEntry = new ZipEntry(bookFile.getFileName());
|
||||
zipEntry.setSize(Files.size(filePath));
|
||||
zos.putNextEntry(zipEntry);
|
||||
|
||||
try (InputStream fis = Files.newInputStream(filePath)) {
|
||||
fis.transferTo(zos);
|
||||
}
|
||||
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
zos.finish();
|
||||
response.getOutputStream().flush();
|
||||
|
||||
log.info("Successfully created and streamed ZIP for book {} with {} files", bookId, allFiles.size());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to create ZIP for book {}: {}", bookId, e.getMessage(), e);
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||
}
|
||||
}
|
||||
|
||||
public void downloadKoboBook(Long bookId, HttpServletResponse response) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
|
||||
var primaryFile = bookEntity.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
throw ApiError.FAILED_TO_DOWNLOAD_FILE.createException(bookId);
|
||||
}
|
||||
boolean isEpub = primaryFile.getBookType() == BookFileType.EPUB;
|
||||
boolean isCbx = primaryFile.getBookType() == BookFileType.CBX;
|
||||
|
||||
@@ -157,4 +317,41 @@ public class BookDownloadService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ResponseEntity<Resource> downloadFolderAsZip(Path folderPath, String folderName) throws IOException {
|
||||
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
|
||||
|
||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
||||
// Get all files in the folder, sorted by name
|
||||
List<Path> files = Files.list(folderPath)
|
||||
.filter(Files::isRegularFile)
|
||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||
.toList();
|
||||
|
||||
for (Path audioFile : files) {
|
||||
ZipEntry entry = new ZipEntry(audioFile.getFileName().toString());
|
||||
zos.putNextEntry(entry);
|
||||
Files.copy(audioFile, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
byte[] zipBytes = baos.toByteArray();
|
||||
Resource resource = new org.springframework.core.io.ByteArrayResource(zipBytes);
|
||||
|
||||
String zipFileName = folderName + ".zip";
|
||||
String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
String fallbackFilename = NON_ASCII_PATTERN.matcher(zipFileName).replaceAll("_");
|
||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||
fallbackFilename, encodedFilename);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.valueOf("application/zip"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length))
|
||||
.header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate")
|
||||
.header(HttpHeaders.PRAGMA, "no-cache")
|
||||
.header(HttpHeaders.EXPIRES, "0")
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
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.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.service.file.FileMoveHelper;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.service.progress.ReadingProgressService;
|
||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class BookFileAttachmentService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final ReadingProgressService readingProgressService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final FileMoveHelper fileMoveHelper;
|
||||
private final BookMapper bookMapper;
|
||||
private final BookService bookService;
|
||||
|
||||
@Transactional
|
||||
public Book attachBookFiles(Long targetBookId, List<Long> sourceBookIds, boolean deleteSourceBooks) {
|
||||
BookEntity targetBook = bookRepository.findByIdWithBookFiles(targetBookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(targetBookId));
|
||||
|
||||
// Validate and deduplicate source book IDs
|
||||
Set<Long> uniqueSourceBookIds = new LinkedHashSet<>(sourceBookIds); // Preserves order, removes duplicates
|
||||
if (uniqueSourceBookIds.contains(targetBookId)) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Cannot attach a book to itself");
|
||||
}
|
||||
|
||||
// Load all source books upfront to avoid Hibernate auto-flush issues when loading inside loop
|
||||
List<BookEntity> sourceBooks = new ArrayList<>();
|
||||
for (Long sourceBookId : uniqueSourceBookIds) {
|
||||
BookEntity sourceBook = bookRepository.findByIdWithBookFiles(sourceBookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(sourceBookId));
|
||||
sourceBooks.add(sourceBook);
|
||||
}
|
||||
|
||||
// === VALIDATION PHASE - Do all validation BEFORE any file operations ===
|
||||
|
||||
// Validate target has a primary file
|
||||
BookFileEntity targetPrimaryFile = targetBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.GENERIC_BAD_REQUEST.createException("Target book has no primary file"));
|
||||
|
||||
// Validate all source books upfront
|
||||
for (BookEntity sourceBook : sourceBooks) {
|
||||
// Validate same library
|
||||
if (!targetBook.getLibrary().getId().equals(sourceBook.getLibrary().getId())) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " must be in the same library as target");
|
||||
}
|
||||
|
||||
// Validate source has exactly 1 book format file
|
||||
List<BookFileEntity> sourceBookFiles = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (sourceBookFiles.isEmpty()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has no book format files to attach");
|
||||
}
|
||||
|
||||
if (sourceBookFiles.size() > 1) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has multiple book format files. Only single-file books can be attached.");
|
||||
}
|
||||
|
||||
BookFileEntity fileToMove = sourceBookFiles.get(0);
|
||||
|
||||
// Validate not folder-based
|
||||
if (fileToMove.isFolderBased()) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " is a folder-based audiobook. Folder-based books cannot be attached.");
|
||||
}
|
||||
|
||||
// Validate source file exists
|
||||
Path sourceFilePath = fileToMove.getFullFilePath();
|
||||
if (!Files.exists(sourceFilePath)) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException(
|
||||
"Source file not found at expected location: " + sourceFilePath +
|
||||
". The file may have been moved, deleted, or the database record is out of sync.");
|
||||
}
|
||||
}
|
||||
|
||||
// === SETUP PHASE - Calculate paths and naming ===
|
||||
|
||||
// Get file naming pattern and determine if primary file is at pattern location
|
||||
String fileNamingPattern = fileMoveHelper.getFileNamingPattern(targetBook.getLibrary());
|
||||
String patternResolvedPath = PathPatternResolver.resolvePattern(targetBook, targetPrimaryFile, fileNamingPattern);
|
||||
Path libraryRootPath = Paths.get(targetBook.getLibraryPath().getPath());
|
||||
Path patternFullPath = libraryRootPath.resolve(patternResolvedPath);
|
||||
|
||||
// Check if primary file is at the pattern location
|
||||
Path actualPrimaryFilePath = targetPrimaryFile.getFullFilePath();
|
||||
boolean primaryFileAtPatternLocation = Files.exists(patternFullPath) &&
|
||||
patternFullPath.normalize().equals(actualPrimaryFilePath.normalize());
|
||||
|
||||
// Determine target directory - use pattern directory, fallback to library root if pattern has no directory
|
||||
Path targetDirectory = patternFullPath.getParent();
|
||||
if (targetDirectory == null) {
|
||||
// Pattern resolved to just a filename with no directory structure
|
||||
targetDirectory = libraryRootPath;
|
||||
}
|
||||
String targetFileSubPath = libraryRootPath.equals(targetDirectory)
|
||||
? ""
|
||||
: libraryRootPath.relativize(targetDirectory).toString();
|
||||
|
||||
// Use pattern-resolved filename (without extension) as base
|
||||
String patternFileName = Paths.get(patternResolvedPath).getFileName().toString();
|
||||
int lastDot = patternFileName.lastIndexOf('.');
|
||||
String baseFileName = lastDot > 0 ? patternFileName.substring(0, lastDot) : patternFileName;
|
||||
|
||||
// Validate target primary file exists (if not at pattern location)
|
||||
if (!primaryFileAtPatternLocation && !Files.exists(actualPrimaryFilePath)) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException(
|
||||
"Target book's primary file not found at expected location: " + actualPrimaryFilePath +
|
||||
". Please ensure the target book's files exist before attaching files.");
|
||||
}
|
||||
|
||||
// === FILE OPERATION PHASE - All file operations inside try-finally for monitoring cleanup ===
|
||||
|
||||
Long libraryId = targetBook.getLibrary().getId();
|
||||
List<BookEntity> sourceBooksToDelete = new ArrayList<>();
|
||||
List<Path> sourceDirectoriesToCleanup = new ArrayList<>();
|
||||
Set<Path> pathsToReregister = new HashSet<>();
|
||||
|
||||
try {
|
||||
// Unregister target directory from monitoring
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(targetDirectory);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to unregister target directory from monitoring: {}", targetDirectory, ex);
|
||||
}
|
||||
pathsToReregister.add(targetDirectory);
|
||||
|
||||
// If primary file is NOT at pattern location, move all existing target book files there first
|
||||
if (!primaryFileAtPatternLocation) {
|
||||
log.info("Primary file not at pattern location, organizing target book files first");
|
||||
|
||||
// Unregister source directories for existing files
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
Path currentPath = existingFile.getFullFilePath();
|
||||
if (Files.exists(currentPath)) {
|
||||
Path sourceDir = currentPath.getParent();
|
||||
if (sourceDir != null) {
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(sourceDir);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to unregister source directory from monitoring: {}", sourceDir, ex);
|
||||
}
|
||||
pathsToReregister.add(sourceDir);
|
||||
sourceDirectoriesToCleanup.add(sourceDir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create target directory if needed
|
||||
try {
|
||||
Files.createDirectories(targetDirectory);
|
||||
} catch (IOException e) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to create target directory: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Move all existing target book files to pattern location
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
Path currentPath = existingFile.getFullFilePath();
|
||||
if (!Files.exists(currentPath)) {
|
||||
log.warn("Skipping missing file during organization: {}", currentPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Generate pattern-resolved filename for this file
|
||||
String resolvedPath = PathPatternResolver.resolvePattern(targetBook, existingFile, fileNamingPattern);
|
||||
String newFileName = Paths.get(resolvedPath).getFileName().toString();
|
||||
|
||||
// Resolve conflicts if file already exists at destination
|
||||
newFileName = resolveFilenameConflict(targetDirectory, newFileName);
|
||||
Path destinationPath = targetDirectory.resolve(newFileName);
|
||||
|
||||
if (!currentPath.normalize().equals(destinationPath.normalize())) {
|
||||
try {
|
||||
Files.move(currentPath, destinationPath);
|
||||
log.info("Organized file from {} to {}", currentPath, destinationPath);
|
||||
|
||||
// Update database record
|
||||
existingFile.setFileSubPath(targetFileSubPath);
|
||||
existingFile.setFileName(newFileName);
|
||||
} catch (IOException e) {
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException(
|
||||
"Failed to organize file " + currentPath + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Track extension counts for handling same-extension conflicts
|
||||
// Initialize with existing extensions in target book
|
||||
Map<String, Integer> extensionCounts = new HashMap<>();
|
||||
for (BookFileEntity existingFile : targetBook.getBookFiles()) {
|
||||
if (existingFile.isBookFormat()) {
|
||||
String ext = getFileExtension(existingFile.getFileName()).toLowerCase();
|
||||
extensionCounts.merge(ext, 1, Integer::sum);
|
||||
}
|
||||
}
|
||||
|
||||
// Process each source book
|
||||
for (BookEntity sourceBook : sourceBooks) {
|
||||
BookFileEntity fileToMove = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.findFirst()
|
||||
.orElseThrow(); // Already validated above
|
||||
|
||||
Path sourceFilePath = fileToMove.getFullFilePath();
|
||||
Path sourceDirectory = sourceFilePath.getParent();
|
||||
|
||||
// Unregister source directory from monitoring to prevent spurious DELETE events
|
||||
if (sourceDirectory != null) {
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(sourceDirectory);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to unregister source directory from monitoring: {}", sourceDirectory, ex);
|
||||
}
|
||||
pathsToReregister.add(sourceDirectory);
|
||||
}
|
||||
|
||||
// Generate new filename using the base name determined earlier (from pattern or actual primary file)
|
||||
String extension = getFileExtension(fileToMove.getFileName()).toLowerCase();
|
||||
|
||||
// Handle same-extension conflicts by adding suffix (_1, _2, etc.)
|
||||
int existingCount = extensionCounts.getOrDefault(extension, 0);
|
||||
String newFileName;
|
||||
if (extension.isEmpty()) {
|
||||
// File has no extension
|
||||
newFileName = existingCount > 0
|
||||
? baseFileName + "_" + existingCount
|
||||
: baseFileName;
|
||||
} else {
|
||||
newFileName = existingCount > 0
|
||||
? baseFileName + "_" + existingCount + "." + extension
|
||||
: baseFileName + "." + extension;
|
||||
}
|
||||
extensionCounts.merge(extension, 1, Integer::sum);
|
||||
|
||||
// Final conflict check against filesystem (in case of external files)
|
||||
newFileName = resolveFilenameConflict(targetDirectory, newFileName);
|
||||
|
||||
// Move the physical file
|
||||
Path destinationPath = targetDirectory.resolve(newFileName);
|
||||
try {
|
||||
Files.move(sourceFilePath, destinationPath);
|
||||
log.info("Moved file from {} to {}", sourceFilePath, destinationPath);
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to move file from {} to {}", sourceFilePath, destinationPath, e);
|
||||
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to move file: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Update file entity with new path info - properly manage bidirectional relationship
|
||||
fileToMove.setFileSubPath(targetFileSubPath);
|
||||
fileToMove.setFileName(newFileName);
|
||||
|
||||
// Remove from source book's collection and add to target's collection
|
||||
sourceBook.getBookFiles().remove(fileToMove);
|
||||
fileToMove.setBook(targetBook);
|
||||
targetBook.getBookFiles().add(fileToMove);
|
||||
|
||||
// Track source directory for cleanup
|
||||
if (sourceDirectory != null) {
|
||||
sourceDirectoriesToCleanup.add(sourceDirectory);
|
||||
}
|
||||
|
||||
// Track source book for deletion if requested
|
||||
if (deleteSourceBooks) {
|
||||
long remainingBookFiles = sourceBook.getBookFiles().stream()
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.count();
|
||||
|
||||
if (remainingBookFiles == 0) {
|
||||
sourceBooksToDelete.add(sourceBook);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete source books after all files are moved
|
||||
if (!sourceBooksToDelete.isEmpty()) {
|
||||
bookRepository.deleteAll(sourceBooksToDelete);
|
||||
}
|
||||
|
||||
// Cleanup empty source directories
|
||||
Set<Path> libraryRoots = targetBook.getLibrary().getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.map(Paths::get)
|
||||
.map(Path::normalize)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
for (Path sourceDir : sourceDirectoriesToCleanup) {
|
||||
bookService.deleteEmptyParentDirsUpToLibraryFolders(sourceDir, libraryRoots);
|
||||
}
|
||||
} finally {
|
||||
// Re-register paths for monitoring (only if they still exist)
|
||||
for (Path path : pathsToReregister) {
|
||||
if (Files.exists(path) && Files.isDirectory(path)) {
|
||||
try {
|
||||
monitoringRegistrationService.registerSpecificPath(path, libraryId);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to re-register path for monitoring: {}", path, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return updated target book
|
||||
return getUpdatedBook(targetBookId);
|
||||
}
|
||||
|
||||
private Book getUpdatedBook(Long bookId) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookEntity refreshedTarget = bookRepository.findByIdWithBookFiles(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId)
|
||||
.orElse(new UserBookProgressEntity());
|
||||
UserBookFileProgressEntity fileProgress = readingProgressService
|
||||
.fetchUserFileProgress(user.getId(), Set.of(bookId))
|
||||
.get(bookId);
|
||||
|
||||
Book book = bookMapper.toBook(refreshedTarget);
|
||||
book.setShelves(bookService.filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
readingProgressService.enrichBookWithProgress(book, userProgress, fileProgress);
|
||||
|
||||
return book;
|
||||
}
|
||||
|
||||
private String resolveFilenameConflict(Path targetDirectory, String originalFileName) {
|
||||
Path targetPath = targetDirectory.resolve(originalFileName);
|
||||
if (!Files.exists(targetPath)) {
|
||||
return originalFileName;
|
||||
}
|
||||
|
||||
// Extract base name and extension
|
||||
String baseName;
|
||||
String extension;
|
||||
int lastDotIndex = originalFileName.lastIndexOf('.');
|
||||
if (lastDotIndex > 0) {
|
||||
baseName = originalFileName.substring(0, lastDotIndex);
|
||||
extension = originalFileName.substring(lastDotIndex);
|
||||
} else {
|
||||
baseName = originalFileName;
|
||||
extension = "";
|
||||
}
|
||||
|
||||
// Try with incrementing suffix
|
||||
int counter = 1;
|
||||
String newFileName;
|
||||
do {
|
||||
newFileName = baseName + "_" + counter + extension;
|
||||
targetPath = targetDirectory.resolve(newFileName);
|
||||
counter++;
|
||||
} while (Files.exists(targetPath) && counter < 1000);
|
||||
|
||||
if (counter >= 1000) {
|
||||
throw ApiError.GENERIC_BAD_REQUEST.createException("Could not resolve filename conflict for: " + originalFileName);
|
||||
}
|
||||
|
||||
return newFileName;
|
||||
}
|
||||
|
||||
private String getFileExtension(String fileName) {
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
int lastDotIndex = fileName.lastIndexOf('.');
|
||||
if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
|
||||
return fileName.substring(lastDotIndex + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -52,10 +52,18 @@ public class BookMarkService {
|
||||
@Transactional
|
||||
public BookMark createBookmark(CreateBookMarkRequest request) {
|
||||
Long userId = getCurrentUserId();
|
||||
validateNoDuplicateBookmark(request.getCfi(), request.getBookId(), userId);
|
||||
|
||||
// Validate no duplicate based on bookmark type
|
||||
if (request.isAudiobookBookmark()) {
|
||||
validateNoDuplicateAudiobookBookmark(request.getPositionMs(), request.getTrackIndex(), request.getBookId(), userId);
|
||||
} else if (request.getCfi() != null) {
|
||||
validateNoDuplicateBookmark(request.getCfi(), request.getBookId(), userId);
|
||||
}
|
||||
|
||||
BookMarkEntity bookmark = BookMarkEntity.builder()
|
||||
.cfi(request.getCfi())
|
||||
.positionMs(request.getPositionMs())
|
||||
.trackIndex(request.getTrackIndex())
|
||||
.title(request.getTitle())
|
||||
.book(findBook(request.getBookId()))
|
||||
.user(findUser(userId))
|
||||
@@ -126,6 +134,16 @@ public class BookMarkService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate no duplicate audiobook bookmark exists within 5 seconds of the position.
|
||||
*/
|
||||
private void validateNoDuplicateAudiobookBookmark(Long positionMs, Integer trackIndex, Long bookId, Long userId) {
|
||||
boolean exists = bookMarkRepository.existsByPositionMsNearAndBookIdAndUserId(positionMs, trackIndex, bookId, userId);
|
||||
if (exists) {
|
||||
throw new APIException("A bookmark already exists near this position", HttpStatus.CONFLICT);
|
||||
}
|
||||
}
|
||||
|
||||
private void applyUpdates(BookMarkEntity bookmark, UpdateBookMarkRequest request) {
|
||||
Optional.ofNullable(request.getTitle()).ifPresent(bookmark::setTitle);
|
||||
Optional.ofNullable(request.getCfi()).ifPresent(bookmark::setCfi);
|
||||
|
||||
+85
-25
@@ -8,15 +8,19 @@ 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.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.repository.BookFileRepository;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.service.progress.ReadingProgressService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
@@ -45,6 +49,7 @@ import java.util.stream.Collectors;
|
||||
public class BookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookFileRepository bookFileRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@@ -53,7 +58,7 @@ public class BookService {
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
private final ReadingProgressService readingProgressService;
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final BookUpdateService bookUpdateService;
|
||||
@@ -74,14 +79,18 @@ public class BookService {
|
||||
user.getId()
|
||||
);
|
||||
|
||||
Set<Long> bookIds = books.stream().map(Book::getId).collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap =
|
||||
userProgressService.fetchUserProgress(
|
||||
user.getId(),
|
||||
books.stream().map(Book::getId).collect(Collectors.toSet())
|
||||
);
|
||||
readingProgressService.fetchUserProgress(user.getId(), bookIds);
|
||||
Map<Long, UserBookFileProgressEntity> fileProgressMap =
|
||||
readingProgressService.fetchUserFileProgress(user.getId(), bookIds);
|
||||
|
||||
books.forEach(book -> {
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(book.getId()));
|
||||
readingProgressService.enrichBookWithProgress(
|
||||
book,
|
||||
progressMap.get(book.getId()),
|
||||
fileProgressMap.get(book.getId())
|
||||
);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
});
|
||||
|
||||
@@ -92,15 +101,21 @@ public class BookService {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
Set<Long> entityIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
|
||||
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
|
||||
Map<Long, UserBookProgressEntity> progressMap =
|
||||
readingProgressService.fetchUserProgress(user.getId(), entityIds);
|
||||
Map<Long, UserBookFileProgressEntity> fileProgressMap =
|
||||
readingProgressService.fetchUserFileProgress(user.getId(), entityIds);
|
||||
|
||||
return bookEntities.stream().map(bookEntity -> {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
if (!withDescription) book.getMetadata().setDescription(null);
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
readingProgressService.enrichBookWithProgress(
|
||||
book,
|
||||
progressMap.get(bookEntity.getId()),
|
||||
fileProgressMap.get(bookEntity.getId())
|
||||
);
|
||||
return book;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
@@ -109,13 +124,17 @@ public class BookService {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity());
|
||||
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId)
|
||||
.orElse(new UserBookProgressEntity());
|
||||
|
||||
// Fetch file-level progress for the book (most recent across all files)
|
||||
UserBookFileProgressEntity fileProgress = readingProgressService
|
||||
.fetchUserFileProgress(user.getId(), Set.of(bookId))
|
||||
.get(bookId);
|
||||
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
book.setLastReadTime(userProgress.getLastReadTime());
|
||||
BookProgressUtil.enrichBookWithProgress(book, userProgress);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
readingProgressService.enrichBookWithProgress(book, userProgress, fileProgress);
|
||||
|
||||
if (!withDescription) {
|
||||
book.getMetadata().setDescription(null);
|
||||
@@ -125,13 +144,17 @@ public class BookService {
|
||||
}
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
public BookViewerSettings getBookViewerSetting(long bookId, long bookFileId) {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
BookViewerSettings.BookViewerSettingsBuilder settingsBuilder = BookViewerSettings.builder();
|
||||
|
||||
BookFileType bookType = bookEntity.getPrimaryBookFile().getBookType();
|
||||
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
||||
.filter(bf -> bf.getId().equals(bookFileId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("Book file not found: " + bookFileId));
|
||||
BookFileType bookType = bookFile.getBookType();
|
||||
if (bookType == BookFileType.EPUB || bookType == BookFileType.FB2
|
||||
|| bookType == BookFileType.MOBI
|
||||
|| bookType == BookFileType.AZW3) {
|
||||
@@ -190,7 +213,7 @@ public class BookService {
|
||||
|
||||
@Transactional
|
||||
public void updateReadProgress(ReadProgressRequest request) {
|
||||
bookUpdateService.updateReadProgress(request);
|
||||
readingProgressService.updateReadProgress(request);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -239,9 +262,28 @@ public class BookService {
|
||||
return bookDownloadService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
public void downloadAllBookFiles(Long bookId, HttpServletResponse response) {
|
||||
bookDownloadService.downloadAllBookFiles(bookId, response);
|
||||
}
|
||||
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(long bookId) throws IOException {
|
||||
return getBookContent(bookId, null);
|
||||
}
|
||||
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(long bookId, String bookType) throws IOException {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
try (FileInputStream inputStream = new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
|
||||
String filePath;
|
||||
if (bookType != null) {
|
||||
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
|
||||
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
||||
.filter(bf -> bf.getBookType() == requestedType)
|
||||
.findFirst()
|
||||
.orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException("No file of type " + bookType + " found for book"));
|
||||
filePath = bookFile.getFullFilePath().toString();
|
||||
} else {
|
||||
filePath = FileUtils.getBookFullPath(bookEntity);
|
||||
}
|
||||
try (FileInputStream inputStream = new FileInputStream(filePath)) {
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)
|
||||
.body(new ByteArrayResource(inputStream.readAllBytes()));
|
||||
@@ -253,8 +295,8 @@ public class BookService {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
|
||||
List<Long> failedFileDeletions = new ArrayList<>();
|
||||
for (BookEntity book : books) {
|
||||
List<Path> fullFilePaths = book.getFullFilePaths();
|
||||
for (Path fullFilePath : fullFilePaths) {
|
||||
for (BookFileEntity bookFile : book.getBookFiles()) {
|
||||
Path fullFilePath = bookFile.getFullFilePath();
|
||||
try {
|
||||
if (Files.exists(fullFilePath)) {
|
||||
try {
|
||||
@@ -262,8 +304,15 @@ public class BookService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to unregister monitoring for path: {}", fullFilePath.getParent(), ex);
|
||||
}
|
||||
Files.delete(fullFilePath);
|
||||
log.info("Deleted book file: {}", fullFilePath);
|
||||
|
||||
// Handle folder-based audiobooks (delete directory recursively)
|
||||
if (bookFile.isFolderBased() && Files.isDirectory(fullFilePath)) {
|
||||
deleteDirectoryRecursively(fullFilePath);
|
||||
log.info("Deleted folder-based audiobook: {}", fullFilePath);
|
||||
} else {
|
||||
Files.delete(fullFilePath);
|
||||
log.info("Deleted book file: {}", fullFilePath);
|
||||
}
|
||||
|
||||
Set<Path> libraryRoots = book.getLibrary().getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
@@ -289,6 +338,16 @@ public class BookService {
|
||||
: ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response);
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (!Files.exists(path)) return;
|
||||
|
||||
try (var walk = Files.walk(path)) {
|
||||
walk.sorted(java.util.Comparator.reverseOrder())
|
||||
.map(Path::toFile)
|
||||
.forEach(java.io.File::delete);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set<Path> libraryRoots) {
|
||||
Path dir = currentDir;
|
||||
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
|
||||
@@ -355,11 +414,12 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
|
||||
public 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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
+16
-147
@@ -4,22 +4,14 @@ 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.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.model.enums.UserPermission;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.adityachandel.booklore.service.progress.ReadingProgressService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
@@ -36,9 +28,6 @@ import java.util.stream.Collectors;
|
||||
@Service
|
||||
public class BookUpdateService {
|
||||
|
||||
private static final float READING_THRESHOLD = 0.5f;
|
||||
private static final float COMPLETED_THRESHOLD = 99.5f;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@@ -49,17 +38,17 @@ public class BookUpdateService {
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
private final KoboReadingStateService koboReadingStateService;
|
||||
private final ReadingProgressService readingProgressService;
|
||||
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
if (book.getPrimaryBookFile().getBookType() == null) {
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null || primaryFile.getBookType() == null) {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
switch (book.getPrimaryBookFile().getBookType()) {
|
||||
switch (primaryFile.getBookType()) {
|
||||
case PDF -> updatePdfViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case CBX -> updateCbxViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
@@ -67,32 +56,6 @@ public class BookUpdateService {
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateReadProgress(ReadProgressRequest request) {
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(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 = findUserOrThrow(user.getId());
|
||||
progress.setUser(userEntity);
|
||||
progress.setBook(book);
|
||||
progress.setLastReadTime(Instant.now());
|
||||
|
||||
Float percentage = updateProgressByBookType(progress, book.getPrimaryBookFile().getBookType(), request);
|
||||
if (percentage != null) {
|
||||
progress.setReadStatus(calculateReadStatus(percentage));
|
||||
setProgressPercent(progress, book.getPrimaryBookFile().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();
|
||||
@@ -110,21 +73,6 @@ public class BookUpdateService {
|
||||
return buildStatusUpdateResponses(bookIds, readStatus, now, dateFinished);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<BookStatusUpdateResponse> resetProgress(List<Long> bookIds, ResetProgressType type) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
validateResetPermission(bookIds, user, type);
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
Instant now = Instant.now();
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
performReset(user.getId(), existingProgressBookIds, type, now);
|
||||
}
|
||||
|
||||
return buildResetResponses(bookIds, existingProgressBookIds, now);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PersonalRatingUpdateResponse> updatePersonalRating(List<Long> bookIds, Integer rating) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
@@ -267,40 +215,6 @@ public class BookUpdateService {
|
||||
));
|
||||
}
|
||||
|
||||
private Float updateProgressByBookType(UserBookProgressEntity progress, BookFileType bookType, ReadProgressRequest request) {
|
||||
return switch (bookType) {
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookProgress(progress, request.getEpubProgress());
|
||||
case PDF -> updatePdfProgress(progress, request.getPdfProgress());
|
||||
case CBX -> updateCbxProgress(progress, request.getCbxProgress());
|
||||
};
|
||||
}
|
||||
|
||||
private Float updateEbookProgress(UserBookProgressEntity progress, EpubProgress epubProgress) {
|
||||
if (epubProgress == null) return null;
|
||||
|
||||
progress.setEpubProgress(epubProgress.getCfi());
|
||||
progress.setEpubProgressHref(epubProgress.getHref());
|
||||
|
||||
float percentage = epubProgress.getPercentage();
|
||||
return Math.round(percentage * 10f) / 10f;
|
||||
}
|
||||
|
||||
private Float updatePdfProgress(UserBookProgressEntity progress, PdfProgress pdfProgress) {
|
||||
if (pdfProgress == null) return null;
|
||||
|
||||
progress.setPdfProgress(pdfProgress.getPage());
|
||||
float percentage = pdfProgress.getPercentage();
|
||||
return Math.round(percentage * 10f) / 10f;
|
||||
}
|
||||
|
||||
private Float updateCbxProgress(UserBookProgressEntity progress, CbxProgress cbxProgress) {
|
||||
if (cbxProgress == null) return null;
|
||||
|
||||
progress.setCbxProgress(cbxProgress.getPage());
|
||||
float percentage = cbxProgress.getPercentage();
|
||||
return Math.round(percentage * 10f) / 10f;
|
||||
}
|
||||
|
||||
private void updateExistingProgress(Long userId, Set<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
if (!bookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdateReadStatus(userId, new ArrayList<>(bookIds), status, now, dateFinished);
|
||||
@@ -336,19 +250,6 @@ public class BookUpdateService {
|
||||
return progress;
|
||||
}
|
||||
|
||||
private void performReset(Long userId, Set<Long> bookIds, ResetProgressType type, Instant now) {
|
||||
List<Long> bookIdList = new ArrayList<>(bookIds);
|
||||
|
||||
switch (type) {
|
||||
case BOOKLORE -> userBookProgressRepository.bulkResetBookloreProgress(userId, bookIdList, now);
|
||||
case KOREADER -> userBookProgressRepository.bulkResetKoreaderProgress(userId, bookIdList);
|
||||
case KOBO -> {
|
||||
userBookProgressRepository.bulkResetKoboProgress(userId, bookIdList);
|
||||
bookIds.forEach(koboReadingStateService::deleteReadingState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createProgressForRating(Long userId, List<Long> allBookIds, Set<Long> existingBookIds, Integer rating) {
|
||||
Set<Long> newProgressBookIds = allBookIds.stream()
|
||||
.filter(id -> !existingBookIds.contains(id))
|
||||
@@ -398,18 +299,24 @@ public class BookUpdateService {
|
||||
|
||||
private List<Book> buildBooksWithProgress(List<BookEntity> bookEntities, Long userId) {
|
||||
Set<Long> bookIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(userId, bookIds);
|
||||
Map<Long, UserBookProgressEntity> progressMap = readingProgressService.fetchUserProgress(userId, bookIds);
|
||||
Map<Long, UserBookFileProgressEntity> fileProgressMap = readingProgressService.fetchUserFileProgress(userId, bookIds);
|
||||
|
||||
return bookEntities.stream()
|
||||
.map(bookEntity -> buildBook(bookEntity, userId, progressMap))
|
||||
.map(bookEntity -> buildBook(bookEntity, userId, progressMap, fileProgressMap))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Book buildBook(BookEntity bookEntity, Long userId, Map<Long, UserBookProgressEntity> progressMap) {
|
||||
private Book buildBook(BookEntity bookEntity, Long userId,
|
||||
Map<Long, UserBookProgressEntity> progressMap,
|
||||
Map<Long, UserBookFileProgressEntity> fileProgressMap) {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), userId));
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
readingProgressService.enrichBookWithProgress(
|
||||
book,
|
||||
progressMap.get(bookEntity.getId()),
|
||||
fileProgressMap.get(bookEntity.getId())
|
||||
);
|
||||
return book;
|
||||
}
|
||||
|
||||
@@ -424,18 +331,6 @@ public class BookUpdateService {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateResetPermission(List<Long> bookIds, BookLoreUser user, ResetProgressType type) {
|
||||
if (bookIds.size() <= 1) return;
|
||||
UserPermission permission = switch (type) {
|
||||
case BOOKLORE -> UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS;
|
||||
case KOREADER -> UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS;
|
||||
default -> null;
|
||||
};
|
||||
if (permission != null && !permission.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> validateBooksAndGetExistingProgress(Long userId, List<Long> bookIds) {
|
||||
long existingBooksCount = bookRepository.countByIdIn(bookIds);
|
||||
if (existingBooksCount != bookIds.size()) {
|
||||
@@ -445,20 +340,6 @@ public class BookUpdateService {
|
||||
return userBookProgressRepository.findExistingProgressBookIds(userId, new HashSet<>(bookIds));
|
||||
}
|
||||
|
||||
private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) {
|
||||
switch (type) {
|
||||
case EPUB, FB2, MOBI, AZW3 -> progress.setEpubProgressPercent(percentage);
|
||||
case PDF -> progress.setPdfProgressPercent(percentage);
|
||||
case CBX -> progress.setCbxProgressPercent(percentage);
|
||||
}
|
||||
}
|
||||
|
||||
private ReadStatus calculateReadStatus(Float percentage) {
|
||||
if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ;
|
||||
if (percentage > READING_THRESHOLD) return ReadStatus.READING;
|
||||
return ReadStatus.UNREAD;
|
||||
}
|
||||
|
||||
private List<BookStatusUpdateResponse> buildStatusUpdateResponses(List<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
@@ -470,17 +351,6 @@ public class BookUpdateService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<BookStatusUpdateResponse> buildResetResponses(List<Long> bookIds, Set<Long> existingBookIds, Instant now) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(null)
|
||||
.readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null)
|
||||
.dateFinished(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<PersonalRatingUpdateResponse> buildRatingUpdateResponses(List<Long> bookIds, Integer rating) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
@@ -497,4 +367,3 @@ public class BookUpdateService {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package com.adityachandel.booklore.service.book;
|
||||
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.request.CreatePhysicalBookRequest;
|
||||
import com.adityachandel.booklore.model.entity.AuthorEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.repository.AuthorRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CategoryRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class PhysicalBookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final AuthorRepository authorRepository;
|
||||
private final CategoryRepository categoryRepository;
|
||||
private final BookMapper bookMapper;
|
||||
|
||||
@Transactional
|
||||
public Book createPhysicalBook(CreatePhysicalBookRequest request) {
|
||||
LibraryEntity library = libraryRepository.findById(request.getLibraryId())
|
||||
.orElseThrow(() -> new APIException("Library not found with id: " + request.getLibraryId(), HttpStatus.NOT_FOUND));
|
||||
|
||||
BookEntity bookEntity = BookEntity.builder()
|
||||
.library(library)
|
||||
.libraryPath(null)
|
||||
.isPhysical(true)
|
||||
.addedOn(Instant.now())
|
||||
.bookFiles(new ArrayList<>())
|
||||
.build();
|
||||
|
||||
BookMetadataEntity metadata = BookMetadataEntity.builder()
|
||||
.book(bookEntity)
|
||||
.title(request.getTitle())
|
||||
.description(request.getDescription())
|
||||
.publisher(request.getPublisher())
|
||||
.publishedDate(parsePublishedDate(request.getPublishedDate()))
|
||||
.language(request.getLanguage())
|
||||
.pageCount(request.getPageCount())
|
||||
.isbn13(extractIsbn13(request.getIsbn()))
|
||||
.isbn10(extractIsbn10(request.getIsbn()))
|
||||
.build();
|
||||
|
||||
bookEntity.setMetadata(metadata);
|
||||
|
||||
if (request.getAuthors() != null && !request.getAuthors().isEmpty()) {
|
||||
addAuthorsToBook(new HashSet<>(request.getAuthors()), bookEntity);
|
||||
}
|
||||
|
||||
if (request.getCategories() != null && !request.getCategories().isEmpty()) {
|
||||
addCategoriesToBook(new HashSet<>(request.getCategories()), bookEntity);
|
||||
}
|
||||
|
||||
BookEntity savedBook = bookRepository.save(bookEntity);
|
||||
log.info("Created physical book '{}' in library {} with id {}", request.getTitle(), library.getName(), savedBook.getId());
|
||||
|
||||
return bookMapper.toBook(savedBook);
|
||||
}
|
||||
|
||||
private LocalDate parsePublishedDate(String publishedDate) {
|
||||
if (publishedDate == null || publishedDate.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = publishedDate.trim();
|
||||
// Try full date format first (YYYY-MM-DD)
|
||||
try {
|
||||
return LocalDate.parse(trimmed, DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
} catch (DateTimeParseException ignored) {}
|
||||
// Try year only format (YYYY)
|
||||
try {
|
||||
int year = Integer.parseInt(trimmed);
|
||||
return LocalDate.of(year, 1, 1);
|
||||
} catch (NumberFormatException ignored) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String extractIsbn13(String isbn) {
|
||||
if (isbn == null) return null;
|
||||
String cleaned = isbn.replaceAll("[^0-9X]", "");
|
||||
return cleaned.length() == 13 ? cleaned : null;
|
||||
}
|
||||
|
||||
private String extractIsbn10(String isbn) {
|
||||
if (isbn == null) return null;
|
||||
String cleaned = isbn.replaceAll("[^0-9X]", "");
|
||||
return cleaned.length() == 10 ? cleaned : null;
|
||||
}
|
||||
|
||||
private void addAuthorsToBook(Set<String> authors, BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getAuthors() == null) {
|
||||
bookEntity.getMetadata().setAuthors(new HashSet<>());
|
||||
}
|
||||
authors.stream()
|
||||
.map(authorName -> truncate(authorName, 255))
|
||||
.map(authorName -> authorRepository.findByName(authorName)
|
||||
.orElseGet(() -> authorRepository.save(AuthorEntity.builder().name(authorName).build())))
|
||||
.forEach(authorEntity -> bookEntity.getMetadata().getAuthors().add(authorEntity));
|
||||
bookEntity.getMetadata().updateSearchText();
|
||||
}
|
||||
|
||||
private void addCategoriesToBook(Set<String> categories, BookEntity bookEntity) {
|
||||
if (bookEntity.getMetadata().getCategories() == null) {
|
||||
bookEntity.getMetadata().setCategories(new HashSet<>());
|
||||
}
|
||||
categories.stream()
|
||||
.map(cat -> truncate(cat, 255))
|
||||
.map(truncated -> categoryRepository.findByName(truncated)
|
||||
.orElseGet(() -> categoryRepository.save(CategoryEntity.builder().name(truncated).build())))
|
||||
.forEach(catEntity -> bookEntity.getMetadata().getCategories().add(catEntity));
|
||||
}
|
||||
|
||||
private String truncate(String input, int maxLength) {
|
||||
if (input == null) return null;
|
||||
return input.length() <= maxLength ? input : input.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.bookdrop;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
@@ -64,7 +65,7 @@ public class BookdropMetadataService {
|
||||
|
||||
List<MetadataProvider> providers = metadataRefreshService.prepareProviders(refreshOptions);
|
||||
Book book = Book.builder()
|
||||
.fileName(entity.getFileName())
|
||||
.primaryFile(BookFile.builder().fileName(entity.getFileName()).build())
|
||||
.metadata(initial)
|
||||
.build();
|
||||
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ public class BookEventBroadcaster {
|
||||
.forEach(u -> {
|
||||
String username = u.getUsername();
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.BOOK_ADD.getPath(), book);
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), LogNotification.info("Book added: " + book.getFileName()));
|
||||
messagingTemplate.convertAndSendToUser(username, Topic.LOG.getPath(), LogNotification.info("Book added: " + (book.getPrimaryFile() != null ? book.getPrimaryFile().getFileName() : "unknown")));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+63
-2
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
@@ -15,14 +16,18 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -57,8 +62,15 @@ public class AdditionalFileService {
|
||||
try {
|
||||
monitoringRegistrationService.unregisterSpecificPath(file.getFullFilePath().getParent());
|
||||
|
||||
Files.deleteIfExists(file.getFullFilePath());
|
||||
log.info("Deleted additional file: {}", file.getFullFilePath());
|
||||
Path filePath = file.getFullFilePath();
|
||||
if (file.isFolderBased() && Files.isDirectory(filePath)) {
|
||||
// For folder-based audiobooks, delete the entire directory
|
||||
deleteDirectoryRecursively(filePath);
|
||||
log.info("Deleted folder-based audiobook: {}", filePath);
|
||||
} else {
|
||||
Files.deleteIfExists(filePath);
|
||||
log.info("Deleted additional file: {}", filePath);
|
||||
}
|
||||
|
||||
additionalFileRepository.delete(file);
|
||||
} catch (IOException e) {
|
||||
@@ -67,6 +79,16 @@ public class AdditionalFileService {
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (!Files.exists(path)) return;
|
||||
|
||||
try (var walk = Files.walk(path)) {
|
||||
walk.sorted(java.util.Comparator.reverseOrder())
|
||||
.map(Path::toFile)
|
||||
.forEach(java.io.File::delete);
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<Resource> downloadAdditionalFile(Long fileId) throws IOException {
|
||||
Optional<BookFileEntity> fileOpt = additionalFileRepository.findById(fileId);
|
||||
if (fileOpt.isEmpty()) {
|
||||
@@ -80,6 +102,11 @@ public class AdditionalFileService {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
// Handle folder-based audiobooks - create a ZIP file
|
||||
if (file.isFolderBased() && Files.isDirectory(filePath)) {
|
||||
return downloadFolderAsZip(file, filePath);
|
||||
}
|
||||
|
||||
Resource resource = new UrlResource(filePath.toUri());
|
||||
|
||||
String encodedFilename = URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8).replace("+", "%20");
|
||||
@@ -91,4 +118,38 @@ public class AdditionalFileService {
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||
.body(resource);
|
||||
}
|
||||
|
||||
private ResponseEntity<Resource> downloadFolderAsZip(BookFileEntity file, Path folderPath) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
|
||||
// Get all files in the folder, sorted by name
|
||||
List<Path> files = Files.list(folderPath)
|
||||
.filter(Files::isRegularFile)
|
||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||
.toList();
|
||||
|
||||
for (Path audioFile : files) {
|
||||
ZipEntry entry = new ZipEntry(audioFile.getFileName().toString());
|
||||
zos.putNextEntry(entry);
|
||||
Files.copy(audioFile, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
byte[] zipBytes = baos.toByteArray();
|
||||
Resource resource = new ByteArrayResource(zipBytes);
|
||||
|
||||
String zipFileName = file.getFileName() + ".zip";
|
||||
String encodedFilename = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replace("+", "%20");
|
||||
String fallbackFilename = NON_ASCII.matcher(zipFileName).replaceAll("_");
|
||||
String contentDisposition = String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s",
|
||||
fallbackFilename, encodedFilename);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.valueOf("application/zip"))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
|
||||
.header(HttpHeaders.CONTENT_LENGTH, String.valueOf(zipBytes.length))
|
||||
.body(resource);
|
||||
}
|
||||
}
|
||||
|
||||
+51
@@ -2,9 +2,12 @@ package com.adityachandel.booklore.service.file;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
public class FileFingerprint {
|
||||
|
||||
@@ -38,4 +41,52 @@ public class FileFingerprint {
|
||||
throw new RuntimeException("Failed to compute partial MD5 hash for: " + filePath, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a hash for a folder-based audiobook.
|
||||
* Uses the first audio file's hash combined with the file count.
|
||||
*/
|
||||
public static String generateFolderHash(Path folderPath) {
|
||||
try {
|
||||
if (!Files.exists(folderPath) || !Files.isDirectory(folderPath)) {
|
||||
throw new RuntimeException("Folder does not exist: " + folderPath);
|
||||
}
|
||||
|
||||
List<Path> audioFiles = Files.list(folderPath)
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(p -> isAudioFile(p.getFileName().toString()))
|
||||
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
|
||||
.toList();
|
||||
|
||||
if (audioFiles.isEmpty()) {
|
||||
throw new RuntimeException("No audio files in folder: " + folderPath);
|
||||
}
|
||||
|
||||
// Hash first file and combine with file count for a representative hash
|
||||
String firstFileHash = generateHash(audioFiles.getFirst());
|
||||
int fileCount = audioFiles.size();
|
||||
|
||||
MessageDigest md5 = MessageDigest.getInstance("MD5");
|
||||
md5.update(firstFileHash.getBytes());
|
||||
md5.update(String.valueOf(fileCount).getBytes());
|
||||
|
||||
byte[] hash = md5.digest();
|
||||
StringBuilder result = new StringBuilder(hash.length * 2);
|
||||
for (byte b : hash) {
|
||||
result.append(String.format("%02x", b));
|
||||
}
|
||||
return result.toString();
|
||||
|
||||
} catch (IOException | NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("Failed to compute folder hash for: " + folderPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isAudioFile(String fileName) {
|
||||
if (fileName == null) return false;
|
||||
String lower = fileName.toLowerCase();
|
||||
return lower.endsWith(".mp3") || lower.endsWith(".m4a") || lower.endsWith(".m4b")
|
||||
|| lower.endsWith(".flac") || lower.endsWith(".ogg") || lower.endsWith(".opus")
|
||||
|| lower.endsWith(".aac");
|
||||
}
|
||||
}
|
||||
|
||||
+8
-1
@@ -56,6 +56,13 @@ public class FileMoveHelper {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean validateSourceExists(Path sourcePath, boolean isFolderBased) {
|
||||
if (isFolderBased) {
|
||||
return Files.isDirectory(sourcePath);
|
||||
}
|
||||
return Files.exists(sourcePath);
|
||||
}
|
||||
|
||||
public void moveFile(Path source, Path target) throws IOException {
|
||||
if (!waitForFileAccessible(source)) {
|
||||
throw new NoSuchFileException(source.toString(), null, "Source file not accessible after retries");
|
||||
@@ -161,7 +168,7 @@ public class FileMoveHelper {
|
||||
}
|
||||
|
||||
public Path generateNewFilePath(BookEntity book, BookFileEntity bookFile, LibraryPathEntity libraryPathEntity, String pattern) {
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book, bookFile, pattern);
|
||||
String newRelativePathStr = PathPatternResolver.resolvePattern(book, bookFile, pattern, bookFile.isFolderBased());
|
||||
if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) {
|
||||
newRelativePathStr = newRelativePathStr.substring(1);
|
||||
}
|
||||
|
||||
+132
-18
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service.file;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.LibraryMapper;
|
||||
import com.adityachandel.booklore.model.dto.FileMoveResult;
|
||||
@@ -31,6 +32,7 @@ public class FileMoveService {
|
||||
|
||||
private static final long EVENT_DRAIN_TIMEOUT_MS = 300;
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookFileRepository;
|
||||
private final LibraryRepository libraryRepository;
|
||||
@@ -45,10 +47,12 @@ public class FileMoveService {
|
||||
@Transactional
|
||||
public void bulkMoveFiles(FileMoveRequest request) {
|
||||
List<FileMoveRequest.Move> moves = request.getMoves();
|
||||
|
||||
|
||||
validateLocalStorage();
|
||||
|
||||
Set<Long> allAffectedLibraryIds = collectAllAffectedLibraryIds(moves);
|
||||
Set<Path> libraryPaths = monitoringRegistrationService.getPathsForLibraries(allAffectedLibraryIds);
|
||||
|
||||
|
||||
log.info("Unregistering {} libraries before bulk file move", allAffectedLibraryIds.size());
|
||||
monitoringRegistrationService.unregisterLibraries(allAffectedLibraryIds);
|
||||
monitoringRegistrationService.waitForEventsDrainedByPaths(libraryPaths, EVENT_DRAIN_TIMEOUT_MS);
|
||||
@@ -133,6 +137,16 @@ public class FileMoveService {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate all source paths exist before attempting moves
|
||||
for (var bookFile : bookEntity.getBookFiles()) {
|
||||
Path sourcePath = bookFile.getFullFilePath();
|
||||
if (!fileMoveHelper.validateSourceExists(sourcePath, bookFile.isFolderBased())) {
|
||||
log.warn("Source {} not found: bookId={}, path={}",
|
||||
bookFile.isFolderBased() ? "folder" : "file", bookId, sourcePath);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (var bookFile : bookEntity.getBookFiles()) {
|
||||
Path sourcePath = bookFile.getFullFilePath();
|
||||
Path targetPath;
|
||||
@@ -157,6 +171,13 @@ public class FileMoveService {
|
||||
return;
|
||||
}
|
||||
|
||||
// Commit file moves FIRST before updating database
|
||||
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
|
||||
fileMoveHelper.commitMove(planned.temp(), planned.target());
|
||||
}
|
||||
plannedMovesByBookFileId.clear();
|
||||
|
||||
// Only update database after all file commits succeed
|
||||
for (var bookFile : bookEntity.getBookFiles()) {
|
||||
String newFileName;
|
||||
if (bookFile.isBook()) {
|
||||
@@ -170,11 +191,6 @@ public class FileMoveService {
|
||||
|
||||
bookRepository.updateLibrary(bookEntity.getId(), targetLibrary.getId(), libraryPathEntity);
|
||||
|
||||
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
|
||||
fileMoveHelper.commitMove(planned.temp(), planned.target());
|
||||
}
|
||||
plannedMovesByBookFileId.clear();
|
||||
|
||||
Path libraryRoot = Paths.get(libraryPathEntity.getPath()).toAbsolutePath().normalize();
|
||||
for (Path sourceParent : sourceParentsToCleanup) {
|
||||
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(sourceParent, Set.of(libraryRoot));
|
||||
@@ -197,42 +213,124 @@ public class FileMoveService {
|
||||
|
||||
@Transactional
|
||||
public FileMoveResult moveSingleFile(BookEntity bookEntity) {
|
||||
record PlannedMove(Path source, Path temp, Path target) {}
|
||||
|
||||
validateLocalStorage();
|
||||
|
||||
Long libraryId = bookEntity.getLibraryPath().getLibrary().getId();
|
||||
Path libraryRoot = Paths.get(bookEntity.getLibraryPath().getPath()).toAbsolutePath().normalize();
|
||||
boolean isLibraryMonitoredWhenCalled = false;
|
||||
Map<Long, PlannedMove> plannedMovesByBookFileId = new HashMap<>();
|
||||
Set<Path> sourceParentsToCleanup = new HashSet<>();
|
||||
|
||||
try {
|
||||
Set<Path> existingPaths = monitoringRegistrationService.getPathsForLibraries(Set.of(libraryId));
|
||||
isLibraryMonitoredWhenCalled = monitoringRegistrationService.isLibraryMonitored(libraryId) || !existingPaths.isEmpty();
|
||||
|
||||
String pattern = fileMoveHelper.getFileNamingPattern(bookEntity.getLibraryPath().getLibrary());
|
||||
Path currentFilePath = bookEntity.getFullFilePath();
|
||||
Path expectedFilePath = fileMoveHelper.generateNewFilePath(bookEntity, bookEntity.getLibraryPath(), pattern);
|
||||
// Ensure bookFiles are loaded
|
||||
BookEntity bookWithFiles = bookEntity;
|
||||
if (bookEntity.getBookFiles() == null || bookEntity.getBookFiles().isEmpty()) {
|
||||
Optional<BookEntity> optionalBook = bookRepository.findByIdWithBookFiles(bookEntity.getId());
|
||||
if (optionalBook.isEmpty()) {
|
||||
log.warn("Book not found for move operation: bookId={}", bookEntity.getId());
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
bookWithFiles = optionalBook.get();
|
||||
}
|
||||
|
||||
if (currentFilePath.equals(expectedFilePath)) {
|
||||
if (bookWithFiles.getBookFiles() == null || bookWithFiles.getBookFiles().isEmpty()) {
|
||||
log.warn("Book has no files to move: bookId={}", bookEntity.getId());
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
|
||||
log.info("File for book ID {} needs to be moved from {} to {} to match library pattern", bookEntity.getId(), currentFilePath, expectedFilePath);
|
||||
String pattern = fileMoveHelper.getFileNamingPattern(bookWithFiles.getLibraryPath().getLibrary());
|
||||
Path currentPrimaryFilePath = bookWithFiles.getFullFilePath();
|
||||
Path expectedPrimaryFilePath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookWithFiles.getLibraryPath(), pattern);
|
||||
|
||||
if (currentPrimaryFilePath.equals(expectedPrimaryFilePath)) {
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
|
||||
log.info("Files for book ID {} need to be moved to match library pattern", bookWithFiles.getId());
|
||||
|
||||
String newFileSubPath = fileMoveHelper.extractSubPath(expectedPrimaryFilePath, bookWithFiles.getLibraryPath());
|
||||
Path targetParentDir = expectedPrimaryFilePath.getParent();
|
||||
|
||||
if (targetParentDir == null) {
|
||||
log.warn("Target parent directory could not be determined for move operation: bookId={}", bookWithFiles.getId());
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
|
||||
// Validate all source paths exist before attempting moves
|
||||
for (var bookFile : bookWithFiles.getBookFiles()) {
|
||||
Path sourcePath = bookFile.getFullFilePath();
|
||||
if (!fileMoveHelper.validateSourceExists(sourcePath, bookFile.isFolderBased())) {
|
||||
log.warn("Source {} not found: bookId={}, path={}",
|
||||
bookFile.isFolderBased() ? "folder" : "file", bookWithFiles.getId(), sourcePath);
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
}
|
||||
|
||||
if (isLibraryMonitoredWhenCalled) {
|
||||
log.debug("Unregistering library {} before moving a single file", libraryId);
|
||||
log.debug("Unregistering library {} before moving files", libraryId);
|
||||
fileMoveHelper.unregisterLibrary(libraryId);
|
||||
monitoringRegistrationService.waitForEventsDrainedByPaths(existingPaths, EVENT_DRAIN_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
fileMoveHelper.moveFile(currentFilePath, expectedFilePath);
|
||||
// Stage all files to temp locations
|
||||
for (var bookFile : bookWithFiles.getBookFiles()) {
|
||||
Path sourcePath = bookFile.getFullFilePath();
|
||||
Path targetPath;
|
||||
if (bookFile.isBook()) {
|
||||
targetPath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookFile, bookWithFiles.getLibraryPath(), pattern);
|
||||
} else {
|
||||
targetPath = targetParentDir.resolve(bookFile.getFileName());
|
||||
}
|
||||
|
||||
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(currentFilePath.getParent(), Set.of(libraryRoot));
|
||||
if (sourcePath.equals(targetPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Path tempPath = fileMoveHelper.moveFileWithBackup(sourcePath);
|
||||
plannedMovesByBookFileId.put(bookFile.getId(), new PlannedMove(sourcePath, tempPath, targetPath));
|
||||
if (sourcePath.getParent() != null) {
|
||||
sourceParentsToCleanup.add(sourcePath.getParent());
|
||||
}
|
||||
}
|
||||
|
||||
if (plannedMovesByBookFileId.isEmpty()) {
|
||||
return FileMoveResult.builder().moved(false).build();
|
||||
}
|
||||
|
||||
// Commit all file moves FIRST before updating database
|
||||
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
|
||||
fileMoveHelper.commitMove(planned.temp(), planned.target());
|
||||
}
|
||||
plannedMovesByBookFileId.clear();
|
||||
|
||||
// Update database for ALL BookFileEntity records (only after all commits succeed)
|
||||
for (var bookFile : bookWithFiles.getBookFiles()) {
|
||||
String newFileName;
|
||||
if (bookFile.isBook()) {
|
||||
Path targetPath = fileMoveHelper.generateNewFilePath(bookWithFiles, bookFile, bookWithFiles.getLibraryPath(), pattern);
|
||||
newFileName = targetPath.getFileName().toString();
|
||||
} else {
|
||||
newFileName = bookFile.getFileName();
|
||||
}
|
||||
bookFileRepository.updateFileNameAndSubPath(bookFile.getId(), newFileName, newFileSubPath);
|
||||
}
|
||||
|
||||
// Clean up empty parent directories
|
||||
for (Path sourceParent : sourceParentsToCleanup) {
|
||||
fileMoveHelper.deleteEmptyParentDirsUpToLibraryFolders(sourceParent, Set.of(libraryRoot));
|
||||
}
|
||||
|
||||
if (isLibraryMonitoredWhenCalled) {
|
||||
// Ensure any file system events from the move and cleanup are drained/ignored while we are still unregistered
|
||||
sleep(EVENT_DRAIN_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
String newFileName = expectedFilePath.getFileName().toString();
|
||||
String newFileSubPath = fileMoveHelper.extractSubPath(expectedFilePath, bookEntity.getLibraryPath());
|
||||
String newFileName = expectedPrimaryFilePath.getFileName().toString();
|
||||
|
||||
return FileMoveResult.builder()
|
||||
.moved(true)
|
||||
@@ -240,8 +338,13 @@ public class FileMoveService {
|
||||
.newFileSubPath(newFileSubPath)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to move file for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
log.error("Failed to move files for book ID {}: {}", bookEntity.getId(), e.getMessage(), e);
|
||||
} finally {
|
||||
// Rollback any uncommitted moves
|
||||
for (PlannedMove planned : plannedMovesByBookFileId.values()) {
|
||||
fileMoveHelper.rollbackMove(planned.temp(), planned.source());
|
||||
}
|
||||
|
||||
if (isLibraryMonitoredWhenCalled) {
|
||||
log.debug("Registering library paths for library {} with root {}", libraryId, libraryRoot);
|
||||
LibraryEntity libraryEntity = bookEntity.getLibraryPath().getLibrary();
|
||||
@@ -262,4 +365,15 @@ public class FileMoveService {
|
||||
throw new RuntimeException("Sleep interrupted", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateLocalStorage() {
|
||||
String diskType = appProperties.getDiskType();
|
||||
if (!"LOCAL".equalsIgnoreCase(diskType)) {
|
||||
throw new IllegalStateException(
|
||||
"File move operations are only supported on local storage. " +
|
||||
"Current disk type is configured as: " + diskType + ". " +
|
||||
"If you are using local storage, set DISK_TYPE=LOCAL in your environment."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -47,7 +47,9 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
@Override
|
||||
public FileProcessResult processFile(LibraryFile libraryFile) {
|
||||
Path path = libraryFile.getFullPath();
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
String hash = libraryFile.isFolderBased()
|
||||
? FileFingerprint.generateFolderHash(path)
|
||||
: FileFingerprint.generateHash(path);
|
||||
Book book = createAndMapBook(libraryFile, hash);
|
||||
return new FileProcessResult(book, FileProcessStatus.NEW);
|
||||
}
|
||||
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.AudiobookMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AudiobookProcessor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
|
||||
|
||||
public AudiobookProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService,
|
||||
AudiobookMetadataExtractor audiobookMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.audiobookMetadataExtractor = audiobookMetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.AUDIOBOOK);
|
||||
setBookMetadata(bookEntity, libraryFile.isFolderBased());
|
||||
if (generateCover(bookEntity, libraryFile.isFolderBased())) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
return generateCover(bookEntity, bookEntity.getPrimaryBookFile().isFolderBased());
|
||||
}
|
||||
|
||||
public boolean generateCover(BookEntity bookEntity, boolean isFolderBased) {
|
||||
try {
|
||||
File audioFile = getAudioFileForMetadata(bookEntity, isFolderBased);
|
||||
if (audioFile == null || !audioFile.exists()) {
|
||||
log.debug("Audio file not found for audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] coverData = audiobookMetadataExtractor.extractCover(audioFile);
|
||||
|
||||
if (coverData == null) {
|
||||
log.debug("No cover image found in audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean saved;
|
||||
try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) {
|
||||
BufferedImage originalImage = FileService.readImage(bais);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return false;
|
||||
}
|
||||
saved = fileService.saveCoverImages(originalImage, bookEntity.getId());
|
||||
originalImage.flush();
|
||||
}
|
||||
|
||||
return saved;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for audiobook '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the audio file to use for metadata extraction.
|
||||
* For folder-based audiobooks, returns the first audio file in the folder.
|
||||
*/
|
||||
private File getAudioFileForMetadata(BookEntity bookEntity, boolean isFolderBased) {
|
||||
if (isFolderBased) {
|
||||
java.nio.file.Path folderPath = bookEntity.getFullFilePath();
|
||||
return FileUtils.getFirstAudioFileInFolder(folderPath)
|
||||
.map(java.nio.file.Path::toFile)
|
||||
.orElse(null);
|
||||
} else {
|
||||
return new File(FileUtils.getBookFullPath(bookEntity));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.AUDIOBOOK);
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity, boolean isFolderBased) {
|
||||
File bookFile = getAudioFileForMetadata(bookEntity, isFolderBased);
|
||||
if (bookFile == null || !bookFile.exists()) {
|
||||
log.warn("Audio file not found for metadata extraction: {}", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
BookMetadata audioMetadata = audiobookMetadataExtractor.extractMetadata(bookFile);
|
||||
if (audioMetadata == null) return;
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
metadata.setTitle(truncate(audioMetadata.getTitle(), 1000));
|
||||
metadata.setSubtitle(truncate(audioMetadata.getSubtitle(), 1000));
|
||||
metadata.setDescription(truncate(audioMetadata.getDescription(), 2000));
|
||||
metadata.setPublisher(truncate(audioMetadata.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(audioMetadata.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(audioMetadata.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(audioMetadata.getSeriesNumber());
|
||||
metadata.setSeriesTotal(audioMetadata.getSeriesTotal());
|
||||
|
||||
String lang = audioMetadata.getLanguage();
|
||||
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||
|
||||
bookCreatorService.addAuthorsToBook(audioMetadata.getAuthors(), bookEntity);
|
||||
|
||||
if (audioMetadata.getCategories() != null) {
|
||||
Set<String> validCategories = audioMetadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.collect(Collectors.toSet());
|
||||
bookCreatorService.addCategoriesToBook(validCategories, bookEntity);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -17,8 +17,11 @@ public class KoboCompatibilityService {
|
||||
if (book == null) {
|
||||
throw new IllegalArgumentException("Book cannot be null");
|
||||
}
|
||||
|
||||
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
return false;
|
||||
}
|
||||
BookFileType bookType = primaryFile.getBookType();
|
||||
if (bookType == null) {
|
||||
return false;
|
||||
@@ -45,7 +48,7 @@ public class KoboCompatibilityService {
|
||||
}
|
||||
|
||||
public boolean meetsCbxConversionSizeLimit(BookEntity book) {
|
||||
if (book == null || book.getPrimaryBookFile().getBookType() != BookFileType.CBX) {
|
||||
if (book == null || book.getPrimaryBookFile() == null || book.getPrimaryBookFile().getBookType() != BookFileType.CBX) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -86,7 +86,7 @@ public class KoboEntitlementService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
return books.stream()
|
||||
.filter(bookEntity -> bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB)
|
||||
.filter(bookEntity -> bookEntity.getPrimaryBookFile() != null && bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB)
|
||||
.map(book -> ChangedProductMetadata.builder()
|
||||
.changedProductMetadata(BookEntitlementContainer.builder()
|
||||
.bookEntitlement(buildBookEntitlement(book, false))
|
||||
@@ -233,6 +233,9 @@ public class KoboEntitlementService {
|
||||
KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings();
|
||||
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
return null;
|
||||
}
|
||||
boolean isEpubFile = primaryFile.getBookType() == BookFileType.EPUB;
|
||||
boolean isCbxFile = primaryFile.getBookType() == BookFileType.CBX;
|
||||
|
||||
|
||||
+37
-14
@@ -7,13 +7,11 @@ import com.adityachandel.booklore.model.dto.KoboSyncSettings;
|
||||
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
|
||||
import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper;
|
||||
import com.adityachandel.booklore.model.dto.response.kobo.KoboReadingStateResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoboReadingStateEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.KoboReadingStateRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookFileProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
|
||||
@@ -37,6 +35,7 @@ public class KoboReadingStateService {
|
||||
private final KoboReadingStateRepository repository;
|
||||
private final KoboReadingStateMapper mapper;
|
||||
private final UserBookProgressRepository progressRepository;
|
||||
private final UserBookFileProgressRepository fileProgressRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
@@ -124,20 +123,20 @@ public class KoboReadingStateService {
|
||||
private void syncKoboProgressToUserBookProgress(KoboReadingState readingState, Long userId) {
|
||||
try {
|
||||
Long bookId = Long.parseLong(readingState.getEntitlementId());
|
||||
|
||||
|
||||
Optional<BookEntity> bookOpt = bookRepository.findById(bookId);
|
||||
if (bookOpt.isEmpty()) {
|
||||
log.warn("Book not found for entitlement ID: {}", readingState.getEntitlementId());
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
BookEntity book = bookOpt.get();
|
||||
Optional<BookLoreUserEntity> userOpt = userRepository.findById(userId);
|
||||
if (userOpt.isEmpty()) {
|
||||
log.warn("User not found: {}", userId);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
UserBookProgressEntity progress = progressRepository.findByUserIdAndBookId(userId, bookId)
|
||||
.orElseGet(() -> {
|
||||
UserBookProgressEntity newProgress = new UserBookProgressEntity();
|
||||
@@ -145,16 +144,16 @@ public class KoboReadingStateService {
|
||||
newProgress.setBook(book);
|
||||
return newProgress;
|
||||
});
|
||||
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark();
|
||||
if (bookmark != null) {
|
||||
if (bookmark.getProgressPercent() != null) {
|
||||
progress.setKoboProgressPercent(bookmark.getProgressPercent().floatValue());
|
||||
}
|
||||
|
||||
|
||||
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
|
||||
if (location != null) {
|
||||
log.debug("Kobo location data: value={}, type={}, source={} (length={})",
|
||||
log.debug("Kobo location data: value={}, type={}, source={} (length={})",
|
||||
location.getValue(), location.getType(), location.getSource(),
|
||||
location.getSource() != null ? location.getSource().length() : 0);
|
||||
progress.setKoboLocation(location.getValue());
|
||||
@@ -162,24 +161,48 @@ public class KoboReadingStateService {
|
||||
progress.setKoboLocationSource(location.getSource());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Instant now = Instant.now();
|
||||
progress.setKoboProgressReceivedTime(now);
|
||||
progress.setLastReadTime(now);
|
||||
|
||||
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
updateReadStatusFromKoboProgress(progress, now);
|
||||
}
|
||||
|
||||
|
||||
progressRepository.save(progress);
|
||||
|
||||
// Also save to file-level progress table (dual-write)
|
||||
saveToFileProgress(userOpt.get(), book, progress);
|
||||
|
||||
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
|
||||
|
||||
|
||||
// Sync progress to Hardcover asynchronously (if enabled for this user)
|
||||
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Invalid entitlement ID format: {}", readingState.getEntitlementId());
|
||||
}
|
||||
}
|
||||
|
||||
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
|
||||
try {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
UserBookFileProgressEntity fileProgress = fileProgressRepository
|
||||
.findByUserIdAndBookFileId(user.getId(), primaryFile.getId())
|
||||
.orElseGet(UserBookFileProgressEntity::new);
|
||||
|
||||
fileProgress.setUser(user);
|
||||
fileProgress.setBookFile(primaryFile);
|
||||
fileProgress.setLastReadTime(progress.getLastReadTime());
|
||||
|
||||
// For Kobo, we store the progress percent (Kobo doesn't provide position data)
|
||||
fileProgress.setProgressPercent(progress.getKoboProgressPercent());
|
||||
|
||||
fileProgressRepository.save(fileProgress);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
|
||||
if (shouldPreserveCurrentStatus(userProgress, now)) {
|
||||
|
||||
+42
-4
@@ -3,13 +3,11 @@ package com.adityachandel.booklore.service.koreader;
|
||||
import com.adityachandel.booklore.config.security.userdetails.KoreaderUserDetails;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.progress.KoreaderProgress;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.KoreaderUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.KoreaderUserRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookFileProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.hardcover.HardcoverSyncService;
|
||||
@@ -31,6 +29,7 @@ import java.util.Map;
|
||||
public class KoreaderService {
|
||||
|
||||
private final UserBookProgressRepository progressRepository;
|
||||
private final UserBookFileProgressRepository fileProgressRepository;
|
||||
private final BookRepository bookRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final KoreaderUserRepository koreaderUserRepository;
|
||||
@@ -79,12 +78,51 @@ public class KoreaderService {
|
||||
|
||||
progressRepository.save(userProgress);
|
||||
|
||||
// Also save to file-level progress table (dual-write)
|
||||
saveToFileProgress(user, book, userProgress);
|
||||
|
||||
log.info("saveProgress: saved progress='{}' percentage={} for userId={} bookHash={}", koProgress.getProgress(), koProgress.getPercentage(), authDetails.getBookLoreUserId(), bookHash);
|
||||
|
||||
Float progressPercent = normalizeProgressPercent(koProgress.getPercentage());
|
||||
hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId());
|
||||
}
|
||||
|
||||
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
|
||||
try {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
UserBookFileProgressEntity fileProgress = fileProgressRepository
|
||||
.findByUserIdAndBookFileId(user.getId(), primaryFile.getId())
|
||||
.orElseGet(UserBookFileProgressEntity::new);
|
||||
|
||||
fileProgress.setUser(user);
|
||||
fileProgress.setBookFile(primaryFile);
|
||||
fileProgress.setLastReadTime(progress.getLastReadTime());
|
||||
|
||||
// Map progress based on book type
|
||||
switch (primaryFile.getBookType()) {
|
||||
case EPUB, FB2, MOBI, AZW3 -> {
|
||||
fileProgress.setPositionData(progress.getEpubProgress());
|
||||
fileProgress.setPositionHref(progress.getEpubProgressHref());
|
||||
fileProgress.setProgressPercent(progress.getEpubProgressPercent());
|
||||
}
|
||||
case PDF -> {
|
||||
fileProgress.setPositionData(progress.getPdfProgress() != null ?
|
||||
String.valueOf(progress.getPdfProgress()) : null);
|
||||
fileProgress.setProgressPercent(progress.getPdfProgressPercent());
|
||||
}
|
||||
case CBX -> {
|
||||
fileProgress.setPositionData(progress.getCbxProgress() != null ?
|
||||
String.valueOf(progress.getCbxProgress()) : null);
|
||||
fileProgress.setProgressPercent(progress.getCbxProgressPercent());
|
||||
}
|
||||
}
|
||||
|
||||
fileProgressRepository.save(fileProgress);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress, boolean syncWithBookloreReader, BookEntity book) {
|
||||
userProgress.setKoreaderProgress(koProgress.getProgress());
|
||||
userProgress.setKoreaderProgressPercent(koProgress.getPercentage());
|
||||
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryOrganizationMode;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.util.BookFileGroupingUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Unified service for grouping book files.
|
||||
* Handles both initial scan (grouping new files) and rescan (matching to existing books).
|
||||
* Organization mode determines the grouping strategy.
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class BookGroupingService {
|
||||
|
||||
private static final double FILELESS_MATCH_THRESHOLD = 0.85;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
/**
|
||||
* Result of grouping operation for rescan.
|
||||
* Contains files to attach to existing books and files that need new book entities.
|
||||
*/
|
||||
public record GroupingResult(
|
||||
Map<BookEntity, List<LibraryFile>> filesToAttach,
|
||||
Map<String, List<LibraryFile>> newBookGroups
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Groups new files for initial library scan.
|
||||
* Returns groups of files that should become a single book entity.
|
||||
*
|
||||
* @param newFiles files to group
|
||||
* @param libraryEntity the library being processed
|
||||
* @return map of group key to list of files in that group
|
||||
*/
|
||||
public Map<String, List<LibraryFile>> groupForInitialScan(List<LibraryFile> newFiles, LibraryEntity libraryEntity) {
|
||||
LibraryOrganizationMode mode = getOrganizationMode(libraryEntity);
|
||||
|
||||
return switch (mode) {
|
||||
case BOOK_PER_FOLDER -> groupByFolder(newFiles);
|
||||
case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(newFiles);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups new files for rescan, considering existing books.
|
||||
* Returns files to attach to existing books and new groups to create.
|
||||
*
|
||||
* @param newFiles files to process
|
||||
* @param libraryEntity the library being processed
|
||||
* @return grouping result with attach map and new groups
|
||||
*/
|
||||
public GroupingResult groupForRescan(List<LibraryFile> newFiles, LibraryEntity libraryEntity) {
|
||||
LibraryOrganizationMode mode = getOrganizationMode(libraryEntity);
|
||||
|
||||
Map<BookEntity, List<LibraryFile>> filesToAttach = new LinkedHashMap<>();
|
||||
List<LibraryFile> unmatched = new ArrayList<>();
|
||||
|
||||
for (LibraryFile file : newFiles) {
|
||||
BookEntity match = findMatchingBook(file, mode);
|
||||
if (match != null) {
|
||||
filesToAttach.computeIfAbsent(match, k -> new ArrayList<>()).add(file);
|
||||
} else {
|
||||
unmatched.add(file);
|
||||
}
|
||||
}
|
||||
|
||||
// Group unmatched files into new book groups
|
||||
Map<String, List<LibraryFile>> newBookGroups;
|
||||
if (unmatched.isEmpty()) {
|
||||
newBookGroups = Collections.emptyMap();
|
||||
} else {
|
||||
newBookGroups = switch (mode) {
|
||||
case BOOK_PER_FOLDER -> groupByFolder(unmatched);
|
||||
case AUTO_DETECT -> BookFileGroupingUtils.groupByBaseName(unmatched);
|
||||
};
|
||||
}
|
||||
|
||||
return new GroupingResult(filesToAttach, newBookGroups);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple folder-based grouping: all files in the same folder become one book.
|
||||
*/
|
||||
private Map<String, List<LibraryFile>> groupByFolder(List<LibraryFile> files) {
|
||||
Map<String, List<LibraryFile>> result = new LinkedHashMap<>();
|
||||
|
||||
for (LibraryFile file : files) {
|
||||
String folderKey = file.getLibraryPathEntity().getId() + ":" +
|
||||
(file.getFileSubPath() == null ? "" : file.getFileSubPath());
|
||||
result.computeIfAbsent(folderKey, k -> new ArrayList<>()).add(file);
|
||||
}
|
||||
|
||||
log.debug("BOOK_PER_FOLDER grouping: {} files into {} groups", files.size(), result.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds an existing book that matches the given file.
|
||||
* Strategy depends on organization mode.
|
||||
*/
|
||||
private BookEntity findMatchingBook(LibraryFile file, LibraryOrganizationMode mode) {
|
||||
// First check for fileless books by metadata matching
|
||||
BookEntity filelessMatch = findMatchingFilelessBook(file, file.getLibraryEntity());
|
||||
if (filelessMatch != null) {
|
||||
return filelessMatch;
|
||||
}
|
||||
|
||||
String fileSubPath = file.getFileSubPath();
|
||||
|
||||
// Root-level files: don't auto-attach
|
||||
if (fileSubPath == null || fileSubPath.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Long libraryPathId = file.getLibraryPathEntity().getId();
|
||||
List<BookEntity> booksInDirectory = bookRepository.findAllByLibraryPathIdAndFileSubPath(libraryPathId, fileSubPath);
|
||||
|
||||
// Filter to non-deleted books only
|
||||
List<BookEntity> activeBooksInDirectory = booksInDirectory.stream()
|
||||
.filter(book -> book.getDeleted() == null || !book.getDeleted())
|
||||
.toList();
|
||||
|
||||
if (activeBooksInDirectory.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return switch (mode) {
|
||||
case BOOK_PER_FOLDER -> findMatchBookPerFolder(file, activeBooksInDirectory);
|
||||
case AUTO_DETECT -> findMatchAutoDetect(file, activeBooksInDirectory);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a fileless book that matches the given file by metadata title.
|
||||
* Only matches books that either have no libraryPath or have the same libraryPath as the file.
|
||||
*/
|
||||
private BookEntity findMatchingFilelessBook(LibraryFile file, LibraryEntity library) {
|
||||
List<BookEntity> filelessBooks = bookRepository.findFilelessBooksByLibraryId(library.getId());
|
||||
if (filelessBooks.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fileBaseName = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
|
||||
Long fileLibraryPathId = file.getLibraryPathEntity().getId();
|
||||
|
||||
for (BookEntity book : filelessBooks) {
|
||||
// Skip books that already have a different libraryPath
|
||||
if (book.getLibraryPath() != null && !book.getLibraryPath().getId().equals(fileLibraryPathId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (book.getMetadata() != null && book.getMetadata().getTitle() != null) {
|
||||
String bookTitle = BookFileGroupingUtils.extractGroupingKey(book.getMetadata().getTitle());
|
||||
double similarity = BookFileGroupingUtils.calculateSimilarity(fileBaseName, bookTitle);
|
||||
if (similarity >= FILELESS_MATCH_THRESHOLD) {
|
||||
log.debug("Matched file '{}' to fileless book '{}' (title: {})",
|
||||
file.getFileName(), book.getId(), book.getMetadata().getTitle());
|
||||
return book;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* BOOK_PER_FOLDER: If exactly one book in folder, attach to it.
|
||||
* If multiple books exist (edge case), use filename matching.
|
||||
*/
|
||||
private BookEntity findMatchBookPerFolder(LibraryFile file, List<BookEntity> booksInDirectory) {
|
||||
// Filter to books with files for filename-based matching
|
||||
List<BookEntity> booksWithFiles = booksInDirectory.stream()
|
||||
.filter(BookEntity::hasFiles)
|
||||
.toList();
|
||||
|
||||
if (booksWithFiles.size() == 1) {
|
||||
BookEntity book = booksWithFiles.get(0);
|
||||
log.debug("BOOK_PER_FOLDER: Attaching '{}' to single book in folder: '{}'",
|
||||
file.getFileName(), book.getPrimaryBookFile().getFileName());
|
||||
return book;
|
||||
}
|
||||
|
||||
if (booksWithFiles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Multiple books in folder - shouldn't happen with BOOK_PER_FOLDER mode
|
||||
// Fall back to exact filename matching
|
||||
log.warn("BOOK_PER_FOLDER: Multiple books ({}) in folder '{}', using filename match",
|
||||
booksWithFiles.size(), file.getFileSubPath());
|
||||
return findExactMatch(file, booksWithFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* AUTO_DETECT: Use fuzzy matching to find best match.
|
||||
*/
|
||||
private BookEntity findMatchAutoDetect(LibraryFile file, List<BookEntity> booksInDirectory) {
|
||||
// Filter to books with files for filename-based matching
|
||||
List<BookEntity> booksWithFiles = booksInDirectory.stream()
|
||||
.filter(BookEntity::hasFiles)
|
||||
.toList();
|
||||
|
||||
if (booksWithFiles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If exactly one book with files in folder, attach to it
|
||||
if (booksWithFiles.size() == 1) {
|
||||
BookEntity book = booksWithFiles.get(0);
|
||||
log.debug("AUTO_DETECT: Single book in folder '{}', attaching '{}' to '{}'",
|
||||
file.getFileSubPath(), file.getFileName(), book.getPrimaryBookFile().getFileName());
|
||||
return book;
|
||||
}
|
||||
|
||||
// Multiple books: use fuzzy matching
|
||||
String fileGroupingKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
|
||||
BookEntity bestMatch = null;
|
||||
double bestSimilarity = 0;
|
||||
|
||||
for (BookEntity book : booksWithFiles) {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
String existingGroupingKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName());
|
||||
|
||||
// Exact match
|
||||
if (fileGroupingKey.equals(existingGroupingKey)) {
|
||||
return book;
|
||||
}
|
||||
|
||||
// Track best fuzzy match
|
||||
double similarity = BookFileGroupingUtils.calculateSimilarity(fileGroupingKey, existingGroupingKey);
|
||||
if (similarity >= 0.85 && similarity > bestSimilarity) {
|
||||
bestSimilarity = similarity;
|
||||
bestMatch = book;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestMatch != null) {
|
||||
log.debug("AUTO_DETECT: Fuzzy matched '{}' to '{}' (similarity: {})",
|
||||
file.getFileName(), bestMatch.getPrimaryBookFile().getFileName(), bestSimilarity);
|
||||
}
|
||||
return bestMatch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a book with exact filename match.
|
||||
* Assumes books list contains only books with files.
|
||||
*/
|
||||
private BookEntity findExactMatch(LibraryFile file, List<BookEntity> books) {
|
||||
String fileKey = BookFileGroupingUtils.extractGroupingKey(file.getFileName());
|
||||
|
||||
for (BookEntity book : books) {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
continue;
|
||||
}
|
||||
String bookKey = BookFileGroupingUtils.extractGroupingKey(primaryFile.getFileName());
|
||||
if (fileKey.equals(bookKey)) {
|
||||
return book;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private LibraryOrganizationMode getOrganizationMode(LibraryEntity library) {
|
||||
LibraryOrganizationMode mode = library.getOrganizationMode();
|
||||
return mode != null ? mode : LibraryOrganizationMode.AUTO_DETECT;
|
||||
}
|
||||
}
|
||||
+1
@@ -39,6 +39,7 @@ public class BookRestorationService {
|
||||
|
||||
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
|
||||
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
|
||||
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
|
||||
+119
-25
@@ -2,66 +2,160 @@ package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.service.kobo.KoboAutoShelfService;
|
||||
import com.adityachandel.booklore.util.BookFileGroupingUtils;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class FileAsBookProcessor implements LibraryFileProcessor {
|
||||
public class FileAsBookProcessor {
|
||||
|
||||
private final BookEventBroadcaster bookEventBroadcaster;
|
||||
private final BookFileProcessorRegistry processorRegistry;
|
||||
private final KoboAutoShelfService koboAutoShelfService;
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
return LibraryScanMode.FILE_AS_BOOK;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
for (LibraryFile libraryFile : libraryFiles) {
|
||||
processFileWithErrorHandling(libraryFile);
|
||||
Map<String, List<LibraryFile>> groups = BookFileGroupingUtils.groupByBaseName(libraryFiles);
|
||||
processLibraryFilesGrouped(groups, libraryEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process pre-grouped library files. Use this when grouping has already been done
|
||||
* (e.g., by BookGroupingService during rescan).
|
||||
*/
|
||||
@Transactional
|
||||
public void processLibraryFilesGrouped(Map<String, List<LibraryFile>> groups, LibraryEntity libraryEntity) {
|
||||
for (Map.Entry<String, List<LibraryFile>> entry : groups.entrySet()) {
|
||||
processGroupWithErrorHandling(entry.getValue(), libraryEntity);
|
||||
}
|
||||
log.info("Finished processing library '{}'", libraryEntity.getName());
|
||||
}
|
||||
|
||||
private void processFileWithErrorHandling(LibraryFile libraryFile) {
|
||||
log.info("Processing file: {}", libraryFile.getFileName());
|
||||
private void processGroupWithErrorHandling(List<LibraryFile> group, LibraryEntity libraryEntity) {
|
||||
try {
|
||||
FileProcessResult result = processLibraryFile(libraryFile);
|
||||
if (result != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId());
|
||||
}
|
||||
processGroup(group, libraryEntity);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to process file '{}': {}", libraryFile.getFileName(), e.getMessage());
|
||||
String fileNames = group.stream().map(LibraryFile::getFileName).toList().toString();
|
||||
log.error("Failed to process file group {}: {}", fileNames, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected FileProcessResult processLibraryFile(LibraryFile libraryFile) {
|
||||
BookFileType type = libraryFile.getBookFileType();
|
||||
private void processGroup(List<LibraryFile> group, LibraryEntity libraryEntity) {
|
||||
Optional<LibraryFile> primaryFile = findBestPrimaryFile(group, libraryEntity);
|
||||
if (primaryFile.isEmpty()) {
|
||||
log.warn("No suitable book file found in group");
|
||||
return;
|
||||
}
|
||||
|
||||
LibraryFile primary = primaryFile.get();
|
||||
log.info("Processing file: {}", primary.getFileName());
|
||||
|
||||
BookFileType type = primary.getBookFileType();
|
||||
if (type == null) {
|
||||
log.warn("Unsupported file type for file: {}", libraryFile.getFileName());
|
||||
return null;
|
||||
log.warn("Unsupported file type for file: {}", primary.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
|
||||
return processor.processFile(libraryFile);
|
||||
FileProcessResult result = processor.processFile(primary);
|
||||
|
||||
if (result == null || result.getBook() == null) {
|
||||
log.warn("Failed to process primary file: {}", primary.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
koboAutoShelfService.autoAddBookToKoboShelves(result.getBook().getId());
|
||||
|
||||
List<LibraryFile> additionalFiles = group.stream()
|
||||
.filter(f -> !f.equals(primary))
|
||||
.toList();
|
||||
|
||||
if (!additionalFiles.isEmpty()) {
|
||||
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId());
|
||||
for (LibraryFile additionalFile : additionalFiles) {
|
||||
createAdditionalBookFile(bookEntity, additionalFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
private Optional<LibraryFile> findBestPrimaryFile(List<LibraryFile> group, LibraryEntity libraryEntity) {
|
||||
List<BookFileType> formatPriority = libraryEntity.getFormatPriority();
|
||||
return group.stream()
|
||||
.filter(f -> f.getBookFileType() != null)
|
||||
.min(Comparator.comparingInt(f -> {
|
||||
BookFileType bookFileType = f.getBookFileType();
|
||||
if (formatPriority != null && !formatPriority.isEmpty()) {
|
||||
int index = formatPriority.indexOf(bookFileType);
|
||||
return index >= 0 ? index : Integer.MAX_VALUE;
|
||||
}
|
||||
return bookFileType.ordinal();
|
||||
}));
|
||||
}
|
||||
|
||||
private void createAdditionalBookFile(BookEntity bookEntity, LibraryFile file) {
|
||||
Optional<BookFileEntity> existing = bookAdditionalFileRepository
|
||||
.findByLibraryPath_IdAndFileSubPathAndFileName(
|
||||
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
|
||||
|
||||
if (existing.isPresent()) {
|
||||
log.debug("Additional file already exists: {}", file.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle folder-based audiobooks vs regular files
|
||||
String hash;
|
||||
Long fileSizeKb;
|
||||
if (file.isFolderBased()) {
|
||||
hash = FileFingerprint.generateFolderHash(file.getFullPath());
|
||||
fileSizeKb = FileUtils.getFolderSizeInKb(file.getFullPath());
|
||||
} else {
|
||||
hash = FileFingerprint.generateHash(file.getFullPath());
|
||||
fileSizeKb = FileUtils.getFileSizeInKb(file.getFullPath());
|
||||
}
|
||||
|
||||
BookFileEntity additionalFile = BookFileEntity.builder()
|
||||
.book(bookEntity)
|
||||
.fileName(file.getFileName())
|
||||
.fileSubPath(file.getFileSubPath())
|
||||
.isBookFormat(true)
|
||||
.folderBased(file.isFolderBased())
|
||||
.bookType(file.getBookFileType())
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.initialHash(hash)
|
||||
.currentHash(hash)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
|
||||
try {
|
||||
bookAdditionalFileRepository.save(additionalFile);
|
||||
log.info("Attached additional format {} to book: {}", file.getFileName(), bookEntity.getPrimaryBookFile().getFileName());
|
||||
} catch (Exception e) {
|
||||
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-255
@@ -1,255 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.FileProcessResult;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.service.event.AdminEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.event.BookEventBroadcaster;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
@Slf4j
|
||||
public class FolderAsBookFileProcessor implements LibraryFileProcessor {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final BookEventBroadcaster bookEventBroadcaster;
|
||||
private final AdminEventBroadcaster adminEventBroadcaster;
|
||||
private final BookFileProcessorRegistry bookFileProcessorRegistry;
|
||||
|
||||
@Override
|
||||
public LibraryScanMode getScanMode() {
|
||||
return LibraryScanMode.FOLDER_AS_BOOK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsSupplementaryFiles() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
Map<Path, List<LibraryFile>> filesByDirectory = libraryFiles.stream()
|
||||
.collect(Collectors.groupingBy(libraryFile -> libraryFile.getFullPath().getParent()));
|
||||
|
||||
log.info("Processing {} directories with {} total files for library: {}",
|
||||
filesByDirectory.size(), libraryFiles.size(), libraryEntity.getName());
|
||||
|
||||
var sortedDirectories = filesByDirectory.entrySet()
|
||||
.stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.toList();
|
||||
for (Map.Entry<Path, List<LibraryFile>> entry : sortedDirectories) {
|
||||
Path directoryPath = entry.getKey();
|
||||
List<LibraryFile> filesInDirectory = entry.getValue();
|
||||
|
||||
log.debug("Processing directory: {} with {} files", directoryPath, filesInDirectory.size());
|
||||
processDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private void processDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var bookCreationResult = getOrCreateBookInDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
if (bookCreationResult.bookEntity.isEmpty()) {
|
||||
log.warn("No book created for directory: {}", directoryPath);
|
||||
return;
|
||||
}
|
||||
|
||||
processAdditionalFiles(bookCreationResult.bookEntity.get(), bookCreationResult.remainingFiles);
|
||||
}
|
||||
|
||||
private GetOrCreateBookResult getOrCreateBookInDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var existingBook = findExistingBookInDirectory(directoryPath, libraryEntity);
|
||||
if (existingBook.isPresent()) {
|
||||
log.debug("Found existing book in directory {}: {}", directoryPath, existingBook.get().getPrimaryBookFile().getFileName());
|
||||
return new GetOrCreateBookResult(existingBook, filesInDirectory);
|
||||
}
|
||||
|
||||
Optional<BookEntity> parentBook = findBookInParentDirectories(directoryPath, libraryEntity);
|
||||
if (parentBook.isPresent()) {
|
||||
log.debug("Found parent book for directory {}: {}", directoryPath, parentBook.get().getPrimaryBookFile().getFileName());
|
||||
return new GetOrCreateBookResult(parentBook, filesInDirectory);
|
||||
}
|
||||
|
||||
log.debug("No existing book found, creating new book from directory: {}", directoryPath);
|
||||
Optional<CreateBookResult> newBook = createNewBookFromDirectory(directoryPath, filesInDirectory, libraryEntity);
|
||||
if (newBook.isPresent()) {
|
||||
log.info("Created new book: {}", newBook.get().bookEntity.getPrimaryBookFile().getFileName());
|
||||
var remainingFiles = filesInDirectory.stream()
|
||||
.filter(file -> !file.equals(newBook.get().libraryFile))
|
||||
.toList();
|
||||
return new GetOrCreateBookResult(Optional.of(newBook.get().bookEntity), remainingFiles);
|
||||
} else {
|
||||
log.warn("Failed to create book from directory: {}", directoryPath);
|
||||
return new GetOrCreateBookResult(Optional.empty(), filesInDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<BookEntity> findExistingBookInDirectory(Path directoryPath, LibraryEntity libraryEntity) {
|
||||
return libraryEntity.getLibraryPaths().stream()
|
||||
.flatMap(libPath -> {
|
||||
String filesSearchPath = Path.of(libPath.getPath())
|
||||
.relativize(directoryPath)
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
return bookRepository
|
||||
.findAllByLibraryPathIdAndFileSubPathStartingWith(libPath.getId(), filesSearchPath)
|
||||
.stream();
|
||||
})
|
||||
.filter(book -> book.getFullFilePath().getParent().equals(directoryPath))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private Optional<BookEntity> findBookInParentDirectories(Path directoryPath, LibraryEntity libraryEntity) {
|
||||
Path parent = directoryPath.getParent();
|
||||
LibraryPathEntity directoryLibraryPathEntity = libraryEntity.getLibraryPaths().stream()
|
||||
.filter(libPath -> directoryPath.startsWith(libPath.getPath()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("No library path found for directory: " + directoryPath));
|
||||
Path directoryLibraryPath = Path.of(directoryLibraryPathEntity.getPath());
|
||||
|
||||
while (parent != null) {
|
||||
final String parentPath = directoryLibraryPath
|
||||
.relativize(parent)
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
|
||||
Optional<BookEntity> parentBook =
|
||||
bookRepository.findAllByLibraryPathIdAndFileSubPathStartingWith(
|
||||
directoryLibraryPathEntity.getId(), parentPath).stream()
|
||||
.filter(book -> book.getPrimaryBookFile().getFileSubPath().equals(parentPath))
|
||||
.findFirst();
|
||||
if (parentBook.isPresent()) {
|
||||
return parentBook;
|
||||
}
|
||||
parent = parent.getParent();
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<CreateBookResult> createNewBookFromDirectory(Path directoryPath, List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
Optional<LibraryFile> mainBookFile = findBestMainBookFile(filesInDirectory, libraryEntity);
|
||||
|
||||
if (mainBookFile.isEmpty()) {
|
||||
log.debug("No suitable book file found in directory: {}", directoryPath);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
LibraryFile bookFile = mainBookFile.get();
|
||||
|
||||
try {
|
||||
log.info("Creating new book from file: {}", bookFile.getFileName());
|
||||
|
||||
BookFileProcessor processor = bookFileProcessorRegistry.getProcessorOrThrow(bookFile.getBookFileType());
|
||||
FileProcessResult result = processor.processFile(bookFile);
|
||||
|
||||
if (result.getBook() != null) {
|
||||
bookEventBroadcaster.broadcastBookAddEvent(result.getBook());
|
||||
|
||||
BookEntity bookEntity = bookRepository.getReferenceById(result.getBook().getId());
|
||||
if (bookEntity.getFullFilePath().equals(bookFile.getFullPath())) {
|
||||
log.info("Successfully created new book: {}", bookEntity.getPrimaryBookFile().getFileName());
|
||||
} else {
|
||||
log.warn("Found duplicate book with different path: {} vs {}", bookEntity.getFullFilePath(), bookFile.getFullPath());
|
||||
}
|
||||
|
||||
return Optional.of(new CreateBookResult(bookEntity, bookFile));
|
||||
} else {
|
||||
log.warn("Book processor returned null for file: {}", bookFile.getFileName());
|
||||
adminEventBroadcaster.broadcastAdminEvent("Failed to create book from file: " + bookFile.getFileName());
|
||||
return Optional.empty();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error processing book file {}: {}", bookFile.getFileName(), e.getMessage(), e);
|
||||
adminEventBroadcaster.broadcastAdminEvent("Error processing book file: " + bookFile.getFileName() + " - " + e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<LibraryFile> findBestMainBookFile(List<LibraryFile> filesInDirectory, LibraryEntity libraryEntity) {
|
||||
var defaultBookFormat = libraryEntity.getDefaultBookFormat();
|
||||
return filesInDirectory.stream()
|
||||
.filter(f -> f.getBookFileType() != null)
|
||||
.min(Comparator.comparingInt(f -> {
|
||||
BookFileType bookFileType = f.getBookFileType();
|
||||
return bookFileType == defaultBookFormat
|
||||
? -1
|
||||
: bookFileType.ordinal();
|
||||
}));
|
||||
}
|
||||
|
||||
private void processAdditionalFiles(BookEntity existingBook, List<LibraryFile> filesInDirectory) {
|
||||
for (LibraryFile file : filesInDirectory) {
|
||||
Optional<BookFileExtension> extension = BookFileExtension.fromFileName(file.getFileName());
|
||||
boolean isBook = extension.isPresent();
|
||||
BookFileType bookType = extension.map(BookFileExtension::getType).orElse(null);
|
||||
|
||||
createAdditionalFileIfNotExists(existingBook, file, isBook, bookType);
|
||||
}
|
||||
}
|
||||
|
||||
private void createAdditionalFileIfNotExists(BookEntity bookEntity, LibraryFile file, boolean isBook, BookFileType bookType) {
|
||||
Optional<BookFileEntity> existingFile = bookAdditionalFileRepository
|
||||
.findByLibraryPath_IdAndFileSubPathAndFileName(
|
||||
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
|
||||
|
||||
if (existingFile.isPresent()) {
|
||||
log.debug("Additional file already exists: {}", file.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
String hash = FileFingerprint.generateHash(file.getFullPath());
|
||||
BookFileEntity additionalFile = BookFileEntity.builder()
|
||||
.book(bookEntity)
|
||||
.fileName(file.getFileName())
|
||||
.fileSubPath(file.getFileSubPath())
|
||||
.isBookFormat(isBook)
|
||||
.bookType(bookType)
|
||||
.fileSizeKb(FileUtils.getFileSizeInKb(file.getFullPath()))
|
||||
.initialHash(hash)
|
||||
.currentHash(hash)
|
||||
.addedOn(java.time.Instant.now())
|
||||
.build();
|
||||
|
||||
try {
|
||||
log.debug("Creating additional file: {} (isBook: {}, type: {})", file.getFileName(), isBook, bookType);
|
||||
bookAdditionalFileRepository.save(additionalFile);
|
||||
|
||||
log.debug("Successfully created additional file: {}", file.getFileName());
|
||||
} catch (Exception e) {
|
||||
bookEntity.getBookFiles().removeIf(a -> a.equals(additionalFile));
|
||||
|
||||
log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public record GetOrCreateBookResult(Optional<BookEntity> bookEntity, List<LibraryFile> remainingFiles) {
|
||||
}
|
||||
|
||||
public record CreateBookResult(BookEntity bookEntity, LibraryFile libraryFile) {
|
||||
}
|
||||
|
||||
}
|
||||
+101
-12
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
@@ -18,26 +19,36 @@ import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class LibraryFileHelper {
|
||||
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
private static final int MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK = 2;
|
||||
|
||||
public List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> allFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) {
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity, processor));
|
||||
allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity));
|
||||
}
|
||||
return allFiles;
|
||||
}
|
||||
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity, LibraryFileProcessor processor) throws IOException {
|
||||
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
|
||||
Path libraryPath = Path.of(pathEntity.getPath());
|
||||
boolean supportsSupplementaryFiles = processor.supportsSupplementaryFiles();
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
|
||||
// Track directories that contain audio files for folder-based audiobook detection
|
||||
Map<Path, List<Path>> dirAudioFiles = new HashMap<>();
|
||||
Map<Path, Boolean> dirHasNonAudioBooks = new HashMap<>();
|
||||
Set<Path> processedAsFolderAudiobook = new HashSet<>();
|
||||
|
||||
Files.walkFileTree(libraryPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
@NonNull
|
||||
@@ -49,20 +60,98 @@ public class LibraryFileHelper {
|
||||
String fileName = file.getFileName().toString();
|
||||
Optional<BookFileExtension> bookExtension = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
if (bookExtension.isEmpty() && !supportsSupplementaryFiles) {
|
||||
if (bookExtension.isEmpty()) {
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file))
|
||||
.fileName(fileName)
|
||||
.bookFileType(bookExtension.map(BookFileExtension::getType).orElse(null))
|
||||
.build());
|
||||
Path parentDir = file.getParent();
|
||||
BookFileType fileType = bookExtension.get().getType();
|
||||
|
||||
if (fileType == BookFileType.AUDIOBOOK) {
|
||||
// Track audio files per directory for folder-based detection
|
||||
dirAudioFiles.computeIfAbsent(parentDir, k -> new ArrayList<>()).add(file);
|
||||
} else {
|
||||
// Track that this directory has non-audio book files
|
||||
dirHasNonAudioBooks.put(parentDir, true);
|
||||
|
||||
// Add non-audio files immediately
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), file))
|
||||
.fileName(fileName)
|
||||
.bookFileType(fileType)
|
||||
.build());
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public FileVisitResult postVisitDirectory(@NonNull Path dir, IOException exc) throws IOException {
|
||||
// Check if this directory should be treated as a folder-based audiobook
|
||||
List<Path> audioFiles = dirAudioFiles.get(dir);
|
||||
boolean hasNonAudioBooks = dirHasNonAudioBooks.getOrDefault(dir, false);
|
||||
|
||||
if (audioFiles != null && audioFiles.size() >= MIN_AUDIO_FILES_FOR_FOLDER_AUDIOBOOK && !hasNonAudioBooks) {
|
||||
// This is a folder-based audiobook: contains 2+ audio files and no ebook files
|
||||
// Don't treat library root as audiobook folder
|
||||
if (!dir.equals(libraryPath)) {
|
||||
log.info("Detected folder-based audiobook: {} ({} audio files)", dir.getFileName(), audioFiles.size());
|
||||
|
||||
processedAsFolderAudiobook.add(dir);
|
||||
|
||||
// Add a single LibraryFile representing the folder
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), dir))
|
||||
.fileName(dir.getFileName().toString())
|
||||
.bookFileType(BookFileType.AUDIOBOOK)
|
||||
.folderBased(true)
|
||||
.build());
|
||||
} else {
|
||||
// Library root - add individual audio files
|
||||
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
|
||||
}
|
||||
} else if (audioFiles != null) {
|
||||
// Not a folder-based audiobook - add individual audio files
|
||||
// But skip if parent was already processed as folder-based audiobook
|
||||
boolean parentIsAudiobookFolder = false;
|
||||
Path parent = dir.getParent();
|
||||
while (parent != null && parent.startsWith(libraryPath)) {
|
||||
if (processedAsFolderAudiobook.contains(parent)) {
|
||||
parentIsAudiobookFolder = true;
|
||||
break;
|
||||
}
|
||||
parent = parent.getParent();
|
||||
}
|
||||
|
||||
if (!parentIsAudiobookFolder) {
|
||||
addIndividualAudioFiles(audioFiles, libraryEntity, pathEntity, libraryFiles);
|
||||
}
|
||||
}
|
||||
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
private void addIndividualAudioFiles(List<Path> audioFiles, LibraryEntity libraryEntity,
|
||||
LibraryPathEntity pathEntity, List<LibraryFile> libraryFiles) {
|
||||
for (Path audioFile : audioFiles) {
|
||||
String fileName = audioFile.getFileName().toString();
|
||||
Optional<BookFileExtension> ext = BookFileExtension.fromFileName(fileName);
|
||||
|
||||
libraryFiles.add(LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(pathEntity)
|
||||
.fileSubPath(FileUtils.getRelativeSubPath(pathEntity.getPath(), audioFile))
|
||||
.fileName(fileName)
|
||||
.bookFileType(ext.map(BookFileExtension::getType).orElse(BookFileType.AUDIOBOOK))
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public FileVisitResult visitFileFailed(@NonNull Path file, IOException e) {
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
|
||||
public interface LibraryFileProcessor {
|
||||
LibraryScanMode getScanMode();
|
||||
void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity);
|
||||
|
||||
/**
|
||||
* Indicates whether this processor supports supplementary files (any file type)
|
||||
* in addition to book files.
|
||||
* @return true if supplementary files are supported, false otherwise
|
||||
*/
|
||||
default boolean supportsSupplementaryFiles() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class LibraryFileProcessorRegistry {
|
||||
|
||||
private final Map<LibraryScanMode, LibraryFileProcessor> processorMap;
|
||||
|
||||
public LibraryFileProcessorRegistry(List<LibraryFileProcessor> processors) {
|
||||
this.processorMap = processors.stream()
|
||||
.collect(Collectors.toMap(LibraryFileProcessor::getScanMode, Function.identity()));
|
||||
}
|
||||
|
||||
public LibraryFileProcessor getProcessor(LibraryEntity libraryEntity) {
|
||||
return processorMap.get(libraryEntity.getScanMode());
|
||||
}
|
||||
}
|
||||
+96
-23
@@ -5,12 +5,15 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.websocket.LogNotification;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.file.FileFingerprint;
|
||||
import com.adityachandel.booklore.task.options.RescanLibraryContext;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.PersistenceContext;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -22,7 +25,9 @@ import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -34,10 +39,11 @@ public class LibraryProcessingService {
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final NotificationService notificationService;
|
||||
private final BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
private final LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
private final FileAsBookProcessor fileAsBookProcessor;
|
||||
private final BookRestorationService bookRestorationService;
|
||||
private final BookDeletionService bookDeletionService;
|
||||
private final LibraryFileHelper libraryFileHelper;
|
||||
private final BookGroupingService bookGroupingService;
|
||||
@PersistenceContext
|
||||
private final EntityManager entityManager;
|
||||
|
||||
@@ -45,10 +51,14 @@ public class LibraryProcessingService {
|
||||
public void processLibrary(long libraryId) {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started processing library: " + libraryEntity.getName()));
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
try {
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
||||
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, libraryEntity);
|
||||
|
||||
// Use BookGroupingService for consistent grouping based on organization mode
|
||||
Map<String, List<LibraryFile>> groups = bookGroupingService.groupForInitialScan(newFiles, libraryEntity);
|
||||
fileAsBookProcessor.processLibraryFilesGrouped(groups, libraryEntity);
|
||||
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished processing library: " + libraryEntity.getName()));
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to process library {}: {}", libraryEntity.getName(), e.getMessage(), e);
|
||||
@@ -61,23 +71,22 @@ public class LibraryProcessingService {
|
||||
public void rescanLibrary(RescanLibraryContext context) throws IOException {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(context.getLibraryId()).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(context.getLibraryId()));
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started refreshing library: " + libraryEntity.getName()));
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
|
||||
|
||||
validateLibraryPathsAccessible(libraryEntity);
|
||||
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity, processor);
|
||||
|
||||
|
||||
List<LibraryFile> libraryFiles = libraryFileHelper.getLibraryFiles(libraryEntity);
|
||||
|
||||
int existingBookCount = libraryEntity.getBookEntities().size();
|
||||
if (existingBookCount > 0 && libraryFiles.isEmpty()) {
|
||||
String paths = libraryEntity.getLibraryPaths().stream()
|
||||
.map(p -> p.getPath())
|
||||
.map(LibraryPathEntity::getPath)
|
||||
.collect(Collectors.joining(", "));
|
||||
log.error("Library '{}' has {} existing books but scan found 0 files. Paths may be offline: {}",
|
||||
log.error("Library '{}' has {} existing books but scan found 0 files. Paths may be offline: {}",
|
||||
libraryEntity.getName(), existingBookCount, paths);
|
||||
throw ApiError.LIBRARY_PATH_NOT_ACCESSIBLE.createException(paths);
|
||||
}
|
||||
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity, processor);
|
||||
|
||||
List<Long> additionalFileIds = detectDeletedAdditionalFiles(libraryFiles, libraryEntity);
|
||||
if (!additionalFileIds.isEmpty()) {
|
||||
log.info("Detected {} removed additional files in library: {}", additionalFileIds.size(), libraryEntity.getName());
|
||||
bookDeletionService.deleteRemovedAdditionalFiles(additionalFileIds);
|
||||
@@ -89,14 +98,27 @@ public class LibraryProcessingService {
|
||||
}
|
||||
bookRestorationService.restoreDeletedBooks(libraryFiles);
|
||||
entityManager.clear();
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
|
||||
List<LibraryFile> newFiles = detectNewBookPaths(libraryFiles, libraryEntity);
|
||||
|
||||
// Use BookGroupingService to determine what to attach vs create new
|
||||
BookGroupingService.GroupingResult groupingResult = bookGroupingService.groupForRescan(newFiles, libraryEntity);
|
||||
|
||||
// Auto-attach files to existing books
|
||||
for (Map.Entry<BookEntity, List<LibraryFile>> entry : groupingResult.filesToAttach().entrySet()) {
|
||||
for (LibraryFile file : entry.getValue()) {
|
||||
autoAttachFile(entry.getKey(), file);
|
||||
}
|
||||
}
|
||||
|
||||
// Process new book groups
|
||||
fileAsBookProcessor.processLibraryFilesGrouped(groupingResult.newBookGroups(), libraryEntity);
|
||||
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
}
|
||||
|
||||
private void validateLibraryPathsAccessible(LibraryEntity libraryEntity) {
|
||||
@@ -117,8 +139,9 @@ public class LibraryProcessingService {
|
||||
return libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> (book.getDeleted() == null || !book.getDeleted()))
|
||||
.filter(book -> {
|
||||
if (book.getBookFiles() == null || book.getBookFiles().isEmpty()) {
|
||||
return true;
|
||||
// Don't mark fileless books as deleted - they're intentionally without files
|
||||
if (!book.hasFiles()) {
|
||||
return false;
|
||||
}
|
||||
return !currentFullPaths.contains(book.getFullFilePath());
|
||||
})
|
||||
@@ -143,12 +166,63 @@ public class LibraryProcessingService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void autoAttachFile(BookEntity book, LibraryFile file) {
|
||||
// Check if file already exists to prevent duplicates during concurrent rescans
|
||||
var existing = bookAdditionalFileRepository.findByLibraryPath_IdAndFileSubPathAndFileName(
|
||||
file.getLibraryPathEntity().getId(), file.getFileSubPath(), file.getFileName());
|
||||
if (existing.isPresent()) {
|
||||
log.debug("Additional file already exists, skipping: {}", file.getFileName());
|
||||
return;
|
||||
}
|
||||
|
||||
// Set libraryPath if not set (fileless books like physical books don't have one)
|
||||
if (book.getLibraryPath() == null) {
|
||||
book.setLibraryPath(file.getLibraryPathEntity());
|
||||
} else if (!book.getLibraryPath().getId().equals(file.getLibraryPathEntity().getId())) {
|
||||
// Book already has a different libraryPath - cannot attach files from different paths
|
||||
log.warn("Cannot attach file '{}' to book id={}: file is in libraryPath {} but book is in libraryPath {}",
|
||||
file.getFileName(), book.getId(), file.getLibraryPathEntity().getId(), book.getLibraryPath().getId());
|
||||
return;
|
||||
}
|
||||
|
||||
String hash = file.isFolderBased()
|
||||
? FileFingerprint.generateFolderHash(file.getFullPath())
|
||||
: FileFingerprint.generateHash(file.getFullPath());
|
||||
Long fileSizeKb = file.isFolderBased()
|
||||
? FileUtils.getFolderSizeInKb(file.getFullPath())
|
||||
: FileUtils.getFileSizeInKb(file.getFullPath());
|
||||
BookFileEntity additionalFile = BookFileEntity.builder()
|
||||
.book(book)
|
||||
.fileName(file.getFileName())
|
||||
.fileSubPath(file.getFileSubPath())
|
||||
.isBookFormat(true)
|
||||
.bookType(file.getBookFileType())
|
||||
.folderBased(file.isFolderBased())
|
||||
.fileSizeKb(fileSizeKb)
|
||||
.initialHash(hash)
|
||||
.currentHash(hash)
|
||||
.addedOn(Instant.now())
|
||||
.build();
|
||||
|
||||
try {
|
||||
bookAdditionalFileRepository.save(additionalFile);
|
||||
String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId();
|
||||
log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName);
|
||||
} catch (Exception e) {
|
||||
log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String generateUniqueKey(BookEntity book) {
|
||||
return generateKey(book.getLibraryPath().getId(), book.getPrimaryBookFile().getFileSubPath(), book.getPrimaryBookFile().getFileName());
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
// Fileless book - use a unique key that won't match any file
|
||||
return "fileless:" + book.getId();
|
||||
}
|
||||
return generateKey(book.getLibraryPath().getId(), primaryFile.getFileSubPath(), primaryFile.getFileName());
|
||||
}
|
||||
|
||||
private String generateUniqueKey(BookFileEntity file) {
|
||||
// Additional files inherit library path from their parent book
|
||||
return generateKey(file.getBook().getLibraryPath().getId(), file.getFileSubPath(), file.getFileName());
|
||||
}
|
||||
|
||||
@@ -161,7 +235,7 @@ public class LibraryProcessingService {
|
||||
return libraryPathId + ":" + safeSubPath + ":" + fileName;
|
||||
}
|
||||
|
||||
protected List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity, LibraryFileProcessor processor) {
|
||||
protected List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
Set<String> currentFileKeys = libraryFiles.stream()
|
||||
.map(this::generateUniqueKey)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -169,8 +243,7 @@ public class LibraryProcessingService {
|
||||
List<BookFileEntity> allAdditionalFiles = bookAdditionalFileRepository.findByLibraryId(libraryEntity.getId());
|
||||
|
||||
return allAdditionalFiles.stream()
|
||||
// Only check files that would be scanned: book formats always, non-book files only if processor supports them
|
||||
.filter(additionalFile -> additionalFile.isBookFormat() || processor.supportsSupplementaryFiles())
|
||||
.filter(BookFileEntity::isBookFormat)
|
||||
.filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile)))
|
||||
.map(BookFileEntity::getId)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
+6
@@ -63,6 +63,12 @@ public class LibraryRescanHelper {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip fileless books (e.g., physical books) - they have no file to extract metadata from
|
||||
if (!bookEntity.hasFiles()) {
|
||||
processedBooks++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (taskId != null && cancellationManager.isTaskCancelled(taskId)) {
|
||||
log.info("Library rescan for library {} was cancelled", library.getId());
|
||||
sendTaskProgressNotification(taskId, (processedBooks * 100) / totalBooks,
|
||||
|
||||
+2
-7
@@ -14,7 +14,6 @@ import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.LibraryScanMode;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryPathRepository;
|
||||
@@ -77,10 +76,7 @@ public class LibraryService {
|
||||
library.setIcon(request.getIcon());
|
||||
library.setIconType(request.getIconType());
|
||||
library.setWatch(request.isWatch());
|
||||
if (request.getScanMode() != null) {
|
||||
library.setScanMode(request.getScanMode());
|
||||
}
|
||||
library.setDefaultBookFormat(request.getDefaultBookFormat());
|
||||
library.setFormatPriority(request.getFormatPriority());
|
||||
|
||||
Set<String> currentPaths = library.getLibraryPaths().stream()
|
||||
.map(LibraryPathEntity::getPath)
|
||||
@@ -159,8 +155,7 @@ public class LibraryService {
|
||||
.icon(request.getIcon())
|
||||
.iconType(request.getIconType())
|
||||
.watch(request.isWatch())
|
||||
.scanMode(request.getScanMode() != null ? request.getScanMode() : LibraryScanMode.FILE_AS_BOOK)
|
||||
.defaultBookFormat(request.getDefaultBookFormat())
|
||||
.formatPriority(request.getFormatPriority())
|
||||
.users(List.of(user.get()))
|
||||
.build();
|
||||
|
||||
|
||||
+22
-5
@@ -140,7 +140,11 @@ public class BookCoverService {
|
||||
if (isCoverLocked(bookEntity)) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
}
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookEntity.getPrimaryBookFile().getBookType());
|
||||
var primaryFile = bookEntity.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
|
||||
}
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType());
|
||||
boolean success = processor.generateCover(bookEntity);
|
||||
if (!success) {
|
||||
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
|
||||
@@ -173,6 +177,7 @@ public class BookCoverService {
|
||||
try {
|
||||
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.filter(book -> book.getPrimaryBookFile() != null)
|
||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false))
|
||||
.toList();
|
||||
int total = books.size();
|
||||
@@ -188,7 +193,12 @@ public class BookCoverService {
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getPrimaryBookFile().getBookType());
|
||||
var primaryFile = book.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
log.warn("{}Skipping physical book ID {} ({}) - no file to regenerate cover from", progress, book.getId(), bookInfo.title());
|
||||
return;
|
||||
}
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType());
|
||||
boolean success = processor.generateCover(book);
|
||||
|
||||
if (success) {
|
||||
@@ -382,6 +392,7 @@ public class BookCoverService {
|
||||
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
|
||||
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
|
||||
.filter(book -> !isCoverLocked(book))
|
||||
.filter(book -> book.getPrimaryBookFile() != null)
|
||||
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getPrimaryBookFile().getBookType(), false))
|
||||
.toList();
|
||||
}
|
||||
@@ -400,15 +411,21 @@ public class BookCoverService {
|
||||
}
|
||||
|
||||
private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer<MetadataWriter, BookEntity> writerAction) {
|
||||
var primaryFile = bookEntity.getPrimaryBookFile();
|
||||
if (primaryFile == null) {
|
||||
// Physical book with no files - skip writing cover to file
|
||||
return;
|
||||
}
|
||||
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
|
||||
|
||||
if ((bookEntity.getPrimaryBookFile().getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(bookEntity.getPrimaryBookFile().getBookType())
|
||||
if ((primaryFile.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
|
||||
metadataWriterFactory.getWriter(primaryFile.getBookType())
|
||||
.ifPresent(writer -> {
|
||||
writerAction.accept(writer, bookEntity);
|
||||
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
|
||||
bookEntity.getPrimaryBookFile().setCurrentHash(newHash);
|
||||
primaryFile.setCurrentHash(newHash);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -125,8 +125,9 @@ public class BookMetadataService {
|
||||
public BookMetadata getComicInfoMetadata(long bookId) {
|
||||
log.info("Extracting ComicInfo metadata for book ID: {}", bookId);
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
if (bookEntity.getPrimaryBookFile().getBookType() != BookFileType.CBX) {
|
||||
log.info("Unsupported operation for file type: {}", bookEntity.getPrimaryBookFile().getBookType().name());
|
||||
var primaryFile = bookEntity.getPrimaryBookFile();
|
||||
if (primaryFile == null || primaryFile.getBookType() != BookFileType.CBX) {
|
||||
log.info("Unsupported operation for book ID {} - no file or not CBX type", bookId);
|
||||
return null;
|
||||
}
|
||||
return cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
|
||||
|
||||
+7
-5
@@ -87,7 +87,7 @@ public class BookMetadataUpdater {
|
||||
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
|
||||
MetadataPersistenceSettings.SaveToOriginalFile writeToFile = settings.getSaveToOriginalFile();
|
||||
var primaryFile = bookEntity.getPrimaryBookFile();
|
||||
BookFileType bookType = primaryFile.getBookType();
|
||||
BookFileType bookType = primaryFile != null ? primaryFile.getBookType() : null;
|
||||
|
||||
boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags);
|
||||
|
||||
@@ -109,7 +109,7 @@ public class BookMetadataUpdater {
|
||||
log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage());
|
||||
}
|
||||
|
||||
if ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) {
|
||||
if (primaryFile != null && bookType != null && ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate)) {
|
||||
metadataWriterFactory.getWriter(bookType).ifPresent(writer -> {
|
||||
try {
|
||||
String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null;
|
||||
@@ -130,14 +130,16 @@ public class BookMetadataUpdater {
|
||||
}
|
||||
|
||||
boolean moveFilesToLibraryPattern = settings.isMoveFilesToLibraryPattern();
|
||||
if (moveFilesToLibraryPattern) {
|
||||
if (moveFilesToLibraryPattern && primaryFile != null) {
|
||||
try {
|
||||
BookEntity book = metadata.getBook();
|
||||
FileMoveResult result = fileMoveService.moveSingleFile(book);
|
||||
if (result.isMoved()) {
|
||||
var bookPrimaryFile = book.getPrimaryBookFile();
|
||||
bookPrimaryFile.setFileName(result.getNewFileName());
|
||||
bookPrimaryFile.setFileSubPath(result.getNewFileSubPath());
|
||||
if (bookPrimaryFile != null) {
|
||||
bookPrimaryFile.setFileName(result.getNewFileName());
|
||||
bookPrimaryFile.setFileSubPath(result.getNewFileSubPath());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to move files for book ID {} after metadata update: {}", bookId, e.getMessage());
|
||||
|
||||
+33
-12
@@ -27,8 +27,10 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
private static final String SEARCH_BASE_URL = "https://duckduckgo.com/?q=";
|
||||
private static final String JSON_BASE_URL = "https://duckduckgo.com/i.js?o=json&q=";
|
||||
private static final String SITE_FILTER = "+(site%3Aamazon.com+OR+site%3Agoodreads.com)";
|
||||
private static final String SEARCH_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
private static final String JSON_PARAMS = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
private static final String SEARCH_PARAMS_TALL = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
private static final String JSON_PARAMS_TALL = "&iar=images&iaf=size%3ALarge%2Clayout%3ATall";
|
||||
private static final String SEARCH_PARAMS_SQUARE = "&iar=images&iaf=size%3ALarge%2Clayout%3ASquare";
|
||||
private static final String JSON_PARAMS_SQUARE = "&iar=images&iaf=size%3ALarge%2Clayout%3ASquare";
|
||||
|
||||
private static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
||||
private static final String REFERRER = "https://duckduckgo.com/";
|
||||
@@ -63,12 +65,17 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
public List<CoverImage> getCovers(CoverFetchRequest request) {
|
||||
String title = request.getTitle();
|
||||
String author = request.getAuthor();
|
||||
boolean squareCover = request.isSquareCover();
|
||||
String bookType = squareCover ? "audiobook" : "book";
|
||||
String searchTerm = (author != null && !author.isEmpty())
|
||||
? title + " " + author + " book"
|
||||
: title + " book";
|
||||
? title + " " + author + " " + bookType
|
||||
: title + " " + bookType;
|
||||
|
||||
String searchParams = squareCover ? SEARCH_PARAMS_SQUARE : SEARCH_PARAMS_TALL;
|
||||
String jsonParams = squareCover ? JSON_PARAMS_SQUARE : JSON_PARAMS_TALL;
|
||||
|
||||
String encodedSiteQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
||||
String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + SEARCH_PARAMS;
|
||||
String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + searchParams;
|
||||
Connection.Response siteResponse = getResponse(siteUrl);
|
||||
Document siteDoc = parseResponse(siteResponse);
|
||||
Map<String, String> cookies = siteResponse.cookies();
|
||||
@@ -79,15 +86,19 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
String siteSearchToken = siteMatcher.group(1);
|
||||
List<CoverImage> siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken, cookies, siteUrl);
|
||||
List<CoverImage> siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken, cookies, siteUrl, jsonParams);
|
||||
siteFilteredImages.removeIf(dto -> dto.getWidth() < 350);
|
||||
siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
if (squareCover) {
|
||||
siteFilteredImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight()));
|
||||
} else {
|
||||
siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
}
|
||||
if (siteFilteredImages.size() > 7) {
|
||||
siteFilteredImages = siteFilteredImages.subList(0, 7);
|
||||
}
|
||||
|
||||
String encodedGeneralQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8);
|
||||
String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + SEARCH_PARAMS;
|
||||
String generalUrl = SEARCH_BASE_URL + encodedGeneralQuery + searchParams;
|
||||
Connection.Response generalResponse = getResponse(generalUrl);
|
||||
Document generalDoc = parseResponse(generalResponse);
|
||||
Map<String, String> generalCookies = generalResponse.cookies();
|
||||
@@ -95,9 +106,13 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
List<CoverImage> generalBookImages = new ArrayList<>();
|
||||
if (generalMatcher.find()) {
|
||||
String generalSearchToken = generalMatcher.group(1);
|
||||
generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken, generalCookies, generalUrl);
|
||||
generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken, generalCookies, generalUrl, jsonParams);
|
||||
generalBookImages.removeIf(dto -> dto.getWidth() < 350);
|
||||
generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
if (squareCover) {
|
||||
generalBookImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight()));
|
||||
} else {
|
||||
generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight());
|
||||
}
|
||||
Set<String> siteUrls = siteFilteredImages.stream().map(CoverImage::getUrl).collect(Collectors.toSet());
|
||||
generalBookImages.removeIf(dto -> siteUrls.contains(dto.getUrl()));
|
||||
if (generalBookImages.size() > 10) {
|
||||
@@ -121,13 +136,13 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
return allImages;
|
||||
}
|
||||
|
||||
private List<CoverImage> fetchImagesFromApi(String query, String searchToken, Map<String, String> cookies, String referrerUrl) {
|
||||
private List<CoverImage> fetchImagesFromApi(String query, String searchToken, Map<String, String> cookies, String referrerUrl, String jsonParams) {
|
||||
List<CoverImage> priority = new ArrayList<>();
|
||||
List<CoverImage> others = new ArrayList<>();
|
||||
try {
|
||||
String url = JSON_BASE_URL
|
||||
+ URLEncoder.encode(query, StandardCharsets.UTF_8)
|
||||
+ JSON_PARAMS
|
||||
+ jsonParams
|
||||
+ "&vqd=" + searchToken;
|
||||
|
||||
Connection.Response resp = Jsoup.connect(url)
|
||||
@@ -185,4 +200,10 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isApproximatelySquare(int width, int height) {
|
||||
if (width == 0 || height == 0) return false;
|
||||
double ratio = (double) width / height;
|
||||
return ratio >= 0.85 && ratio <= 1.15;
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -115,7 +115,7 @@ public class MetadataRefreshService {
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
try {
|
||||
if (book.getMetadata().areAllFieldsLocked()) {
|
||||
log.info("Skipping locked book: {}", book.getPrimaryBookFile().getFileName());
|
||||
log.info("Skipping locked book: {}", getBookIdentifier(book));
|
||||
sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, "Skipped locked book: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode);
|
||||
return null;
|
||||
}
|
||||
@@ -165,11 +165,11 @@ public class MetadataRefreshService {
|
||||
sendBatchProgressNotification(jobId, finalCompletedCount + 1, totalBooks, "Processed: " + book.getMetadata().getTitle(), MetadataFetchTaskStatus.IN_PROGRESS, bookReviewMode);
|
||||
} catch (Exception e) {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
log.info("Processing interrupted for book: {}", book.getPrimaryBookFile().getFileName());
|
||||
log.info("Processing interrupted for book: {}", getBookIdentifier(book));
|
||||
status.setRollbackOnly();
|
||||
return null;
|
||||
}
|
||||
log.error("Metadata update failed for book: {}", book.getPrimaryBookFile().getFileName(), e);
|
||||
log.error("Metadata update failed for book: {}", getBookIdentifier(book), e);
|
||||
sendBatchProgressNotification(jobId, finalCompletedCount, totalBooks, String.format("Failed to process: %s - %s", book.getMetadata().getTitle(), e.getMessage()), MetadataFetchTaskStatus.ERROR, isReviewMode);
|
||||
}
|
||||
bookRepository.saveAndFlush(book);
|
||||
@@ -246,6 +246,16 @@ public class MetadataRefreshService {
|
||||
sendBatchProgressNotification(taskId, completedCount, total, message, MetadataFetchTaskStatus.IN_PROGRESS, isReviewMode);
|
||||
}
|
||||
|
||||
private String getBookIdentifier(BookEntity book) {
|
||||
if (book.getPrimaryBookFile() != null && book.getPrimaryBookFile().getFileName() != null) {
|
||||
return book.getPrimaryBookFile().getFileName();
|
||||
}
|
||||
if (book.getMetadata() != null && book.getMetadata().getTitle() != null) {
|
||||
return book.getMetadata().getTitle();
|
||||
}
|
||||
return "Book ID: " + book.getId();
|
||||
}
|
||||
|
||||
private void sendBatchProgressNotification(String taskId, int current, int total, String message, MetadataFetchTaskStatus status, boolean isReview) {
|
||||
notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_PROGRESS, new MetadataBatchProgressNotification(taskId, current, total, message, status.name(), isReview));
|
||||
}
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.jaudiotagger.audio.AudioFile;
|
||||
import org.jaudiotagger.audio.AudioFileIO;
|
||||
import org.jaudiotagger.tag.FieldKey;
|
||||
import org.jaudiotagger.tag.Tag;
|
||||
import org.jaudiotagger.tag.images.Artwork;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AudiobookMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
static {
|
||||
// Suppress verbose JAudioTagger logging
|
||||
Logger.getLogger("org.jaudiotagger").setLevel(Level.WARNING);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File audioFile) {
|
||||
try {
|
||||
AudioFile f = AudioFileIO.read(audioFile);
|
||||
Tag tag = f.getTag();
|
||||
|
||||
if (tag == null) {
|
||||
return BookMetadata.builder()
|
||||
.title(FilenameUtils.getBaseName(audioFile.getName()))
|
||||
.build();
|
||||
}
|
||||
|
||||
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder();
|
||||
|
||||
// Title - prefer album for audiobooks, fallback to title, then filename
|
||||
String album = tag.getFirst(FieldKey.ALBUM);
|
||||
String title = tag.getFirst(FieldKey.TITLE);
|
||||
if (StringUtils.isNotBlank(album)) {
|
||||
builder.title(album);
|
||||
} else if (StringUtils.isNotBlank(title)) {
|
||||
builder.title(title);
|
||||
} else {
|
||||
builder.title(FilenameUtils.getBaseName(audioFile.getName()));
|
||||
}
|
||||
|
||||
// Author - use album artist or artist
|
||||
String albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST);
|
||||
String artist = tag.getFirst(FieldKey.ARTIST);
|
||||
Set<String> authors = new HashSet<>();
|
||||
if (StringUtils.isNotBlank(albumArtist)) {
|
||||
authors.add(albumArtist);
|
||||
} else if (StringUtils.isNotBlank(artist)) {
|
||||
authors.add(artist);
|
||||
}
|
||||
if (!authors.isEmpty()) {
|
||||
builder.authors(authors);
|
||||
}
|
||||
|
||||
// Description - use comment field
|
||||
String comment = tag.getFirst(FieldKey.COMMENT);
|
||||
if (StringUtils.isNotBlank(comment)) {
|
||||
builder.description(comment);
|
||||
}
|
||||
|
||||
// Publisher - use record label or publisher
|
||||
String publisher = tag.getFirst(FieldKey.RECORD_LABEL);
|
||||
if (StringUtils.isNotBlank(publisher)) {
|
||||
builder.publisher(publisher);
|
||||
}
|
||||
|
||||
// Year/Date
|
||||
String year = tag.getFirst(FieldKey.YEAR);
|
||||
if (StringUtils.isNotBlank(year)) {
|
||||
try {
|
||||
int yearInt = Integer.parseInt(year.trim().substring(0, Math.min(4, year.trim().length())));
|
||||
if (yearInt >= 1 && yearInt <= 9999) {
|
||||
builder.publishedDate(LocalDate.of(yearInt, 1, 1));
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// Genre as category
|
||||
String genre = tag.getFirst(FieldKey.GENRE);
|
||||
if (StringUtils.isNotBlank(genre)) {
|
||||
Set<String> categories = new HashSet<>();
|
||||
categories.add(genre);
|
||||
builder.categories(categories);
|
||||
}
|
||||
|
||||
// Language
|
||||
String language = tag.getFirst(FieldKey.LANGUAGE);
|
||||
if (StringUtils.isNotBlank(language)) {
|
||||
builder.language(language);
|
||||
}
|
||||
|
||||
// Series info from grouping or custom tags
|
||||
String grouping = tag.getFirst(FieldKey.GROUPING);
|
||||
if (StringUtils.isNotBlank(grouping)) {
|
||||
builder.seriesName(grouping);
|
||||
}
|
||||
|
||||
// Try to extract track number as series number for multi-part audiobooks
|
||||
String trackNo = tag.getFirst(FieldKey.TRACK);
|
||||
if (StringUtils.isNotBlank(trackNo)) {
|
||||
try {
|
||||
String trackNum = trackNo.contains("/") ? trackNo.split("/")[0] : trackNo;
|
||||
builder.seriesNumber((float) Integer.parseInt(trackNum.trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// Try to get total tracks
|
||||
String trackTotal = tag.getFirst(FieldKey.TRACK_TOTAL);
|
||||
if (StringUtils.isNotBlank(trackTotal)) {
|
||||
try {
|
||||
builder.seriesTotal(Integer.parseInt(trackTotal.trim()));
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to read metadata from audio file {}: {}", audioFile.getName(), e.getMessage(), e);
|
||||
return BookMetadata.builder()
|
||||
.title(FilenameUtils.getBaseName(audioFile.getName()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File audioFile) {
|
||||
try {
|
||||
AudioFile f = AudioFileIO.read(audioFile);
|
||||
Tag tag = f.getTag();
|
||||
|
||||
if (tag == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Artwork artwork = tag.getFirstArtwork();
|
||||
if (artwork != null) {
|
||||
return artwork.getBinaryData();
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract cover from audio file {}: {}", audioFile.getName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
@@ -18,6 +18,7 @@ public class MetadataExtractorFactory {
|
||||
private final Fb2MetadataExtractor fb2MetadataExtractor;
|
||||
private final MobiMetadataExtractor mobiMetadataExtractor;
|
||||
private final Azw3MetadataExtractor azw3MetadataExtractor;
|
||||
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
|
||||
|
||||
public BookMetadata extractMetadata(BookFileType bookFileType, File file) {
|
||||
return switch (bookFileType) {
|
||||
@@ -27,6 +28,7 @@ public class MetadataExtractorFactory {
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3 -> azw3MetadataExtractor.extractMetadata(file);
|
||||
case AUDIOBOOK -> audiobookMetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,6 +40,7 @@ public class MetadataExtractorFactory {
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractMetadata(file);
|
||||
case M4B, M4A, MP3, AAC, FLAC, OPUS, OGG -> audiobookMetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,6 +52,7 @@ public class MetadataExtractorFactory {
|
||||
case FB2 -> fb2MetadataExtractor.extractCover(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractCover(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractCover(file);
|
||||
case M4B, M4A, MP3, AAC, FLAC, OPUS, OGG -> audiobookMetadataExtractor.extractCover(file);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -276,8 +276,8 @@ public class AmazonBookParser implements BookParser {
|
||||
String title = fetchMetadataRequest.getTitle();
|
||||
if (title != null && !title.isEmpty()) {
|
||||
searchTerm.append(cleanSearchTerm(title));
|
||||
} else {
|
||||
String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getFileName()));
|
||||
} else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null) {
|
||||
String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getPrimaryFile().getFileName()));
|
||||
if (!filename.isEmpty()) {
|
||||
searchTerm.append(cleanSearchTerm(filename));
|
||||
}
|
||||
|
||||
+2
-2
@@ -800,9 +800,9 @@ public class ComicvineBookParser implements BookParser {
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
||||
return request.getTitle();
|
||||
} else if (book.getFileName() != null && !book.getFileName().isEmpty()) {
|
||||
} else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()) {
|
||||
// Use filename but preserve parentheses for year extraction
|
||||
String name = book.getFileName();
|
||||
String name = book.getPrimaryFile().getFileName();
|
||||
// Remove extension only
|
||||
int dotIndex = name.lastIndexOf('.');
|
||||
if (dotIndex > 0) {
|
||||
|
||||
+3
-3
@@ -116,7 +116,7 @@ public class DoubanBookParser implements BookParser {
|
||||
}
|
||||
|
||||
private List<BookMetadata> getDoubanSearchResults(Book book, FetchMetadataRequest request) {
|
||||
log.debug("Douban: Querying metadata for ISBN: {}, Title: {}, Author: {}, FileName: {}", request.getIsbn(), request.getTitle(), request.getAuthor(), book.getFileName());
|
||||
log.debug("Douban: Querying metadata for ISBN: {}, Title: {}, Author: {}, FileName: {}", request.getIsbn(), request.getTitle(), request.getAuthor(), book.getPrimaryFile() != null ? book.getPrimaryFile().getFileName() : null);
|
||||
String queryUrl = buildQueryUrl(request, book);
|
||||
if (queryUrl == null) {
|
||||
log.error("Query URL is null, cannot proceed.");
|
||||
@@ -309,8 +309,8 @@ public class DoubanBookParser implements BookParser {
|
||||
.filter(word -> !word.isEmpty())
|
||||
.collect(Collectors.joining(" "));
|
||||
searchTerm.append(cleanedTitle);
|
||||
} else {
|
||||
String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getFileName()));
|
||||
} else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null) {
|
||||
String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getPrimaryFile().getFileName()));
|
||||
if (!filename.isEmpty()) {
|
||||
String cleanedFilename = Arrays.stream(filename.split(" "))
|
||||
.map(word -> NON_ALPHANUMERIC_CJK_PATTERN.matcher(word).replaceAll("").trim())
|
||||
|
||||
+2
-2
@@ -497,8 +497,8 @@ public class GoodReadsParser implements BookParser {
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
return (request.getTitle() != null && !request.getTitle().isEmpty())
|
||||
? request.getTitle()
|
||||
: (book.getFileName() != null && !book.getFileName().isEmpty()
|
||||
? BookUtils.cleanFileName(book.getFileName())
|
||||
: (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()
|
||||
? BookUtils.cleanFileName(book.getPrimaryFile().getFileName())
|
||||
: null);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -444,7 +444,8 @@ public class GoogleParser implements BookParser {
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
String searchTerm = Optional.ofNullable(request.getTitle())
|
||||
.filter(title -> !title.isEmpty())
|
||||
.orElseGet(() -> Optional.ofNullable(book.getFileName())
|
||||
.orElseGet(() -> Optional.ofNullable(book.getPrimaryFile())
|
||||
.map(pf -> pf.getFileName())
|
||||
.filter(fileName -> !fileName.isEmpty())
|
||||
.map(BookUtils::cleanFileName)
|
||||
.orElse(null));
|
||||
|
||||
+2
-2
@@ -157,8 +157,8 @@ public class RanobeDbParser implements BookParser {
|
||||
private String getSearchTerm(Book book, FetchMetadataRequest request) {
|
||||
if (request.getTitle() != null && !request.getTitle().isEmpty()) {
|
||||
return request.getTitle();
|
||||
} else if (book.getFileName() != null && !book.getFileName().isEmpty()) {
|
||||
return BookUtils.cleanFileName(book.getFileName());
|
||||
} else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null && !book.getPrimaryFile().getFileName().isEmpty()) {
|
||||
return BookUtils.cleanFileName(book.getPrimaryFile().getFileName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
+2
@@ -20,6 +20,7 @@ public class AppMigrationStartup {
|
||||
private final PopulateSearchTextMigration populateSearchTextMigration;
|
||||
private final MoveIconsToDataFolderMigration moveIconsToDataFolderMigration;
|
||||
private final GenerateCoverHashMigration generateCoverHashMigration;
|
||||
private final MigrateProgressToFileProgressMigration migrateProgressToFileProgressMigration;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void runMigrationsOnce() {
|
||||
@@ -32,5 +33,6 @@ public class AppMigrationStartup {
|
||||
appMigrationService.executeMigration(populateSearchTextMigration);
|
||||
appMigrationService.executeMigration(moveIconsToDataFolderMigration);
|
||||
appMigrationService.executeMigration(generateCoverHashMigration);
|
||||
appMigrationService.executeMigration(migrateProgressToFileProgressMigration);
|
||||
}
|
||||
}
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.adityachandel.booklore.service.migration.migrations;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookFileProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.UserBookFileProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.service.migration.Migration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MigrateProgressToFileProgressMigration implements Migration {
|
||||
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final UserBookFileProgressRepository userBookFileProgressRepository;
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return "migrateProgressToFileProgress";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Migrate existing reading progress from UserBookProgressEntity to UserBookFileProgressEntity";
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void execute() {
|
||||
log.info("Starting migration: {}", getKey());
|
||||
|
||||
List<UserBookProgressEntity> allProgress = userBookProgressRepository.findAll();
|
||||
int migratedCount = 0;
|
||||
int skippedCount = 0;
|
||||
|
||||
for (UserBookProgressEntity progress : allProgress) {
|
||||
if (!hasAnyProgress(progress)) {
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
Optional<BookFileEntity> bookFileOpt = findBookFileForProgress(progress);
|
||||
if (bookFileOpt.isEmpty()) {
|
||||
log.debug("No matching book file found for progress id={}, bookId={}",
|
||||
progress.getId(), progress.getBook().getId());
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
BookFileEntity bookFile = bookFileOpt.get();
|
||||
|
||||
// Check if file progress already exists
|
||||
Optional<UserBookFileProgressEntity> existingFileProgress =
|
||||
userBookFileProgressRepository.findByUserIdAndBookFileId(
|
||||
progress.getUser().getId(), bookFile.getId());
|
||||
|
||||
if (existingFileProgress.isPresent()) {
|
||||
log.debug("File progress already exists for userId={}, bookFileId={}",
|
||||
progress.getUser().getId(), bookFile.getId());
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
UserBookFileProgressEntity fileProgress = createFileProgress(progress, bookFile);
|
||||
userBookFileProgressRepository.save(fileProgress);
|
||||
migratedCount++;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to migrate progress for progressId={}: {}",
|
||||
progress.getId(), e.getMessage());
|
||||
skippedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Migration '{}' completed. Migrated: {}, Skipped: {}",
|
||||
getKey(), migratedCount, skippedCount);
|
||||
}
|
||||
|
||||
private boolean hasAnyProgress(UserBookProgressEntity progress) {
|
||||
return progress.getPdfProgress() != null ||
|
||||
progress.getEpubProgress() != null ||
|
||||
progress.getCbxProgress() != null;
|
||||
}
|
||||
|
||||
private Optional<BookFileEntity> findBookFileForProgress(UserBookProgressEntity progress) {
|
||||
if (progress.getBook() == null || progress.getBook().getBookFiles() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<BookFileEntity> bookFiles = progress.getBook().getBookFiles();
|
||||
if (bookFiles.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
// Determine which type of progress we have and find matching book file
|
||||
if (progress.getPdfProgress() != null) {
|
||||
return findBookFileByType(bookFiles, BookFileType.PDF);
|
||||
} else if (progress.getEpubProgress() != null) {
|
||||
// EPUB progress can apply to EPUB, FB2, MOBI, AZW3
|
||||
return findBookFileByTypes(bookFiles, BookFileType.EPUB, BookFileType.FB2,
|
||||
BookFileType.MOBI, BookFileType.AZW3);
|
||||
} else if (progress.getCbxProgress() != null) {
|
||||
return findBookFileByType(bookFiles, BookFileType.CBX);
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<BookFileEntity> findBookFileByType(List<BookFileEntity> bookFiles, BookFileType type) {
|
||||
return bookFiles.stream()
|
||||
.filter(bf -> bf.isBookFormat() && bf.getBookType() == type)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private Optional<BookFileEntity> findBookFileByTypes(List<BookFileEntity> bookFiles, BookFileType... types) {
|
||||
for (BookFileType type : types) {
|
||||
Optional<BookFileEntity> found = findBookFileByType(bookFiles, type);
|
||||
if (found.isPresent()) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private UserBookFileProgressEntity createFileProgress(UserBookProgressEntity progress, BookFileEntity bookFile) {
|
||||
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
|
||||
fileProgress.setUser(progress.getUser());
|
||||
fileProgress.setBookFile(bookFile);
|
||||
fileProgress.setLastReadTime(progress.getLastReadTime());
|
||||
|
||||
// Map progress data based on book type
|
||||
switch (bookFile.getBookType()) {
|
||||
case PDF -> {
|
||||
fileProgress.setPositionData(progress.getPdfProgress() != null ?
|
||||
String.valueOf(progress.getPdfProgress()) : null);
|
||||
fileProgress.setProgressPercent(progress.getPdfProgressPercent());
|
||||
}
|
||||
case EPUB, FB2, MOBI, AZW3 -> {
|
||||
fileProgress.setPositionData(progress.getEpubProgress());
|
||||
fileProgress.setPositionHref(progress.getEpubProgressHref());
|
||||
fileProgress.setProgressPercent(progress.getEpubProgressPercent());
|
||||
}
|
||||
case CBX -> {
|
||||
fileProgress.setPositionData(progress.getCbxProgress() != null ?
|
||||
String.valueOf(progress.getCbxProgress()) : null);
|
||||
fileProgress.setProgressPercent(progress.getCbxProgressPercent());
|
||||
}
|
||||
}
|
||||
|
||||
return fileProgress;
|
||||
}
|
||||
}
|
||||
+55
-19
@@ -3,11 +3,11 @@ package com.adityachandel.booklore.service.opds;
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookFile;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.enums.OpdsSortOrder;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -543,9 +543,17 @@ public class OpdsFeedService {
|
||||
}
|
||||
|
||||
private void appendLinks(StringBuilder feed, Book book) {
|
||||
String mimeType = fileMimeType(book);
|
||||
feed.append(" <link href=\"/api/v1/opds/")
|
||||
.append(book.getId()).append("/download\" rel=\"http://opds-spec.org/acquisition\" type=\"").append(mimeType).append("\"/>\n");
|
||||
// Add acquisition link for primary file
|
||||
if (book.getPrimaryFile() != null) {
|
||||
appendAcquisitionLink(feed, book.getId(), book.getPrimaryFile());
|
||||
}
|
||||
|
||||
// Add acquisition links for alternative formats
|
||||
if (book.getAlternativeFormats() != null) {
|
||||
for (BookFile altFormat : book.getAlternativeFormats()) {
|
||||
appendAcquisitionLink(feed, book.getId(), altFormat);
|
||||
}
|
||||
}
|
||||
|
||||
if (book.getMetadata() != null && book.getMetadata().getCoverUpdatedOn() != null) {
|
||||
String coverUrl = "/api/v1/opds/" + book.getId() + "/cover?" + book.getMetadata().getCoverUpdatedOn();
|
||||
@@ -556,6 +564,26 @@ public class OpdsFeedService {
|
||||
}
|
||||
}
|
||||
|
||||
private void appendAcquisitionLink(StringBuilder feed, Long bookId, BookFile bookFile) {
|
||||
if (bookFile == null || bookFile.getId() == null) return;
|
||||
|
||||
String mimeType = fileMimeType(bookFile);
|
||||
feed.append(" <link href=\"/api/v1/opds/")
|
||||
.append(bookId)
|
||||
.append("/download?fileId=")
|
||||
.append(bookFile.getId())
|
||||
.append("\" rel=\"http://opds-spec.org/acquisition\" type=\"")
|
||||
.append(mimeType)
|
||||
.append("\"");
|
||||
|
||||
// Add title attribute to help readers distinguish formats
|
||||
if (bookFile.getBookType() != null) {
|
||||
feed.append(" title=\"").append(bookFile.getBookType().name()).append("\"");
|
||||
}
|
||||
|
||||
feed.append("/>\n");
|
||||
}
|
||||
|
||||
private String determineFeedTitle(Long libraryId, Set<Long> shelfIds, Long magicShelfId, String author, String series) {
|
||||
if (magicShelfId != null) {
|
||||
return magicShelfBookService.getMagicShelfName(magicShelfId);
|
||||
@@ -604,23 +632,22 @@ public class OpdsFeedService {
|
||||
return DateTimeFormatter.ISO_INSTANT.format(java.time.Instant.now());
|
||||
}
|
||||
|
||||
private boolean hasValidFilePath(Book book) {
|
||||
return book.getFileName() != null
|
||||
&& book.getLibraryPath() != null
|
||||
&& book.getLibraryPath().getPath() != null
|
||||
&& book.getFileSubPath() != null;
|
||||
private boolean hasValidFilePath(BookFile bookFile) {
|
||||
return bookFile != null
|
||||
&& bookFile.getFileName() != null
|
||||
&& bookFile.getFilePath() != null;
|
||||
}
|
||||
|
||||
private String fileMimeType(Book book) {
|
||||
if (book == null || book.getBookType() == null) {
|
||||
private String fileMimeType(BookFile bookFile) {
|
||||
if (bookFile == null || bookFile.getBookType() == null) {
|
||||
return "application/octet-stream";
|
||||
}
|
||||
return switch (book.getBookType()) {
|
||||
return switch (bookFile.getBookType()) {
|
||||
case PDF -> "application/pdf";
|
||||
case EPUB -> "application/epub+zip";
|
||||
case FB2 -> {
|
||||
if (hasValidFilePath(book)) {
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(book)));
|
||||
if (hasValidFilePath(bookFile)) {
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(bookFile.getFilePath()));
|
||||
if (type == ArchiveUtils.ArchiveType.ZIP) {
|
||||
yield "application/zip";
|
||||
}
|
||||
@@ -630,8 +657,8 @@ public class OpdsFeedService {
|
||||
case MOBI -> "application/x-mobipocket-ebook";
|
||||
case AZW3 -> "application/vnd.amazon.ebook";
|
||||
case CBX -> {
|
||||
if (book.getArchiveType() != null) {
|
||||
yield switch (book.getArchiveType()) {
|
||||
if (bookFile.getArchiveType() != null) {
|
||||
yield switch (bookFile.getArchiveType()) {
|
||||
case RAR -> "application/vnd.comicbook-rar";
|
||||
case ZIP -> "application/vnd.comicbook+zip";
|
||||
case SEVEN_ZIP -> "application/x-7z-compressed";
|
||||
@@ -639,14 +666,14 @@ public class OpdsFeedService {
|
||||
};
|
||||
}
|
||||
|
||||
if (hasValidFilePath(book)) {
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(book)));
|
||||
if (hasValidFilePath(bookFile)) {
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(bookFile.getFilePath()));
|
||||
yield switch (type) {
|
||||
case RAR -> "application/vnd.comicbook-rar";
|
||||
case ZIP -> "application/vnd.comicbook+zip";
|
||||
case SEVEN_ZIP -> "application/x-7z-compressed";
|
||||
default -> {
|
||||
String lower = book.getFileName().toLowerCase();
|
||||
String lower = bookFile.getFileName().toLowerCase();
|
||||
if (lower.endsWith(".cbr")) yield "application/vnd.comicbook-rar";
|
||||
if (lower.endsWith(".cbz")) yield "application/vnd.comicbook+zip";
|
||||
if (lower.endsWith(".cb7")) yield "application/x-7z-compressed";
|
||||
@@ -657,6 +684,15 @@ public class OpdsFeedService {
|
||||
}
|
||||
yield "application/vnd.comicbook+zip";
|
||||
}
|
||||
case AUDIOBOOK -> {
|
||||
String lower = bookFile.getFileName().toLowerCase();
|
||||
if (lower.endsWith(".m4b") || lower.endsWith(".m4a")) yield "audio/mp4";
|
||||
if (lower.endsWith(".mp3")) yield "audio/mpeg";
|
||||
if (lower.endsWith(".flac")) yield "audio/flac";
|
||||
if (lower.endsWith(".ogg") || lower.endsWith(".opus")) yield "audio/ogg";
|
||||
if (lower.endsWith(".aac")) yield "audio/aac";
|
||||
yield "audio/mp4";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user