Merge pull request #367 from adityachandelgit/develop
Merge Develop into Master for Release
This commit is contained in:
@@ -67,6 +67,8 @@ dependencies {
|
||||
|
||||
// --- API Documentation ---
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6'
|
||||
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||
implementation 'com.github.junrar:junrar:7.5.5'
|
||||
}
|
||||
|
||||
hibernate {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.adityachandel.booklore.config;
|
||||
|
||||
import com.adityachandel.booklore.service.AppSettingService;
|
||||
import jakarta.servlet.MultipartConfigElement;
|
||||
import org.springframework.boot.web.servlet.MultipartConfigFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.unit.DataSize;
|
||||
|
||||
@Configuration
|
||||
public class MultipartConfig {
|
||||
|
||||
@Bean
|
||||
public MultipartConfigElement multipartConfigElement(AppSettingService appSettingService) {
|
||||
MultipartConfigFactory factory = new MultipartConfigFactory();
|
||||
long maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
|
||||
|
||||
factory.setMaxFileSize(DataSize.ofMegabytes(maxSizeMb));
|
||||
factory.setMaxRequestSize(DataSize.ofMegabytes(maxSizeMb));
|
||||
return factory.createMultipartConfig();
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -51,7 +51,8 @@ public class SecurityConfig {
|
||||
"/api/v1/settings",
|
||||
"/api/v1/setup",
|
||||
"/api/v1/setup/**",
|
||||
"/api/v1/opds/*/cover.jpg"
|
||||
"/api/v1/opds/*/cover.jpg",
|
||||
"/api/v1/cbx/*/pages/*"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.service.CbxReaderService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/cbx")
|
||||
@RequiredArgsConstructor
|
||||
public class CbxReaderController {
|
||||
|
||||
private final CbxReaderService cbxReaderService;
|
||||
|
||||
@GetMapping("/{bookId}/pages")
|
||||
public List<Integer> listPages(@PathVariable Long bookId) {
|
||||
return cbxReaderService.getAvailablePages(bookId);
|
||||
}
|
||||
|
||||
@GetMapping("/{bookId}/pages/{pageNumber}")
|
||||
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
|
||||
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
|
||||
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,8 @@ public enum ApiError {
|
||||
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
|
||||
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"),
|
||||
LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"),
|
||||
FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: 100 MB"),
|
||||
FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: %d MB"),
|
||||
CACHE_TOO_LARGE(HttpStatus.BAD_REQUEST, "Book archive is too large to cache with current settings"),
|
||||
DIRECTORY_CREATION_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to create the directory: %s"),
|
||||
INVALID_LIBRARY_PATH(HttpStatus.BAD_REQUEST, "Invalid library path"),
|
||||
FILE_ALREADY_EXISTS(HttpStatus.CONFLICT, "File already exists"),
|
||||
|
||||
+4
@@ -60,6 +60,10 @@ public class BookLoreUserTransformer {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.EpubReaderSetting.class);
|
||||
userSettings.setEpubReaderSetting(value);
|
||||
}
|
||||
case CBX_READER_SETTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
|
||||
userSettings.setCbxReaderSetting(value);
|
||||
}
|
||||
case SIDEBAR_LIBRARY_SORTING -> {
|
||||
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
|
||||
userSettings.setSidebarLibrarySorting(value);
|
||||
|
||||
@@ -23,5 +23,6 @@ public class Book {
|
||||
private BookMetadata metadata;
|
||||
private PdfProgress pdfProgress;
|
||||
private EpubProgress epubProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
private List<Shelf> shelves;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
|
||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
@@ -36,6 +38,7 @@ public class BookLoreUser {
|
||||
public PerBookSetting perBookSetting;
|
||||
public PdfReaderSetting pdfReaderSetting;
|
||||
public EpubReaderSetting epubReaderSetting;
|
||||
public CbxReaderSetting cbxReaderSetting;
|
||||
public SidebarSortOption sidebarLibrarySorting;
|
||||
public SidebarSortOption sidebarShelfSorting;
|
||||
|
||||
@@ -50,7 +53,6 @@ public class BookLoreUser {
|
||||
private String flow;
|
||||
}
|
||||
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@@ -60,6 +62,15 @@ public class BookLoreUser {
|
||||
private String pageZoom;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class CbxReaderSetting {
|
||||
private CbxPageSpread pageSpread;
|
||||
private CbxPageViewMode pageViewMode;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@@ -67,6 +78,7 @@ public class BookLoreUser {
|
||||
public static class PerBookSetting {
|
||||
private GlobalOrIndividual pdf;
|
||||
private GlobalOrIndividual epub;
|
||||
private GlobalOrIndividual cbx;
|
||||
|
||||
public enum GlobalOrIndividual {
|
||||
Global, Individual
|
||||
|
||||
@@ -26,6 +26,7 @@ public class BookMetadata {
|
||||
private Integer seriesTotal;
|
||||
private String isbn13;
|
||||
private String isbn10;
|
||||
private String asin;
|
||||
private Integer pageCount;
|
||||
private String language;
|
||||
private Double rating;
|
||||
@@ -54,6 +55,7 @@ public class BookMetadata {
|
||||
private Boolean seriesTotalLocked;
|
||||
private Boolean isbn13Locked;
|
||||
private Boolean isbn10Locked;
|
||||
private Boolean asinLocked;
|
||||
private Boolean pageCountLocked;
|
||||
private Boolean languageLocked;
|
||||
private Boolean ratingLocked;
|
||||
|
||||
+1
@@ -8,4 +8,5 @@ import lombok.Data;
|
||||
public class BookViewerSettings {
|
||||
private PdfViewerPreferences pdfSettings;
|
||||
private EpubViewerPreferences epubSettings;
|
||||
private CbxViewerPreferences cbxSettings;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Builder
|
||||
@Data
|
||||
public class CbxProgress {
|
||||
@NotNull
|
||||
Integer page;
|
||||
@NotNull
|
||||
Float percentage;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class CbxViewerPreferences {
|
||||
private Long bookId;
|
||||
private CbxPageSpread pageSpread;
|
||||
private CbxPageViewMode pageViewMode;
|
||||
}
|
||||
+1
@@ -14,4 +14,5 @@ public class FetchMetadataRequest {
|
||||
private String isbn;
|
||||
private String title;
|
||||
private String author;
|
||||
private String asin;
|
||||
}
|
||||
|
||||
+3
-1
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.model.dto.request;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.CbxProgress;
|
||||
import com.adityachandel.booklore.model.dto.EpubProgress;
|
||||
import com.adityachandel.booklore.model.dto.PdfProgress;
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
@@ -12,9 +13,10 @@ public class ReadProgressRequest {
|
||||
private Long bookId;
|
||||
private EpubProgress epubProgress;
|
||||
private PdfProgress pdfProgress;
|
||||
private CbxProgress cbxProgress;
|
||||
|
||||
@AssertTrue(message = "Either epubProgress or pdfProgress must be provided")
|
||||
public boolean isProgressValid() {
|
||||
return epubProgress != null || pdfProgress != null;
|
||||
return epubProgress != null || pdfProgress != null || cbxProgress != null;
|
||||
}
|
||||
}
|
||||
|
||||
+7
-4
@@ -5,16 +5,19 @@ import lombok.Getter;
|
||||
@Getter
|
||||
public enum AppSettingKey {
|
||||
QUICK_BOOK_MATCH("quick_book_match", true),
|
||||
OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
|
||||
OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true),
|
||||
|
||||
AUTO_BOOK_SEARCH("auto_book_search", false),
|
||||
COVER_IMAGE_RESOLUTION("cover_image_resolution", false),
|
||||
SIMILAR_BOOK_RECOMMENDATION("similar_book_recommendation", false),
|
||||
UPLOAD_FILE_PATTERN("upload_file_pattern", false),
|
||||
OPDS_SERVER_ENABLED("opds_server_enabled", false),
|
||||
OIDC_ENABLED("oidc_enabled", false),
|
||||
OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
|
||||
OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true);
|
||||
CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false),
|
||||
MAX_FILE_UPLOAD_SIZE_IN_MB("max_file_upload_size_in_mb", false);
|
||||
|
||||
private final String dbKey;
|
||||
private final boolean isJson;
|
||||
|
||||
+2
@@ -17,6 +17,8 @@ public class AppSettings {
|
||||
private boolean similarBookRecommendation;
|
||||
private boolean opdsServerEnabled;
|
||||
private String uploadPattern;
|
||||
private Integer cbxCacheSizeInMb;
|
||||
private Integer maxFileUploadSizeInMb;
|
||||
|
||||
private boolean remoteAuthEnabled;
|
||||
private boolean oidcEnabled;
|
||||
|
||||
+1
@@ -7,6 +7,7 @@ public enum UserSettingKey {
|
||||
PER_BOOK_SETTING("perBookSetting", true),
|
||||
PDF_READER_SETTING("pdfReaderSetting", true),
|
||||
EPUB_READER_SETTING("epubReaderSetting", true),
|
||||
CBX_READER_SETTING("cbxReaderSetting", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true);
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@@ -60,4 +62,11 @@ public class BookEntity {
|
||||
@Column(name = "similar_books_json", columnDefinition = "TEXT")
|
||||
private List<BookRecommendationLite> similarBooksJson;
|
||||
|
||||
public Path getFullFilePath() {
|
||||
if (libraryPath == null || libraryPath.getPath() == null || fileSubPath == null || fileName == null) {
|
||||
throw new IllegalStateException("Cannot construct file path: missing library path, file subpath, or file name");
|
||||
}
|
||||
|
||||
return Paths.get(libraryPath.getPath(), fileSubPath, fileName);
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -51,6 +51,9 @@ public class BookMetadataEntity {
|
||||
@Column(name = "isbn_10", length = 10)
|
||||
private String isbn10;
|
||||
|
||||
@Column(name = "asin", length = 10)
|
||||
private String asin;
|
||||
|
||||
@Column(name = "page_count")
|
||||
private Integer pageCount;
|
||||
|
||||
@@ -104,6 +107,9 @@ public class BookMetadataEntity {
|
||||
@Column(name = "isbn_10_locked")
|
||||
private Boolean isbn10Locked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "asin_locked")
|
||||
private Boolean asinLocked = Boolean.FALSE;
|
||||
|
||||
@Column(name = "page_count_locked")
|
||||
private Boolean pageCountLocked = Boolean.FALSE;
|
||||
|
||||
@@ -181,6 +187,7 @@ public class BookMetadataEntity {
|
||||
this.descriptionLocked = lock;
|
||||
this.isbn13Locked = lock;
|
||||
this.isbn10Locked = lock;
|
||||
this.asinLocked = lock;
|
||||
this.pageCountLocked = lock;
|
||||
this.thumbnailLocked = lock;
|
||||
this.languageLocked = lock;
|
||||
@@ -206,6 +213,7 @@ public class BookMetadataEntity {
|
||||
|| Boolean.TRUE.equals(this.descriptionLocked)
|
||||
|| Boolean.TRUE.equals(this.isbn13Locked)
|
||||
|| Boolean.TRUE.equals(this.isbn10Locked)
|
||||
|| Boolean.TRUE.equals(this.asinLocked)
|
||||
|| Boolean.TRUE.equals(this.pageCountLocked)
|
||||
|| Boolean.TRUE.equals(this.thumbnailLocked)
|
||||
|| Boolean.TRUE.equals(this.languageLocked)
|
||||
@@ -231,6 +239,7 @@ public class BookMetadataEntity {
|
||||
&& Boolean.TRUE.equals(this.descriptionLocked)
|
||||
&& Boolean.TRUE.equals(this.isbn13Locked)
|
||||
&& Boolean.TRUE.equals(this.isbn10Locked)
|
||||
&& Boolean.TRUE.equals(this.asinLocked)
|
||||
&& Boolean.TRUE.equals(this.pageCountLocked)
|
||||
&& Boolean.TRUE.equals(this.thumbnailLocked)
|
||||
&& Boolean.TRUE.equals(this.languageLocked)
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "cbx_viewer_preference", uniqueConstraints = {
|
||||
@UniqueConstraint(columnNames = {"user_id", "book_id"})
|
||||
})
|
||||
public class CbxViewerPreferencesEntity {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "book_id", nullable = false)
|
||||
private Long bookId;
|
||||
|
||||
@Column(name = "spread")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private CbxPageSpread pageSpread;
|
||||
|
||||
@Column(name = "view_mode")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private CbxPageViewMode pageViewMode;
|
||||
}
|
||||
+6
@@ -40,4 +40,10 @@ public class UserBookProgressEntity {
|
||||
|
||||
@Column(name = "epub_progress_percent")
|
||||
private Float epubProgressPercent;
|
||||
|
||||
@Column(name = "cbx_progress")
|
||||
private Integer cbxProgress;
|
||||
|
||||
@Column(name = "cbx_progress_percent")
|
||||
private Float cbxProgressPercent;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum BookFileType {
|
||||
PDF, EPUB
|
||||
PDF, EPUB, CBX
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum CbxPageSpread {
|
||||
EVEN,
|
||||
ODD
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum CbxPageViewMode {
|
||||
SINGLE_PAGE,
|
||||
TWO_PAGE
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CbxViewerPreferencesRepository extends JpaRepository<CbxViewerPreferencesEntity, Long> {
|
||||
|
||||
Optional<CbxViewerPreferencesEntity> findByBookIdAndUserId(long bookId, Long id);
|
||||
}
|
||||
+66
@@ -1,10 +1,17 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserSettingEntity;
|
||||
import com.adityachandel.booklore.repository.AppMigrationRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.service.user.UserProvisioningService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -12,6 +19,7 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@@ -20,6 +28,7 @@ public class AppMigrationService {
|
||||
|
||||
private AppMigrationRepository migrationRepository;
|
||||
private BookRepository bookRepository;
|
||||
private UserProvisioningService userProvisioningService;
|
||||
|
||||
@Transactional
|
||||
public void populateMissingFileSizesOnce() {
|
||||
@@ -44,4 +53,61 @@ public class AppMigrationService {
|
||||
migrationRepository.save(migration);
|
||||
log.info("Migration 'populateFileSizes' executed successfully.");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addCbxReaderSettingToExistingUsers(UserRepository userRepository, ObjectMapper objectMapper) {
|
||||
final String migrationKey = "addCbxReaderSetting";
|
||||
|
||||
if (migrationRepository.existsById(migrationKey)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<BookLoreUserEntity> users = userRepository.findAll();
|
||||
int updatedCount = 0;
|
||||
AtomicInteger perBookUpdatedCount = new AtomicInteger();
|
||||
|
||||
for (BookLoreUserEntity user : users) {
|
||||
boolean hasCbxSetting = user.getSettings().stream().anyMatch(s -> s.getSettingKey().equals(UserSettingKey.CBX_READER_SETTING.getDbKey()));
|
||||
|
||||
if (!hasCbxSetting) {
|
||||
try {
|
||||
UserSettingEntity setting = UserSettingEntity.builder()
|
||||
.user(user)
|
||||
.settingKey(UserSettingKey.CBX_READER_SETTING.getDbKey())
|
||||
.settingValue(objectMapper.writeValueAsString(userProvisioningService.buildDefaultCbxReaderSetting()))
|
||||
.build();
|
||||
user.getSettings().add(setting);
|
||||
updatedCount++;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create CBX setting for user {}", user.getUsername(), e);
|
||||
}
|
||||
}
|
||||
|
||||
user.getSettings().stream()
|
||||
.filter(s -> s.getSettingKey().equals(UserSettingKey.PER_BOOK_SETTING.getDbKey()))
|
||||
.findFirst()
|
||||
.ifPresent(setting -> {
|
||||
try {
|
||||
var current = objectMapper.readValue(setting.getSettingValue(), BookLoreUser.UserSettings.PerBookSetting.class);
|
||||
if (current.getCbx() == null) {
|
||||
current.setCbx(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual);
|
||||
setting.setSettingValue(objectMapper.writeValueAsString(current));
|
||||
perBookUpdatedCount.getAndIncrement();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to update PER_BOOK_SETTING for user {}", user.getUsername(), e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
userRepository.saveAll(users);
|
||||
|
||||
AppMigrationEntity migration = new AppMigrationEntity();
|
||||
migration.setKey(migrationKey);
|
||||
migration.setExecutedAt(LocalDateTime.now());
|
||||
migration.setDescription("Add CBX reader setting and update PER_BOOK_SETTING to include CBX for existing users");
|
||||
migrationRepository.save(migration);
|
||||
|
||||
log.info("Migration '{}' completed. Added CBX setting to {} users and updated PER_BOOK_SETTING for {} users.", migrationKey, updatedCount, perBookUpdatedCount);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
@@ -10,9 +12,12 @@ import org.springframework.stereotype.Component;
|
||||
public class AppMigrationStartup {
|
||||
|
||||
private final AppMigrationService appMigrationService;
|
||||
private final UserRepository userRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void runMigrationsOnce() {
|
||||
appMigrationService.populateMissingFileSizesOnce();
|
||||
appMigrationService.addCbxReaderSettingToExistingUsers(userRepository, objectMapper);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +77,8 @@ public class AppSettingService {
|
||||
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
|
||||
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
|
||||
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
|
||||
builder.cbxCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
|
||||
builder.maxFileUploadSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
+10
-1
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.mapper.BookMetadataMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.CbxProgress;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
|
||||
@@ -19,6 +20,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
|
||||
import com.adityachandel.booklore.model.enums.MetadataProvider;
|
||||
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.service.metadata.parser.BookParser;
|
||||
@@ -54,6 +56,7 @@ public class BookMetadataService {
|
||||
private final FileService fileService;
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -197,6 +200,7 @@ public class BookMetadataService {
|
||||
metadataCombined.setPublishedDate(metadata.getPublishedDate() != null ? metadata.getPublishedDate() : metadataCombined.getPublishedDate());
|
||||
metadataCombined.setIsbn10(metadata.getIsbn10() != null ? metadata.getIsbn10() : metadataCombined.getIsbn10());
|
||||
metadataCombined.setIsbn13(metadata.getIsbn13() != null ? metadata.getIsbn13() : metadataCombined.getIsbn13());
|
||||
metadataCombined.setAsin(metadata.getAsin() != null ? metadata.getAsin() : metadataCombined.getAsin());
|
||||
metadataCombined.setPageCount(metadata.getPageCount() != null ? metadata.getPageCount() : metadataCombined.getPageCount());
|
||||
metadataCombined.setLanguage(metadata.getLanguage() != null ? metadata.getLanguage() : metadataCombined.getLanguage());
|
||||
metadataCombined.setRating(metadata.getRating() != null ? metadata.getRating() : metadataCombined.getRating());
|
||||
@@ -331,6 +335,7 @@ public class BookMetadataService {
|
||||
private FetchMetadataRequest buildFetchMetadataRequestFromBook(Book book) {
|
||||
return FetchMetadataRequest.builder()
|
||||
.isbn(book.getMetadata().getIsbn10())
|
||||
.asin(book.getMetadata().getAsin())
|
||||
.author(String.join(", ", book.getMetadata().getAuthors()))
|
||||
.title(book.getMetadata().getTitle())
|
||||
.bookId(book.getId())
|
||||
@@ -372,6 +377,9 @@ public class BookMetadataService {
|
||||
case "isbn13":
|
||||
existingMetadata.setIsbn13Locked(isLocked);
|
||||
break;
|
||||
case "asin":
|
||||
existingMetadata.setAsinLocked(isLocked);
|
||||
break;
|
||||
case "description":
|
||||
existingMetadata.setDescriptionLocked(isLocked);
|
||||
break;
|
||||
@@ -438,9 +446,10 @@ public class BookMetadataService {
|
||||
switch (book.getBookType()) {
|
||||
case PDF -> pdfProcessor.generateCover(book);
|
||||
case EPUB -> epubProcessor.generateCover(book);
|
||||
case CBX -> cbxProcessor.generateCover(book);
|
||||
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType());
|
||||
}
|
||||
log.info("{} Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
||||
+6
-1
@@ -71,7 +71,9 @@ public class BookMetadataUpdater {
|
||||
if ((metadata.getIsbn13Locked() == null || !metadata.getIsbn13Locked()) && newMetadata.getIsbn13() != null) {
|
||||
metadata.setIsbn13(newMetadata.getIsbn13().isBlank() ? null : newMetadata.getIsbn13());
|
||||
}
|
||||
|
||||
if ((metadata.getAsinLocked() == null || !metadata.getAsinLocked()) && newMetadata.getAsin() != null) {
|
||||
metadata.setAsin(newMetadata.getAsin().isBlank() ? null : newMetadata.getAsin());
|
||||
}
|
||||
if ((metadata.getDescriptionLocked() == null || !metadata.getDescriptionLocked()) && newMetadata.getDescription() != null) {
|
||||
metadata.setDescription(newMetadata.getDescription().isBlank() ? null : newMetadata.getDescription());
|
||||
}
|
||||
@@ -216,6 +218,9 @@ public class BookMetadataUpdater {
|
||||
if (newMetadata.getIsbn10Locked() != null) {
|
||||
metadata.setIsbn10Locked(newMetadata.getIsbn10Locked());
|
||||
}
|
||||
if (newMetadata.getAsinLocked() != null) {
|
||||
metadata.setAsinLocked(newMetadata.getAsinLocked());
|
||||
}
|
||||
if (newMetadata.getPageCountLocked() != null) {
|
||||
metadata.setPageCountLocked(newMetadata.getPageCountLocked());
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ public class BooksService {
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final ShelfRepository shelfRepository;
|
||||
private final FileService fileService;
|
||||
private final BookMapper bookMapper;
|
||||
@@ -67,6 +68,13 @@ public class BooksService {
|
||||
.zoom(pdfPref.getZoom())
|
||||
.spread(pdfPref.getSpread())
|
||||
.build()));
|
||||
} else if (bookEntity.getBookType() == BookFileType.CBX) {
|
||||
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
.pageViewMode(cbxPref.getPageViewMode())
|
||||
.pageSpread(cbxPref.getPageSpread())
|
||||
.build()));
|
||||
} else {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
@@ -111,6 +119,22 @@ public class BooksService {
|
||||
epubPrefs.setFlow(epubSettings.getFlow());
|
||||
epubViewerPreferencesRepository.save(epubPrefs);
|
||||
|
||||
} else if (bookEntity.getBookType() == BookFileType.CBX) {
|
||||
CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return cbxViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
|
||||
CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
|
||||
cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
|
||||
cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
|
||||
cbxViewerPreferencesRepository.save(cbxPrefs);
|
||||
|
||||
} else {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
@@ -137,6 +161,12 @@ public class BooksService {
|
||||
.percentage(userProgress.getEpubProgressPercent())
|
||||
.build());
|
||||
}
|
||||
if (bookEntity.getBookType() == BookFileType.CBX) {
|
||||
book.setCbxProgress(CbxProgress.builder()
|
||||
.page(userProgress.getCbxProgress())
|
||||
.percentage(userProgress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
|
||||
if (!withDescription) {
|
||||
@@ -180,6 +210,12 @@ public class BooksService {
|
||||
.percentage(userProgress.getPdfProgressPercent())
|
||||
.build());
|
||||
}
|
||||
if (bookEntity.getBookType() == BookFileType.CBX) {
|
||||
book.setCbxProgress(CbxProgress.builder()
|
||||
.page(userProgress.getCbxProgress())
|
||||
.percentage(userProgress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
return book;
|
||||
})
|
||||
@@ -236,6 +272,9 @@ public class BooksService {
|
||||
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
|
||||
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
|
||||
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
|
||||
} else if (book.getBookType() == BookFileType.CBX && request.getCbxProgress() != null) {
|
||||
userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
|
||||
userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
|
||||
}
|
||||
userBookProgressRepository.save(userBookProgress);
|
||||
}
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CbxMetadataExtractor implements UploadedFileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||
String title = FilenameUtils.getBaseName(filePath);
|
||||
metadata.setTitle(title);
|
||||
return metadata;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
import org.apache.pdfbox.io.IOUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CbxReaderService {
|
||||
|
||||
private static final String CACHE_INFO_FILENAME = ".cache-info";
|
||||
private static final String CBZ_EXTENSION = ".cbz";
|
||||
private static final String CBR_EXTENSION = ".cbr";
|
||||
private static final String CB7_EXTENSION = ".cb7";
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final FileService fileService;
|
||||
|
||||
public List<Integer> getAvailablePages(Long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
|
||||
|
||||
Path cbzPath = Path.of(bookFullPath);
|
||||
Path cacheDir = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId));
|
||||
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
|
||||
|
||||
try {
|
||||
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
|
||||
long estimatedSize = estimateArchiveSize(cbzPath);
|
||||
if (estimatedSize > maxCacheSizeBytes) {
|
||||
log.warn("Cache skipped: Estimated archive size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
|
||||
throw ApiError.CACHE_TOO_LARGE.createException();
|
||||
}
|
||||
enforceCacheLimit();
|
||||
|
||||
if (needsCacheRefresh(cbzPath, cacheInfoPath)) {
|
||||
log.info("Invalidating cache for book {}", bookId);
|
||||
if (Files.exists(cacheDir)) FileUtils.deleteDirectoryRecursively(cacheDir);
|
||||
Files.createDirectories(cacheDir);
|
||||
extractCbxArchive(cbzPath, cacheDir);
|
||||
writeCacheInfo(cbzPath, cacheInfoPath);
|
||||
if (!Files.exists(cacheDir)) {
|
||||
log.warn("Cache for book {} was deleted during enforcement. Re-extracting.", bookId);
|
||||
Files.createDirectories(cacheDir);
|
||||
extractCbxArchive(cbzPath, cacheDir);
|
||||
writeCacheInfo(cbzPath, cacheInfoPath);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to cache CBZ for book {}", bookId, e);
|
||||
return List.of();
|
||||
}
|
||||
|
||||
try (var stream = Files.list(cacheDir)) {
|
||||
return stream
|
||||
.filter(p -> p.toString().endsWith(".jpg"))
|
||||
.sorted(Comparator.comparing(Path::getFileName))
|
||||
.map(p -> extractPageNumber(p.getFileName().toString()))
|
||||
.filter(p -> p != -1)
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to list pages for book {}", bookId, e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
|
||||
Path pagePath = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId), String.format("%04d.jpg", page));
|
||||
if (!Files.exists(pagePath)) throw new FileNotFoundException("Page not found: " + page);
|
||||
try (InputStream in = Files.newInputStream(pagePath)) {
|
||||
IOUtils.copy(in, outputStream);
|
||||
}
|
||||
}
|
||||
|
||||
private void extractCbxArchive(Path cbxPath, Path targetDir) throws IOException {
|
||||
String filename = cbxPath.getFileName().toString().toLowerCase();
|
||||
if (filename.endsWith(CBZ_EXTENSION)) {
|
||||
extractZipArchive(cbxPath, targetDir);
|
||||
} else if (filename.endsWith(CB7_EXTENSION)) {
|
||||
extract7zArchive(cbxPath, targetDir);
|
||||
} else if (filename.endsWith(CBR_EXTENSION)) {
|
||||
extractRarArchive(cbxPath, targetDir);
|
||||
} else {
|
||||
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
private void extractZipArchive(Path cbzPath, Path targetDir) throws IOException {
|
||||
try (InputStream fis = Files.newInputStream(cbzPath);
|
||||
ZipInputStream zis = new ZipInputStream(fis)) {
|
||||
|
||||
ZipEntry entry;
|
||||
int index = 1;
|
||||
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
isImageFile(entry.getName());
|
||||
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
||||
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
|
||||
Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
zis.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void extract7zArchive(Path cb7Path, Path targetDir) throws IOException {
|
||||
try (SevenZFile sevenZFile = new SevenZFile(cb7Path.toFile())) {
|
||||
SevenZArchiveEntry entry;
|
||||
int index = 1;
|
||||
while ((entry = sevenZFile.getNextEntry()) != null) {
|
||||
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
||||
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
|
||||
try (OutputStream out = Files.newOutputStream(target)) {
|
||||
copySevenZEntry(sevenZFile, out, entry.getSize());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void copySevenZEntry(SevenZFile sevenZFile, OutputStream out, long size) throws IOException {
|
||||
byte[] buffer = new byte[8192];
|
||||
long read = 0;
|
||||
int count;
|
||||
while (read < size && (count = sevenZFile.read(buffer, 0, (int) Math.min(buffer.length, size - read))) > 0) {
|
||||
out.write(buffer, 0, count);
|
||||
read += count;
|
||||
}
|
||||
}
|
||||
|
||||
private void extractRarArchive(Path cbrPath, Path targetDir) throws IOException {
|
||||
try (Archive archive = new Archive(cbrPath.toFile())) {
|
||||
List<FileHeader> headers = archive.getFileHeaders();
|
||||
int index = 1;
|
||||
for (FileHeader header : headers) {
|
||||
if (!header.isDirectory() && isImageFile(header.getFileName())) {
|
||||
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
|
||||
try (OutputStream out = Files.newOutputStream(target)) {
|
||||
archive.extractFile(header, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to extract CBR archive", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isImageFile(String name) {
|
||||
String lower = name.toLowerCase().replace("\\", "/");
|
||||
return lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png");
|
||||
}
|
||||
|
||||
private int extractPageNumber(String filename) {
|
||||
try {
|
||||
return Integer.parseInt(filename.replaceAll("\\D+", ""));
|
||||
} catch (Exception e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean needsCacheRefresh(Path cbzPath, Path cacheInfoPath) throws IOException {
|
||||
if (!Files.exists(cacheInfoPath)) return true;
|
||||
|
||||
long currentLastModified = Files.getLastModifiedTime(cbzPath).toMillis();
|
||||
String recordedTimestamp = Files.readString(cacheInfoPath).trim();
|
||||
|
||||
try {
|
||||
long recordedLastModified = Long.parseLong(recordedTimestamp);
|
||||
return recordedLastModified != currentLastModified;
|
||||
} catch (NumberFormatException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCacheInfo(Path cbzPath, Path cacheInfoPath) throws IOException {
|
||||
long lastModified = Files.getLastModifiedTime(cbzPath).toMillis();
|
||||
Files.writeString(cacheInfoPath, String.valueOf(lastModified), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
|
||||
}
|
||||
|
||||
private void enforceCacheLimit() {
|
||||
try {
|
||||
Path cacheRoot = Path.of(fileService.getCbxCachePath());
|
||||
if (!Files.exists(cacheRoot) || !Files.isDirectory(cacheRoot)) {
|
||||
return;
|
||||
}
|
||||
long totalSize = 0L;
|
||||
List<Path> cacheDirs;
|
||||
try (Stream<Path> stream = Files.list(cacheRoot)) {
|
||||
cacheDirs = stream.filter(Files::isDirectory).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
for (Path dir : cacheDirs) {
|
||||
totalSize += getDirectorySize(dir);
|
||||
}
|
||||
|
||||
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
|
||||
|
||||
while (totalSize > maxCacheSizeBytes && !cacheDirs.isEmpty()) {
|
||||
Path leastRecentlyReadDir = cacheDirs.stream()
|
||||
.min(Comparator.comparingLong(this::getLastReadTime))
|
||||
.orElse(null);
|
||||
|
||||
long sizeFreed = getDirectorySize(leastRecentlyReadDir);
|
||||
FileUtils.deleteDirectoryRecursively(leastRecentlyReadDir);
|
||||
cacheDirs.remove(leastRecentlyReadDir);
|
||||
totalSize -= sizeFreed;
|
||||
log.info("Deleted cache directory {} to enforce cache size limit", leastRecentlyReadDir);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error enforcing cache size limit", e);
|
||||
}
|
||||
}
|
||||
|
||||
private long getLastReadTime(Path cacheDir) {
|
||||
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
|
||||
if (!Files.exists(cacheInfoPath)) {
|
||||
return Long.MIN_VALUE;
|
||||
}
|
||||
try {
|
||||
String content = Files.readString(cacheInfoPath).trim();
|
||||
return Long.parseLong(content);
|
||||
} catch (Exception e) {
|
||||
return Long.MIN_VALUE;
|
||||
}
|
||||
}
|
||||
|
||||
private long getDirectorySize(Path dir) {
|
||||
try (Stream<Path> paths = Files.walk(dir)) {
|
||||
return paths
|
||||
.filter(Files::isRegularFile)
|
||||
.mapToLong(p -> {
|
||||
try {
|
||||
return Files.size(p);
|
||||
} catch (IOException e) {
|
||||
return 0L;
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
} catch (IOException e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private long estimateArchiveSize(Path cbxPath) {
|
||||
try {
|
||||
String name = cbxPath.getFileName().toString().toLowerCase();
|
||||
if (name.endsWith(CBZ_EXTENSION)) {
|
||||
return estimateCbzArchiveSize(cbxPath);
|
||||
} else if (name.endsWith(CB7_EXTENSION)) {
|
||||
return estimateCb7ArchiveSize(cbxPath);
|
||||
} else if (name.endsWith(CBR_EXTENSION)) {
|
||||
return estimateCbrArchiveSize(cbxPath);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to estimate archive size for {}", cbxPath, e);
|
||||
}
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
private long estimateCbzArchiveSize(Path cbxPath) throws IOException {
|
||||
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(cbxPath))) {
|
||||
ZipEntry entry;
|
||||
long total = 0;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
||||
total += entry.getCompressedSize();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
|
||||
private long estimateCb7ArchiveSize(Path cbxPath) throws IOException {
|
||||
try (SevenZFile sevenZFile = new SevenZFile(cbxPath.toFile())) {
|
||||
SevenZArchiveEntry entry;
|
||||
long total = 0;
|
||||
while ((entry = sevenZFile.getNextEntry()) != null) {
|
||||
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
||||
total += entry.getSize();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
|
||||
private long estimateCbrArchiveSize(Path cbxPath) throws IOException, RarException {
|
||||
try (Archive archive = new Archive(cbxPath.toFile())) {
|
||||
long total = 0;
|
||||
for (FileHeader header : archive.getFileHeaders()) {
|
||||
if (!header.isDirectory() && isImageFile(header.getFileName())) {
|
||||
total += header.getFullUnpackSize();
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
|
||||
private long mbToBytes(int mb) {
|
||||
return mb * 1024L * 1024L;
|
||||
}
|
||||
}
|
||||
+7
-9
@@ -1,17 +1,13 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import io.documentnode.epub4j.domain.Author;
|
||||
import io.documentnode.epub4j.domain.Book;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
@@ -20,21 +16,23 @@ import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EpubMetadataExtractor implements BookFileMetadataExtractor {
|
||||
public class EpubMetadataExtractor implements UploadedFileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||
UploadedFileMetadata metadata = new UploadedFileMetadata();
|
||||
|
||||
try (FileInputStream fis = new FileInputStream(filePath)) {
|
||||
Book epubBook = new EpubReader().readEpub(fis);
|
||||
Book epub = new EpubReader().readEpub(fis);
|
||||
|
||||
String title = epubBook.getTitle();
|
||||
String title = epub.getTitle();
|
||||
if (title != null && !title.isBlank()) {
|
||||
metadata.setTitle(title);
|
||||
} else {
|
||||
metadata.setTitle(FilenameUtils.getBaseName(filePath));
|
||||
}
|
||||
|
||||
List<Author> epubAuthors = epubBook.getMetadata().getAuthors();
|
||||
List<Author> epubAuthors = epub.getMetadata().getAuthors();
|
||||
if (!epubAuthors.isEmpty()) {
|
||||
Set<String> authors = epubAuthors.stream()
|
||||
.map(author -> author.getFirstname() + " " + author.getLastname())
|
||||
|
||||
+38
-17
@@ -3,13 +3,13 @@ package com.adityachandel.booklore.service;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
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.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
@@ -31,21 +31,24 @@ import java.util.Optional;
|
||||
@Slf4j
|
||||
public class FileUploadService {
|
||||
|
||||
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;
|
||||
private static final String PDF_MIME_TYPE = "application/pdf";
|
||||
private static final String EPUB_MIME_TYPE = "application/epub+zip";
|
||||
private static final String CBZ_MIME_TYPE = "application/x-cbz";
|
||||
private static final String CBR_MIME_TYPE = "application/x-cbr";
|
||||
private static final String CB7_MIME_TYPE = "application/x-cb7";
|
||||
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final NotificationService notificationService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
|
||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
|
||||
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
validateFile(file);
|
||||
Integer uploadSizeInMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
|
||||
validateFile(file, uploadSizeInMb);
|
||||
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
@@ -62,18 +65,12 @@ public class FileUploadService {
|
||||
try {
|
||||
file.transferTo(tempPath);
|
||||
|
||||
String fileType = Objects.requireNonNull(file.getContentType());
|
||||
|
||||
if (fileType.equalsIgnoreCase(PDF_MIME_TYPE)) {
|
||||
metadata = pdfMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
} else if (fileType.equalsIgnoreCase(EPUB_MIME_TYPE)) {
|
||||
metadata = epubMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
} else {
|
||||
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
|
||||
}
|
||||
metadata = extractMetadata(file, tempPath);
|
||||
|
||||
String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim();
|
||||
String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : "";
|
||||
|
||||
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename());
|
||||
|
||||
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
|
||||
@@ -100,13 +97,35 @@ public class FileUploadService {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file) {
|
||||
private UploadedFileMetadata extractMetadata(MultipartFile file, Path tempPath) throws IOException {
|
||||
String fileType = Objects.requireNonNull(file.getContentType());
|
||||
return switch (fileType.toLowerCase()) {
|
||||
case PDF_MIME_TYPE -> pdfMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
case EPUB_MIME_TYPE -> epubMetadataExtractor.extractMetadata(tempPath.toString());
|
||||
case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> new UploadedFileMetadata();
|
||||
default -> throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
|
||||
};
|
||||
}
|
||||
|
||||
private boolean isSupportedContentType(String fileType) {
|
||||
return PDF_MIME_TYPE.equals(fileType)
|
||||
|| EPUB_MIME_TYPE.equals(fileType)
|
||||
|| CBZ_MIME_TYPE.equals(fileType)
|
||||
|| CBR_MIME_TYPE.equals(fileType)
|
||||
|| CB7_MIME_TYPE.equals(fileType);
|
||||
}
|
||||
|
||||
private boolean isFileTooLarge(MultipartFile file, int uploadSizeInMb) {
|
||||
return file.getSize() > uploadSizeInMb * 1024L * 1024L;
|
||||
}
|
||||
|
||||
private void validateFile(MultipartFile file, int uploadSizeInMb) {
|
||||
String fileType = file.getContentType();
|
||||
if (!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType)) {
|
||||
if (!isSupportedContentType(fileType)) {
|
||||
throw ApiError.INVALID_FILE_FORMAT.createException();
|
||||
}
|
||||
if (file.getSize() > MAX_FILE_SIZE) {
|
||||
throw ApiError.FILE_TOO_LARGE.createException();
|
||||
if (isFileTooLarge(file, uploadSizeInMb)) {
|
||||
throw ApiError.FILE_TOO_LARGE.createException(uploadSizeInMb);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +148,7 @@ public class FileUploadService {
|
||||
return switch (fileType) {
|
||||
case PDF -> pdfProcessor.processFile(libraryFile, false);
|
||||
case EPUB -> epubProcessor.processFile(libraryFile, false);
|
||||
case CBX -> cbxProcessor.processFile(libraryFile, false);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -160,6 +180,7 @@ public class FileUploadService {
|
||||
return switch (fileType.toLowerCase()) {
|
||||
case PDF_MIME_TYPE -> BookFileType.PDF;
|
||||
case EPUB_MIME_TYPE -> BookFileType.EPUB;
|
||||
case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> BookFileType.CBX;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
+140
-47
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
@@ -18,12 +19,15 @@ import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
@@ -37,8 +41,14 @@ public class LibraryProcessingService {
|
||||
private final NotificationService notificationService;
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final CbxProcessor cbxProcessor;
|
||||
private final BookRepository bookRepository;
|
||||
private final EntityManager entityManager;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
|
||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
private final Map<String, ScheduledFuture<?>> deletionTasks = new ConcurrentHashMap<>();
|
||||
private static final int DELETE_DEBOUNCE_SECONDS = 3;
|
||||
|
||||
@Transactional
|
||||
public void processLibrary(long libraryId) throws IOException {
|
||||
@@ -51,18 +61,34 @@ public class LibraryProcessingService {
|
||||
|
||||
@Transactional
|
||||
public void processFile(WatchEvent.Kind<?> eventKind, long libraryId, String libraryPath, String filePath) {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
Path path = Paths.get(filePath);
|
||||
String fileName = path.getFileName().toString();
|
||||
|
||||
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
|
||||
ScheduledFuture<?> scheduledDeletion = deletionTasks.remove(filePath);
|
||||
if (scheduledDeletion != null) {
|
||||
scheduledDeletion.cancel(false);
|
||||
log.debug("Cancelled scheduled deletion for file: {}", filePath);
|
||||
}
|
||||
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath));
|
||||
|
||||
LibraryPathEntity libraryPathEntity = getLibraryPathEntityForFile(libraryEntity, libraryPath);
|
||||
libraryPathEntity = entityManager.merge(libraryPathEntity);
|
||||
|
||||
LibraryPathEntity finalLibraryPathEntity = libraryPathEntity;
|
||||
bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.ifPresent(existingBook -> {
|
||||
Path newFullPath = path;
|
||||
Path oldFullPath = existingBook.getFullFilePath();
|
||||
if (!newFullPath.equals(oldFullPath)) {
|
||||
existingBook.setLibraryPath(finalLibraryPathEntity);
|
||||
existingBook.setFileSubPath(FileUtils.getRelativeSubPath(finalLibraryPathEntity.getPath(), newFullPath));
|
||||
bookRepository.save(existingBook);
|
||||
log.debug("Updated path for moved book: {}", fileName);
|
||||
}
|
||||
});
|
||||
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
.libraryPathEntity(libraryPathEntity)
|
||||
@@ -75,11 +101,33 @@ public class LibraryProcessingService {
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
|
||||
|
||||
} else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
|
||||
bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.ifPresent(bookEntity -> {
|
||||
deleteRemovedBooks(List.of(bookEntity));
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId()));
|
||||
});
|
||||
ScheduledFuture<?> scheduledDeletion = deletionTasks.putIfAbsent(filePath, scheduler.schedule(() -> {
|
||||
try {
|
||||
boolean fileStillExists = libraryEntity.getLibraryPaths().stream()
|
||||
.anyMatch(lp -> {
|
||||
Path fullPath = Path.of(lp.getPath()).resolve(fileName);
|
||||
return Files.exists(fullPath);
|
||||
});
|
||||
if (!fileStillExists) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.ifPresent(bookEntity -> {
|
||||
deleteRemovedBooks(List.of(bookEntity.getId()));
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(bookEntity.getId()));
|
||||
log.debug("Deleted book after debounce: {}", fileName);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
log.debug("File '{}' detected to still exist after debounce, skipping delete.", fileName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error during delayed deletion of file: {}", filePath, e);
|
||||
} finally {
|
||||
deletionTasks.remove(filePath);
|
||||
}
|
||||
}, DELETE_DEBOUNCE_SECONDS, TimeUnit.SECONDS));
|
||||
|
||||
// If scheduledDeletion != null, it means a task was already scheduled, so we skip scheduling again
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,8 +140,15 @@ public class LibraryProcessingService {
|
||||
|
||||
@Transactional
|
||||
protected BookFileType getBookFileType(String fileName) {
|
||||
if (fileName.endsWith(".pdf")) {
|
||||
String lowerCaseName = fileName.toLowerCase();
|
||||
if (lowerCaseName.endsWith(".pdf")) {
|
||||
return BookFileType.PDF;
|
||||
} else if (lowerCaseName.endsWith(".cbz")) {
|
||||
return BookFileType.CBX;
|
||||
} else if (lowerCaseName.endsWith(".cbr")) {
|
||||
return BookFileType.CBX;
|
||||
} else if (lowerCaseName.endsWith(".cb7")) {
|
||||
return BookFileType.CBX;
|
||||
} else {
|
||||
return BookFileType.EPUB;
|
||||
}
|
||||
@@ -103,19 +158,62 @@ public class LibraryProcessingService {
|
||||
public void rescanLibrary(long libraryId) throws IOException {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
|
||||
processLibraryFiles(getUnProcessedFiles(libraryEntity));
|
||||
deleteRemovedBooks(getRemovedBooks(libraryEntity));
|
||||
detectMovedBooksAndUpdatePaths(libraryEntity);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
deleteRemovedBooks(detectDeletedBookIds(libraryEntity));
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
processLibraryFiles(detectNewBookPaths(libraryEntity));
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
void detectMovedBooksAndUpdatePaths(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> currentLibraryFiles = getLibraryFiles(libraryEntity);
|
||||
Map<String, Path> currentFileMap = currentLibraryFiles.stream()
|
||||
.collect(Collectors.toMap(LibraryFile::getFileName, LibraryFile::getFullPath, (existing, replacement) -> existing));
|
||||
for (BookEntity book : libraryEntity.getBookEntities()) {
|
||||
Path existingPath = book.getFullFilePath();
|
||||
Path updatedPath = currentFileMap.get(book.getFileName());
|
||||
if (updatedPath != null && !updatedPath.equals(existingPath)) {
|
||||
log.info("Detected moved book: '{}' from '{}' to '{}'", book.getFileName(), existingPath, updatedPath);
|
||||
libraryEntity.getLibraryPaths().stream()
|
||||
.filter(lp -> updatedPath.startsWith(Path.of(lp.getPath())))
|
||||
.findFirst()
|
||||
.ifPresent(matchingPath -> {
|
||||
book.setLibraryPath(matchingPath);
|
||||
book.setFileSubPath(FileUtils.getRelativeSubPath(matchingPath.getPath(), updatedPath));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<Long> detectDeletedBookIds(LibraryEntity libraryEntity) throws IOException {
|
||||
Set<String> currentFileNames = getLibraryFiles(libraryEntity).stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
return libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> !currentFileNames.contains(book.getFileName()))
|
||||
.map(BookEntity::getId)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<LibraryFile> detectNewBookPaths(LibraryEntity libraryEntity) throws IOException {
|
||||
Set<String> existingFileNames = libraryEntity.getBookEntities().stream()
|
||||
.map(BookEntity::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
return getLibraryFiles(libraryEntity).stream()
|
||||
.filter(file -> !existingFileNames.contains(file.getFileName()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void deleteRemovedBooks(List<BookEntity> removedBookEntities) {
|
||||
if (!removedBookEntities.isEmpty()) {
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
Set<Long> bookIds = removedBookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
bookRepository.deleteByIdIn(bookIds);
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
|
||||
protected void deleteRemovedBooks(List<Long> bookIds) {
|
||||
bookRepository.deleteByIdIn(bookIds);
|
||||
notificationService.sendMessage(Topic.BOOKS_REMOVE, bookIds);
|
||||
if (bookIds.size() > 1) {
|
||||
log.info("Books removed: {}", bookIds);
|
||||
}
|
||||
}
|
||||
@@ -139,34 +237,12 @@ public class LibraryProcessingService {
|
||||
return pdfProcessor.processFile(libraryFile, false);
|
||||
} else if (libraryFile.getBookFileType() == BookFileType.EPUB) {
|
||||
return epubProcessor.processFile(libraryFile, false);
|
||||
} else if (libraryFile.getBookFileType() == BookFileType.CBX) {
|
||||
return cbxProcessor.processFile(libraryFile, false);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<BookEntity> getRemovedBooks(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
|
||||
List<BookEntity> bookEntities = libraryEntity.getBookEntities();
|
||||
Set<String> libraryFilePaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
return bookEntities.stream()
|
||||
.filter(book -> !libraryFilePaths.contains(book.getFileName()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<LibraryFile> getUnProcessedFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
|
||||
List<BookEntity> bookEntities = libraryEntity.getBookEntities();
|
||||
Set<String> processedPaths = bookEntities.stream()
|
||||
.map(BookEntity::getFileName)
|
||||
.collect(Collectors.toSet());
|
||||
return libraryFiles.stream()
|
||||
.filter(libraryFile -> !processedPaths.contains(libraryFile.getFileName()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(LibraryEntity libraryEntity) throws IOException {
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
for (LibraryPathEntity libraryPathEntity : libraryEntity.getLibraryPaths()) {
|
||||
@@ -182,12 +258,29 @@ public class LibraryProcessingService {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.filter(file -> {
|
||||
String fileName = file.getFileName().toString().toLowerCase();
|
||||
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
|
||||
return fileName.endsWith(".pdf") ||
|
||||
fileName.endsWith(".epub") ||
|
||||
fileName.endsWith(".cbz") ||
|
||||
fileName.endsWith(".cbr") ||
|
||||
fileName.endsWith(".cb7");
|
||||
})
|
||||
.forEach(fullFilePath -> {
|
||||
BookFileType fileType = fullFilePath.getFileName().toString().toLowerCase().endsWith(".pdf")
|
||||
? BookFileType.PDF
|
||||
: BookFileType.EPUB;
|
||||
String fileName = fullFilePath.getFileName().toString().toLowerCase();
|
||||
BookFileType fileType;
|
||||
if (fileName.endsWith(".pdf")) {
|
||||
fileType = BookFileType.PDF;
|
||||
} else if (fileName.endsWith(".epub")) {
|
||||
fileType = BookFileType.EPUB;
|
||||
} else if (fileName.endsWith(".cbz")) {
|
||||
fileType = BookFileType.CBX;
|
||||
} else if (fileName.endsWith(".cbr")) {
|
||||
fileType = BookFileType.CBX;
|
||||
} else if (fileName.endsWith(".cb7")) {
|
||||
fileType = BookFileType.CBX;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
String relativePath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), fullFilePath);
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.libraryEntity(libraryEntity)
|
||||
|
||||
+4
-1
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
|
||||
@@ -13,7 +14,7 @@ import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PdfMetadataExtractor implements BookFileMetadataExtractor {
|
||||
public class PdfMetadataExtractor implements UploadedFileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public UploadedFileMetadata extractMetadata(String filePath) {
|
||||
@@ -24,6 +25,8 @@ public class PdfMetadataExtractor implements BookFileMetadataExtractor {
|
||||
if (info != null) {
|
||||
if (info.getTitle() != null && !info.getTitle().isBlank()) {
|
||||
metadata.setTitle(info.getTitle());
|
||||
} else {
|
||||
metadata.setTitle(FilenameUtils.getBaseName(filePath));
|
||||
}
|
||||
if (info.getAuthor() != null && !info.getAuthor().isBlank()) {
|
||||
metadata.setAuthors(Set.of(info.getAuthor().split(",")));
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.UploadedFileMetadata;
|
||||
|
||||
public interface BookFileMetadataExtractor {
|
||||
public interface UploadedFileMetadataExtractor {
|
||||
|
||||
UploadedFileMetadata extractMetadata(String filePath);
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class CbxProcessor implements FileProcessor {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final BookCreatorService bookCreatorService;
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
public Book processFile(LibraryFile libraryFile, boolean forceProcess) {
|
||||
File bookFile = new File(libraryFile.getFileName());
|
||||
String fileName = bookFile.getName();
|
||||
if (!forceProcess) {
|
||||
Optional<BookEntity> bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
|
||||
return bookOptional.map(bookMapper::toBook).orElseGet(() -> processNewFile(libraryFile));
|
||||
} else {
|
||||
return processNewFile(libraryFile);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
protected Book processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookEntity = bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
return bookMapper.toBook(bookEntity);
|
||||
}
|
||||
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
File file = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
try {
|
||||
Optional<BufferedImage> imageOptional = extractImagesFromArchive(file);
|
||||
if (imageOptional.isPresent()) {
|
||||
BufferedImage firstImage = imageOptional.get();
|
||||
boolean saved = fileProcessingUtils.saveCoverImage(firstImage, bookEntity.getId());
|
||||
if (saved) {
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover from archive {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractImagesFromArchive(File file) {
|
||||
String name = file.getName().toLowerCase();
|
||||
if (name.endsWith(".cbz")) {
|
||||
return extractFirstImageFromZip(file);
|
||||
} else if (name.endsWith(".cb7")) {
|
||||
return extractFirstImageFrom7z(file);
|
||||
} else if (name.endsWith(".cbr")) {
|
||||
return extractFirstImageFromRar(file);
|
||||
} else {
|
||||
log.warn("Unsupported archive format: {}", name);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFromRar(File file) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
List<FileHeader> headers = archive.getFileHeaders();
|
||||
List<FileHeader> imageHeaders = headers.stream()
|
||||
.filter(h -> !h.isDirectory())
|
||||
.filter(h -> {
|
||||
String fileName = h.getFileNameString().replace("\\", "/").toLowerCase();
|
||||
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".webp");
|
||||
})
|
||||
.sorted(Comparator.comparing(FileHeader::getFileNameString))
|
||||
.toList();
|
||||
|
||||
for (FileHeader header : imageHeaders) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
archive.extractFile(header, baos);
|
||||
byte[] imageData = baos.toByteArray();
|
||||
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
|
||||
if (img != null) {
|
||||
return Optional.of(img);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error extracting image from RAR archive {}: {}", file.getName(), e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
return Collections.list(zipFile.getEntries()).stream()
|
||||
.filter(e -> !e.isDirectory())
|
||||
.filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)"))
|
||||
.min(Comparator.comparing(ZipArchiveEntry::getName))
|
||||
.map(entry -> {
|
||||
try (InputStream is = zipFile.getInputStream(entry)) {
|
||||
return ImageIO.read(is);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.error("Error extracting image from ZIP archive {}: {}", file.getName(), e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFrom7z(File file) {
|
||||
try (SevenZFile sevenZFile = new SevenZFile(file)) {
|
||||
List<SevenZArchiveEntry> imageEntries = new ArrayList<>();
|
||||
SevenZArchiveEntry entry;
|
||||
while ((entry = sevenZFile.getNextEntry()) != null) {
|
||||
if (!entry.isDirectory() && entry.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) {
|
||||
imageEntries.add(entry);
|
||||
}
|
||||
}
|
||||
imageEntries.sort(Comparator.comparing(SevenZArchiveEntry::getName));
|
||||
sevenZFile.close();
|
||||
|
||||
try (SevenZFile sevenZFileReset = new SevenZFile(file)) {
|
||||
for (SevenZArchiveEntry imgEntry : imageEntries) {
|
||||
SevenZArchiveEntry currentEntry;
|
||||
while ((currentEntry = sevenZFileReset.getNextEntry()) != null) {
|
||||
if (currentEntry.equals(imgEntry)) {
|
||||
byte[] content = new byte[(int) currentEntry.getSize()];
|
||||
int offset = 0;
|
||||
while (offset < content.length) {
|
||||
int bytesRead = sevenZFileReset.read(content, offset, content.length - offset);
|
||||
if (bytesRead < 0) {
|
||||
break;
|
||||
}
|
||||
offset += bytesRead;
|
||||
}
|
||||
BufferedImage img = ImageIO.read(new ByteArrayInputStream(content));
|
||||
if (img != null) {
|
||||
return Optional.of(img);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
} catch (Exception e) {
|
||||
log.error("Error extracting image from 7z archive {}: {}", file.getName(), e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private void setMetadata(BookEntity bookEntity) {
|
||||
String baseName = new File(bookEntity.getFileName()).getName();
|
||||
String title = baseName.replaceAll("(?i)\\.cb[sz7]$", "").replaceAll("[_\\-]", " ").trim();
|
||||
bookEntity.getMetadata().setTitle(truncate(title, 1000));
|
||||
}
|
||||
|
||||
private String truncate(String input, int maxLength) {
|
||||
if (input == null) return null;
|
||||
return input.length() <= maxLength ? input : input.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
+148
-25
@@ -1,8 +1,37 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
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;
|
||||
@@ -10,30 +39,15 @@ import com.adityachandel.booklore.repository.BookMetadataRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.BookCreatorService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import io.documentnode.epub4j.domain.Identifier;
|
||||
import io.documentnode.epub4j.domain.Metadata;
|
||||
import io.documentnode.epub4j.domain.Resource;
|
||||
import io.documentnode.epub4j.epub.EpubReader;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import net.lingala.zip4j.ZipFile;
|
||||
import net.lingala.zip4j.model.FileHeader;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -117,10 +131,16 @@ public class EpubProcessor implements FileProcessor {
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
try {
|
||||
io.documentnode.epub4j.domain.Book book = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
|
||||
log.debug("***Setting metadata for book {}", bookEntity.getFileName());
|
||||
try (FileInputStream fis =
|
||||
new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
|
||||
|
||||
io.documentnode.epub4j.domain.Book book =
|
||||
new EpubReader().readEpub(fis);
|
||||
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
|
||||
if (epubMetadata != null) {
|
||||
bookMetadata.setTitle(truncate(epubMetadata.getFirstTitle(), 1000));
|
||||
|
||||
@@ -134,12 +154,36 @@ public class EpubProcessor implements FileProcessor {
|
||||
|
||||
List<String> identifiers = epubMetadata.getIdentifiers().stream()
|
||||
.map(Identifier::getValue)
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.map(id -> id.contains(":") ? id.substring(id.indexOf(":") + 1) : id) // strip prefix
|
||||
.map(id -> id.replace("-", "")) // remove dashes
|
||||
.toList();
|
||||
|
||||
|
||||
if (!identifiers.isEmpty()) {
|
||||
String isbn13 = identifiers.stream().filter(id -> id.length() == 13).findFirst().orElse(null);
|
||||
String isbn10 = identifiers.stream().filter(id -> id.length() == 10).findFirst().orElse(null);
|
||||
// Checking for ISBN 13 (strict 13-digit numeric)
|
||||
String isbn13 = identifiers.stream()
|
||||
.filter(id -> id.length() == 13 && id.matches("\\d{13}"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
// Checking for ISBN 10 (strict 10-digit format or ends in X)
|
||||
String isbn10 = identifiers.stream()
|
||||
.filter(id -> id.length() == 10 && id.matches("\\d{9}[\\dXx]"))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
// Checking for ASIN (alphanumeric 10 chars, must not be ISBN-10)
|
||||
String asin = identifiers.stream()
|
||||
.filter(id -> id.length() == 10 && id.matches("^[A-Z0-9]{10}$"))
|
||||
.filter(id -> !id.equalsIgnoreCase(isbn10))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
bookMetadata.setIsbn13(truncate(isbn13, 64));
|
||||
bookMetadata.setIsbn10(truncate(isbn10, 64));
|
||||
bookMetadata.setAsin(truncate(asin, 20));
|
||||
}
|
||||
|
||||
bookMetadata.setLanguage(truncate(
|
||||
@@ -162,7 +206,8 @@ public class EpubProcessor implements FileProcessor {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Calibre (EPUB2) series tags
|
||||
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
|
||||
if (seriesName != null && !seriesName.isEmpty()) {
|
||||
bookMetadata.setSeriesName(truncate(seriesName, 1000));
|
||||
@@ -178,6 +223,9 @@ public class EpubProcessor implements FileProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
// fall-back to OPF for anything still missing
|
||||
extractFromOpf(FileUtils.getBookFullPath(bookEntity), bookMetadata);
|
||||
|
||||
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
|
||||
bookCreatorService.addCategoriesToBook(epubMetadata.getSubjects(), bookEntity);
|
||||
}
|
||||
@@ -213,4 +261,79 @@ public class EpubProcessor implements FileProcessor {
|
||||
if (input == null) return null;
|
||||
return input.length() <= maxLength ? input : input.substring(0, maxLength);
|
||||
}
|
||||
|
||||
private void extractFromOpf(String epubPath, BookMetadataEntity meta) {
|
||||
try (ZipFile zip = new ZipFile(epubPath)) {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
dbf.setNamespaceAware(true);
|
||||
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
DocumentBuilder builder = dbf.newDocumentBuilder();
|
||||
|
||||
FileHeader containerHdr = zip.getFileHeader("META-INF/container.xml");
|
||||
if (containerHdr == null) return;
|
||||
try (InputStream cis = zip.getInputStream(containerHdr)) {
|
||||
Document containerDoc;
|
||||
try {
|
||||
containerDoc = builder.parse(cis);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
if (containerDoc == null) return;
|
||||
NodeList roots = containerDoc.getElementsByTagName("rootfile");
|
||||
if (roots.getLength() == 0) return;
|
||||
String opfPath = ((Element) roots.item(0)).getAttribute("full-path");
|
||||
if (StringUtils.isBlank(opfPath)) return;
|
||||
FileHeader opfHdr = zip.getFileHeader(opfPath);
|
||||
if (opfHdr == null) return;
|
||||
try (InputStream in = zip.getInputStream(opfHdr)) {
|
||||
Document doc;
|
||||
try {
|
||||
doc = builder.parse(in);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
if (doc == null) return;
|
||||
if (StringUtils.isBlank(meta.getIsbn13()) || StringUtils.isBlank(meta.getIsbn10())) {
|
||||
NodeList idNodes = doc.getElementsByTagNameNS("*", "identifier");
|
||||
for (int i = 0; i < idNodes.getLength(); i++) {
|
||||
String idRaw = idNodes.item(i).getTextContent().trim();
|
||||
String isbn = idRaw.toLowerCase().startsWith("isbn:") ? idRaw.substring(5) : idRaw;
|
||||
if (isbn.length() == 13 && StringUtils.isBlank(meta.getIsbn13())) {
|
||||
meta.setIsbn13(truncate(isbn, 64));
|
||||
}
|
||||
if (isbn.length() == 10 && StringUtils.isBlank(meta.getIsbn10())) {
|
||||
meta.setIsbn10(truncate(isbn, 64));
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeList metaNodes = doc.getElementsByTagNameNS("*", "meta");
|
||||
for (int i = 0; i < metaNodes.getLength(); i++) {
|
||||
Element m = (Element) metaNodes.item(i);
|
||||
String nameAttr = m.getAttribute("name");
|
||||
String propAttr = m.getAttribute("property");
|
||||
String content = m.hasAttribute("content") ? m.getAttribute("content").trim() : m.getTextContent().trim();
|
||||
|
||||
if (StringUtils.isBlank(meta.getSeriesName()) && (nameAttr.equalsIgnoreCase("calibre:series") || propAttr.equalsIgnoreCase("belongs-to-collection"))) {
|
||||
meta.setSeriesName(truncate(content, 1000));
|
||||
}
|
||||
if (meta.getSeriesNumber() == null && (nameAttr.equalsIgnoreCase("calibre:series_index") || propAttr.equalsIgnoreCase("group-position"))) {
|
||||
try {
|
||||
int number = (int) Double.parseDouble(content);
|
||||
meta.setSeriesNumber((float) number);
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
if (meta.getPageCount() == null && (nameAttr.equalsIgnoreCase("calibre:pages") || nameAttr.equalsIgnoreCase("pageCount") || propAttr.equalsIgnoreCase("schema:pageCount") || propAttr.equalsIgnoreCase("media:pageCount"))) {
|
||||
try {
|
||||
int pages = Integer.parseInt(content);
|
||||
meta.setPageCount(pages);
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
-41
@@ -91,23 +91,17 @@ public class AmazonBookParser implements BookParser {
|
||||
Element link = item.select("a:containsOwn(" + type + ")").first();
|
||||
if (link != null) {
|
||||
bookLink = link.attr("href");
|
||||
//log.info("{} link found: {}", type, bookLink);
|
||||
break; // Take the first found link, whether Paperback or Hardcover
|
||||
} else {
|
||||
//log.info("No link containing '{}' found.", type);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (bookLink != null) {
|
||||
return extractAsinFromUrl(bookLink);
|
||||
} else {
|
||||
String asin = item.attr("data-asin");
|
||||
//log.info("No book link found, returning ASIN: {}", asin);
|
||||
return asin;
|
||||
return item.attr("data-asin");
|
||||
}
|
||||
}
|
||||
|
||||
private String extractAsinFromUrl(String url) {
|
||||
// Extract the ASIN (book ID) from the URL, which will be the part after "/dp/"
|
||||
String[] parts = url.split("/dp/");
|
||||
if (parts.length > 1) {
|
||||
String[] asinParts = parts[1].split("/");
|
||||
@@ -132,6 +126,7 @@ public class AmazonBookParser implements BookParser {
|
||||
.seriesTotal(getSeriesTotal(doc))
|
||||
.isbn13(getIsbn13(doc))
|
||||
.isbn10(getIsbn10(doc))
|
||||
.asin(amazonBookId)
|
||||
.publisher(getPublisher(doc))
|
||||
.publishedDate(getPublicationDate(doc))
|
||||
.language(getLanguage(doc))
|
||||
@@ -184,7 +179,7 @@ public class AmazonBookParser implements BookParser {
|
||||
if (titleElement != null) {
|
||||
return titleElement.text();
|
||||
}
|
||||
log.error("Error fetching title: Element not found.");
|
||||
log.warn("Failed to parse title: Element not found.");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -193,7 +188,7 @@ public class AmazonBookParser implements BookParser {
|
||||
if (subtitleElement != null) {
|
||||
return subtitleElement.text();
|
||||
}
|
||||
log.debug("Error fetching subtitle: Element not found.");
|
||||
log.warn("Failed to parse subtitle: Element not found.");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -207,9 +202,9 @@ public class AmazonBookParser implements BookParser {
|
||||
.map(Element::text)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
log.error("Error fetching authors: Byline element not found.");
|
||||
log.warn("Failed to parse authors: Byline element not found.");
|
||||
} catch (Exception e) {
|
||||
log.error("Error fetching authors: {}", e.getMessage());
|
||||
log.warn("Failed to parse authors: {}", e.getMessage());
|
||||
}
|
||||
return Set.of();
|
||||
}
|
||||
@@ -224,7 +219,7 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Error extracting description from the document", e);
|
||||
log.warn("Failed to parse description: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -235,9 +230,9 @@ public class AmazonBookParser implements BookParser {
|
||||
if (isbn10Element != null) {
|
||||
return isbn10Element.text();
|
||||
}
|
||||
log.debug("Error fetching ISBN-10: Element not found.");
|
||||
log.warn("Failed to parse isbn10: Element not found.");
|
||||
} catch (Exception e) {
|
||||
log.debug("Error fetching ISBN-10: {}", e.getMessage());
|
||||
log.warn("Failed to parse isbn10: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -248,9 +243,9 @@ public class AmazonBookParser implements BookParser {
|
||||
if (isbn13Element != null) {
|
||||
return isbn13Element.text();
|
||||
}
|
||||
log.debug("Error fetching ISBN-13: Element not found.");
|
||||
log.warn("Failed to parse isbn13: Element not found.");
|
||||
} catch (Exception e) {
|
||||
log.debug("Error fetching ISBN-13: {}", e.getMessage());
|
||||
log.warn("Failed to parse isbn13: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -271,10 +266,10 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.warn("Error fetching publisher: Element 'detailBullets_feature_div' not found.");
|
||||
log.warn("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching publisher: {}", e.getMessage());
|
||||
log.warn("Failed to parse publisher: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -285,9 +280,9 @@ public class AmazonBookParser implements BookParser {
|
||||
if (publicationDateElement != null) {
|
||||
return parseAmazonDate(publicationDateElement.text());
|
||||
}
|
||||
log.warn("Error fetching publication date: Element not found.");
|
||||
log.warn("Failed to parse publishedDate: Element not found.");
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching publication date: {}", e.getMessage());
|
||||
log.warn("Failed to parse publishedDate: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -298,10 +293,10 @@ public class AmazonBookParser implements BookParser {
|
||||
if (seriesNameElement != null) {
|
||||
return seriesNameElement.text();
|
||||
} else {
|
||||
log.debug("Error fetching series name: Element not found.");
|
||||
log.warn("Failed to parse seriesName: Element not found.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Error fetching series name: {}", e.getMessage());
|
||||
log.warn("Failed to parse seriesName: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -316,10 +311,10 @@ public class AmazonBookParser implements BookParser {
|
||||
return Float.parseFloat(parts[1]);
|
||||
}
|
||||
} else {
|
||||
log.debug("Error fetching series number: Element not found.");
|
||||
log.warn("Failed to parse seriesNumber: Element not found.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Error fetching series number: {}", e.getMessage());
|
||||
log.warn("Failed to parse seriesNumber: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -334,10 +329,10 @@ public class AmazonBookParser implements BookParser {
|
||||
return Integer.parseInt(parts[3]);
|
||||
}
|
||||
} else {
|
||||
log.debug("Error fetching series total: Element not found.");
|
||||
log.warn("Failed to parse seriesTotal: Element not found.");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Error fetching series total: {}", e.getMessage());
|
||||
log.warn("Failed to parse seriesTotal: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -348,9 +343,9 @@ public class AmazonBookParser implements BookParser {
|
||||
if (languageElement != null) {
|
||||
return languageElement.text();
|
||||
}
|
||||
log.warn("Error fetching language: Element not found.");
|
||||
log.warn("Failed to parse language: Element not found.");
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching language: {}", e.getMessage());
|
||||
log.warn("Failed to parse language: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -366,9 +361,9 @@ public class AmazonBookParser implements BookParser {
|
||||
.map(c -> c.replace("(Books)", "").trim())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
log.warn("Error fetching best seller categories: Element not found.");
|
||||
log.warn("Failed to parse categories: Element not found.");
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching best seller categories: {}", e.getMessage());
|
||||
log.warn("Failed to parse categories: {}", e.getMessage());
|
||||
}
|
||||
return Set.of();
|
||||
}
|
||||
@@ -386,7 +381,7 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching rating", e);
|
||||
log.warn("Failed to parse amazonRating: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -405,7 +400,7 @@ public class AmazonBookParser implements BookParser {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching review count", e);
|
||||
log.warn("Failed to parse amazonReviewCount: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -416,9 +411,9 @@ public class AmazonBookParser implements BookParser {
|
||||
if (imageElement != null) {
|
||||
return imageElement.attr("src");
|
||||
}
|
||||
log.warn("Error fetching image URL: Image element not found.");
|
||||
log.warn("Failed to parse thumbnail: Image element not found.");
|
||||
} catch (Exception e) {
|
||||
log.warn("Error fetching image URL: {}", e.getMessage());
|
||||
log.warn("Failed to parse thumbnail: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -432,7 +427,7 @@ public class AmazonBookParser implements BookParser {
|
||||
String cleanedPageCount = pageCountText.replaceAll("[^\\d]", "");
|
||||
return Integer.parseInt(cleanedPageCount);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Error parsing page count: {}", pageCountText, e);
|
||||
log.warn("Error parsing page count: {}, error: {}", pageCountText, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,7 +480,7 @@ public class AmazonBookParser implements BookParser {
|
||||
document.select("span.a-text-bold").tagName("b").removeAttr("class");
|
||||
document.select("span.a-text-italic").tagName("i").removeAttr("class");
|
||||
for (Element span : document.select("span.a-list-item")) {
|
||||
span.unwrap(); // Removes the span and keeps its content
|
||||
span.unwrap();
|
||||
}
|
||||
document.select("ol.a-ordered-list.a-vertical").tagName("ol").removeAttr("class");
|
||||
document.select("ul.a-unordered-list.a-vertical").tagName("ul").removeAttr("class");
|
||||
@@ -493,13 +488,10 @@ public class AmazonBookParser implements BookParser {
|
||||
span.unwrap();
|
||||
}
|
||||
document.select("li").forEach(li -> {
|
||||
// Remove <br> tags preceding the <li> (if any)
|
||||
Element prev = li.previousElementSibling();
|
||||
if (prev != null && "br".equals(prev.tagName())) {
|
||||
prev.remove();
|
||||
}
|
||||
|
||||
// Remove <br> tags following the <li> (if any)
|
||||
Element next = li.nextElementSibling();
|
||||
if (next != null && "br".equals(next.tagName())) {
|
||||
next.remove();
|
||||
@@ -510,7 +502,7 @@ public class AmazonBookParser implements BookParser {
|
||||
.forEach(Element::remove);
|
||||
return document.body().html();
|
||||
} catch (Exception e) {
|
||||
log.warn("Error cleaning html description", e);
|
||||
log.warn("Error cleaning html description, Error: {}", e.getMessage());
|
||||
}
|
||||
return html;
|
||||
}
|
||||
|
||||
+2
-3
@@ -84,7 +84,7 @@ public class MonitoringService {
|
||||
if (!eventQueue.offer(event)) {
|
||||
log.warn("Event queue is full, dropping event: {}", event.getFilePath());
|
||||
} else {
|
||||
log.info("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size());
|
||||
log.debug("Queued file change event: {} ({} in queue)", event.getFilePath(), eventQueue.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,8 +113,7 @@ public class MonitoringService {
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
}
|
||||
log.info("Processed file change event for library {}: {} (from folder: {}) with kind: {}",
|
||||
libraryId, filePath, watchedFolder, event.getEventKind());
|
||||
log.debug("Processed file change event for library {}: {} (from folder: {}) with kind: {}", libraryId, filePath, watchedFolder, event.getEventKind());
|
||||
} else {
|
||||
log.warn("No libraryId found for watched folder: {}", watchedFolder);
|
||||
}
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class MonitoringTask {
|
||||
Path fullPath = directory.resolve(fileName);
|
||||
|
||||
if (isPdfOrEpub(fileName) && (kind == StandardWatchEventKinds.ENTRY_CREATE || kind == StandardWatchEventKinds.ENTRY_DELETE)) {
|
||||
log.info("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory);
|
||||
log.debug("Event kind: {}; File affected: {}; Full path: {}; Watched folder: {}", kind, fileName, fullPath, directory);
|
||||
eventPublisher.publishEvent(new FileChangeEvent(this, fullPath, kind, directory));
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -9,6 +9,8 @@ import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
||||
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
|
||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
@@ -179,6 +181,7 @@ public class UserProvisioningService {
|
||||
addUserSetting(user, UserSettingKey.PER_BOOK_SETTING, buildDefaultPerBookSetting());
|
||||
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
|
||||
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
|
||||
addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultCbxReaderSetting());
|
||||
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
|
||||
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
|
||||
|
||||
@@ -203,6 +206,7 @@ public class UserProvisioningService {
|
||||
return BookLoreUser.UserSettings.PerBookSetting.builder()
|
||||
.epub(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
|
||||
.pdf(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
|
||||
.cbx(BookLoreUser.UserSettings.PerBookSetting.GlobalOrIndividual.Individual)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -222,6 +226,13 @@ public class UserProvisioningService {
|
||||
.build();
|
||||
}
|
||||
|
||||
public BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
|
||||
return BookLoreUser.UserSettings.CbxReaderSetting.builder()
|
||||
.pageViewMode(CbxPageViewMode.SINGLE_PAGE)
|
||||
.pageSpread(CbxPageSpread.ODD)
|
||||
.build();
|
||||
}
|
||||
|
||||
private Object buildDefaultSidebarLibrarySorting() {
|
||||
return SidebarSortOption.builder()
|
||||
.field("id")
|
||||
|
||||
@@ -118,6 +118,10 @@ public class FileService {
|
||||
return appProperties.getPathConfig() + "/thumbs/" + bookId + "/";
|
||||
}
|
||||
|
||||
public String getCbxCachePath() {
|
||||
return appProperties.getPathConfig() + "/cbx_cache";
|
||||
}
|
||||
|
||||
public String getMissingThumbnailPath() {
|
||||
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@ package com.adityachandel.booklore.util;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Comparator;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
@@ -14,7 +16,10 @@ public class FileUtils {
|
||||
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
|
||||
|
||||
public static String getBookFullPath(BookEntity bookEntity) {
|
||||
return String.format("%s/%s/%s", bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName());
|
||||
return Path.of(bookEntity.getLibraryPath().getPath(), bookEntity.getFileSubPath(), bookEntity.getFileName())
|
||||
.normalize()
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
}
|
||||
|
||||
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
|
||||
@@ -42,4 +47,14 @@ public class FileUtils {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteDirectoryRecursively(Path path) throws IOException {
|
||||
if (!Files.exists(path)) return;
|
||||
|
||||
try (var walk = Files.walk(path)) {
|
||||
walk.sorted(Comparator.reverseOrder())
|
||||
.map(Path::toFile)
|
||||
.forEach(File::delete);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,7 @@ app:
|
||||
spring:
|
||||
servlet:
|
||||
multipart:
|
||||
enabled: true
|
||||
max-file-size: 100MB
|
||||
max-request-size: 100MB
|
||||
enabled: false
|
||||
mvc:
|
||||
async:
|
||||
request-timeout: 600000
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS cbx_viewer_preference
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
spread VARCHAR(16) NULL,
|
||||
view_mode VARCHAR(16) NULL,
|
||||
UNIQUE (user_id, book_id)
|
||||
);
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE user_book_progress
|
||||
ADD COLUMN cbx_progress INT NULL,
|
||||
ADD COLUMN cbx_progress_percent FLOAT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE book_metadata ADD COLUMN asin VARCHAR(20);
|
||||
ALTER TABLE book_metadata ADD COLUMN asin_locked BOOLEAN DEFAULT FALSE;
|
||||
@@ -15,6 +15,7 @@ import {SetupRedirectGuard} from './core/setup/setup-redirect.guard';
|
||||
import {EmptyComponent} from './core/empty/empty.component';
|
||||
import {LoginGuard} from './core/setup/ login.guard';
|
||||
import {OidcCallbackComponent} from './core/security/oidc-callback/oidc-callback.component';
|
||||
import {CbxReaderComponent} from './book/components/cbx-reader/cbx-reader.component';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -52,6 +53,11 @@ export const routes: Routes = [
|
||||
component: EpubViewerComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'cbx-viewer/book/:bookId',
|
||||
component: CbxReaderComponent,
|
||||
canActivate: [AuthGuard]
|
||||
},
|
||||
{
|
||||
path: 'login',
|
||||
component: LoginComponent,
|
||||
|
||||
@@ -61,19 +61,22 @@
|
||||
|
||||
<p-fluid>
|
||||
<div class="relative">
|
||||
<i class="pi pi-search search-icon"></i>
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
placeholder="Search title or author..."
|
||||
placeholder="Title, Series or Author..."
|
||||
[(ngModel)]="bookTitle"
|
||||
(ngModelChange)="onBookTitleChange($event)"/>
|
||||
(ngModelChange)="onSearchTermChange($event)"
|
||||
class="search-input"
|
||||
/>
|
||||
<p-button
|
||||
*ngIf="bookTitle"
|
||||
icon="pi pi-times"
|
||||
[text]="true"
|
||||
size="small"
|
||||
[rounded]="true"
|
||||
class="absolute right-2 top-1/2 transform -translate-y-1/2"
|
||||
class="absolute right-2 top-1/2 -translate-y-1/2"
|
||||
(click)="clearSearch()">
|
||||
</p-button>
|
||||
</div>
|
||||
|
||||
@@ -85,3 +85,21 @@
|
||||
font-weight: 100;
|
||||
}
|
||||
}
|
||||
|
||||
.search-icon {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 10px;
|
||||
transform: translateY(-50%);
|
||||
color: var(--text-color-secondary);
|
||||
font-size: 1.0rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
width: 100%;
|
||||
padding-left: 30px;
|
||||
height: 2.5rem;
|
||||
line-height: 2.5rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
bookState$: Observable<BookState> | undefined;
|
||||
entity$: Observable<Library | Shelf | null> | undefined;
|
||||
entityType$: Observable<EntityType> | undefined;
|
||||
bookOrAuthor$ = new BehaviorSubject<string>('');
|
||||
searchTerm$ = new BehaviorSubject<string>('');
|
||||
|
||||
entity: Library | Shelf | null = null;
|
||||
entityType: EntityType | undefined;
|
||||
@@ -115,6 +115,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
|
||||
sortOptions: any[] = [
|
||||
{label: 'Title', icon: '', field: 'title', command: () => this.sortBooks('title')},
|
||||
{label: 'Title + Series', icon: '', field: 'titleSeries', command: () => this.sortBooks('titleSeries')},
|
||||
{label: 'Author', icon: '', field: 'author', command: () => this.sortBooks('author')},
|
||||
{label: 'Last Read', field: 'lastReadTime', command: () => this.sortBooks('lastReadTime')},
|
||||
{label: 'Added On', field: 'addedOn', command: () => this.sortBooks('addedOn')},
|
||||
@@ -177,7 +178,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
|
||||
this.activatedRoute.paramMap.subscribe(() => {
|
||||
this.bookOrAuthor$.next('');
|
||||
this.searchTerm$.next('');
|
||||
this.bookTitle = '';
|
||||
this.deselectAllBooks();
|
||||
this.clearFilter();
|
||||
@@ -311,15 +312,16 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
|
||||
private headerFilter(bookState: BookState): Observable<BookState> {
|
||||
return this.bookOrAuthor$.pipe(
|
||||
map(title => {
|
||||
if (title && title.trim() !== '') {
|
||||
return this.searchTerm$.pipe(
|
||||
map(term => {
|
||||
if (term && term.trim() !== '') {
|
||||
const filteredBooks = bookState.books?.filter(book => {
|
||||
const matchesTitle = book.metadata?.title?.toLowerCase().includes(title.toLowerCase());
|
||||
const matchesTitle = book.metadata?.title?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesSeries = book.metadata?.seriesName?.toLowerCase().includes(term.toLowerCase());
|
||||
const matchesAuthor = book.metadata?.authors.some(author =>
|
||||
author.toLowerCase().includes(title.toLowerCase())
|
||||
author.toLowerCase().includes(term.toLowerCase())
|
||||
);
|
||||
return matchesTitle || matchesAuthor;
|
||||
return matchesTitle || matchesSeries || matchesAuthor;
|
||||
}) || null;
|
||||
return {...bookState, books: filteredBooks};
|
||||
}
|
||||
@@ -425,13 +427,13 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
}
|
||||
|
||||
onBookTitleChange(newTitle: string): void {
|
||||
this.bookOrAuthor$.next(newTitle);
|
||||
onSearchTermChange(term: string): void {
|
||||
this.searchTerm$.next(term);
|
||||
}
|
||||
|
||||
clearSearch(): void {
|
||||
this.bookTitle = '';
|
||||
this.onBookTitleChange('');
|
||||
this.onSearchTermChange('');
|
||||
this.resetFilters();
|
||||
}
|
||||
|
||||
@@ -497,7 +499,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
|
||||
sortBooks(field: string): void {
|
||||
const existingSort = this.sortOptions.find(opt => opt.field === field);
|
||||
|
||||
if (!existingSort) return;
|
||||
|
||||
if (this.selectedSort?.field === field) {
|
||||
@@ -521,7 +522,9 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
|
||||
this.router.navigate([], {
|
||||
queryParams: {
|
||||
sort: this.selectedSort.field,
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING ? SORT_DIRECTION.ASCENDING : SORT_DIRECTION.DESCENDING
|
||||
direction: this.selectedSort.direction === SortDirection.ASCENDING
|
||||
? SORT_DIRECTION.ASCENDING
|
||||
: SORT_DIRECTION.DESCENDING
|
||||
},
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true
|
||||
|
||||
+5
-1
@@ -21,6 +21,8 @@
|
||||
<th pResizableColumn>Title</th>
|
||||
<th pResizableColumn>Authors</th>
|
||||
<th pResizableColumn>Publisher</th>
|
||||
<th pResizableColumn>Series</th>
|
||||
<th pResizableColumn>#</th>
|
||||
<th pResizableColumn>Genres</th>
|
||||
<th>Published</th>
|
||||
<th>Last Read</th>
|
||||
@@ -55,9 +57,11 @@
|
||||
<td (click)="openMetadataCenter(book.id)">
|
||||
<img [attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)" alt="Book Cover" class="size-7"/>
|
||||
</td>
|
||||
<td class="min-w-[15rem] max-w-[20rem] overflow-hidden truncate" [title]="metadata.title">{{ metadata.title }}</td>
|
||||
<td class="min-w-[18rem] max-w-[25rem] overflow-hidden truncate" [title]="metadata.title">{{ metadata.title }}</td>
|
||||
<td class="min-w-[10rem] max-w-[15rem] overflow-hidden truncate" [title]="getAuthorNames(metadata.authors)">{{ getAuthorNames(metadata.authors) }}</td>
|
||||
<td class="min-w-[9rem] max-w-[13rem] overflow-hidden truncate" [title]="metadata.publisher">{{ metadata.publisher }}</td>
|
||||
<td class="min-w-[9rem] max-w-[13rem] overflow-hidden truncate" [title]="metadata.seriesName">{{ metadata.seriesName }}</td>
|
||||
<td class="min-w-[1rem] max-w-[1rem] overflow-hidden truncate" [title]="metadata.seriesNumber">{{ metadata.seriesNumber }}</td>
|
||||
<td class="min-w-[12rem] max-w-[18rem] overflow-hidden truncate" [title]="getGenres(metadata.categories)">{{ getGenres(metadata.categories) }}</td>
|
||||
<td class="min-w-[9rem] max-w-[9rem] overflow-hidden truncate">
|
||||
{{ metadata.publishedDate ? (metadata.publishedDate | date: 'dd-MMM-yyyy') : '' }}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<div class="comic-reader-container">
|
||||
<div class="navigation">
|
||||
<div class="goto-page-controls" style="display: flex; align-items: center; margin-right: auto;">
|
||||
<input type="number" [(ngModel)]="goToPageInput" [min]="1" [max]="pages.length" placeholder="Page">
|
||||
<button
|
||||
(click)="goToPageInput !== null && goToPage(goToPageInput)"
|
||||
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > pages.length">
|
||||
Go
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="page-controls" style="display: flex; align-items: center; justify-content: center; flex-grow: 1;">
|
||||
<button class="mr-2" (click)="goToPage(1)" [disabled]="currentPage === 0"><<</button>
|
||||
<button (click)="previousPage()" [disabled]="currentPage === 0"><</button>
|
||||
<span>
|
||||
Page {{ currentPage + 1 }}{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
|
||||
</span>
|
||||
<button (click)="nextPage()" [disabled]="currentPage >= pages.length - 1">></button>
|
||||
<button class="ml-2" (click)="goToPage(pages.length)" [disabled]="currentPage >= pages.length - 1">>></button>
|
||||
</div>
|
||||
|
||||
<div class="spread-controls" style="display: flex; align-items: center; margin-left: auto;">
|
||||
<button *ngIf="isTwoPageView" (click)="toggleSpreadDirection()" title="Toggle Spread Direction">
|
||||
{{ pageSpread === 'ODD' ? '⬅️' : '➡️' }}
|
||||
</button>
|
||||
<button (click)="toggleView()" title="Toggle View">
|
||||
{{ isTwoPageView ? '1️⃣' : '2️⃣' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="image-container" [class.two-page-view]="isTwoPageView">
|
||||
<ng-container *ngIf="!isLoading; else loading">
|
||||
<ng-container *ngIf="pages.length > 0; else noPages">
|
||||
<img *ngFor="let url of imageUrls" [src]="url" alt="Comic Page"/>
|
||||
</ng-container>
|
||||
</ng-container>
|
||||
<ng-template #noPages>
|
||||
<p>No pages available.</p>
|
||||
</ng-template>
|
||||
<ng-template #loading>
|
||||
<div style="display: flex; justify-content: center; align-items: center; height: 100%;">
|
||||
<p-progressSpinner></p-progressSpinner>
|
||||
</div>
|
||||
</ng-template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,115 @@
|
||||
.comic-reader-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
height: 100vh;
|
||||
width: 100vw;
|
||||
overflow-x: hidden;
|
||||
box-sizing: border-box;
|
||||
|
||||
.navigation {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin: 1rem;
|
||||
|
||||
.page-controls {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
|
||||
span {
|
||||
min-width: 8rem;
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0 0.25rem;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
|
||||
&:disabled {
|
||||
cursor: default;
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.spread-controls {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
|
||||
button {
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.image-container {
|
||||
flex-grow: 1;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
overflow: hidden;
|
||||
padding: 0 1rem;
|
||||
box-sizing: border-box;
|
||||
|
||||
&.two-page-view {
|
||||
img {
|
||||
max-width: calc(50% - 0.5rem);
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.two-page-view) {
|
||||
img {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
img {
|
||||
max-height: 100%;
|
||||
height: auto;
|
||||
width: auto;
|
||||
object-fit: contain;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
|
||||
flex-shrink: 1;
|
||||
margin: 0;
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
.goto-page-controls {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
padding-left: 6px;
|
||||
}
|
||||
|
||||
.goto-page-controls input[type="number"] {
|
||||
width: 40px;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.goto-page-controls button:disabled {
|
||||
cursor: default;
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import {Component, HostListener, inject, OnInit} from '@angular/core';
|
||||
import {NgFor, NgIf} from '@angular/common';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {CbxReaderService} from '../../service/cbx-reader.service';
|
||||
import {BookService} from '../../service/book.service';
|
||||
import {UserService} from '../../../settings/user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {forkJoin} from 'rxjs';
|
||||
import {BookSetting, CbxPageSpread, CbxPageViewMode} from '../../model/book.model';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {FormsModule} from "@angular/forms";
|
||||
|
||||
@Component({
|
||||
selector: 'app-cbx-reader',
|
||||
standalone: true,
|
||||
imports: [NgIf, NgFor, ProgressSpinner, FormsModule],
|
||||
templateUrl: './cbx-reader.component.html',
|
||||
styleUrl: './cbx-reader.component.scss'
|
||||
})
|
||||
export class CbxReaderComponent implements OnInit {
|
||||
goToPageInput: number | null = null;
|
||||
bookId!: number;
|
||||
pages: number[] = [];
|
||||
currentPage = 0;
|
||||
isLoading = true;
|
||||
|
||||
pageSpread: CbxPageSpread = CbxPageSpread.ODD;
|
||||
pageViewMode: CbxPageViewMode = CbxPageViewMode.SINGLE_PAGE;
|
||||
|
||||
private touchStartX = 0;
|
||||
private touchEndX = 0;
|
||||
|
||||
private route = inject(ActivatedRoute);
|
||||
private cbxReaderService = inject(CbxReaderService);
|
||||
private bookService = inject(BookService);
|
||||
private userService = inject(UserService);
|
||||
private messageService = inject(MessageService);
|
||||
|
||||
ngOnInit() {
|
||||
this.route.paramMap.subscribe((params) => {
|
||||
this.isLoading = true;
|
||||
this.bookId = +params.get('bookId')!;
|
||||
|
||||
forkJoin([
|
||||
this.bookService.getBookByIdFromAPI(this.bookId, false),
|
||||
this.bookService.getBookSetting(this.bookId),
|
||||
this.userService.getMyself(),
|
||||
this.cbxReaderService.getAvailablePages(this.bookId)
|
||||
]).subscribe({
|
||||
next: ([cbxMeta, bookSettings, myself, pages]) => {
|
||||
const userSettings = myself.userSettings;
|
||||
const global = userSettings.perBookSetting.cbx === 'Global';
|
||||
|
||||
this.pageViewMode = global
|
||||
? userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE
|
||||
: bookSettings.cbxSettings?.pageViewMode || userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE;
|
||||
|
||||
this.pageSpread = global
|
||||
? userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD
|
||||
: bookSettings.cbxSettings?.pageSpread || userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD;
|
||||
|
||||
this.pages = pages;
|
||||
this.currentPage = (cbxMeta.cbxProgress?.page || 1) - 1;
|
||||
this.alignCurrentPageToParity();
|
||||
this.isLoading = false;
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || 'Failed to load the book';
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
|
||||
this.isLoading = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
get isTwoPageView(): boolean {
|
||||
return this.pageViewMode === CbxPageViewMode.TWO_PAGE;
|
||||
}
|
||||
|
||||
toggleView() {
|
||||
if (!this.isTwoPageView && this.isPhonePortrait()) return;
|
||||
this.pageViewMode = this.isTwoPageView ? CbxPageViewMode.SINGLE_PAGE : CbxPageViewMode.TWO_PAGE;
|
||||
this.alignCurrentPageToParity();
|
||||
this.updateViewerSetting();
|
||||
}
|
||||
|
||||
toggleSpreadDirection() {
|
||||
this.pageSpread = this.pageSpread === CbxPageSpread.ODD ? CbxPageSpread.EVEN : CbxPageSpread.ODD;
|
||||
this.alignCurrentPageToParity();
|
||||
this.updateViewerSetting();
|
||||
}
|
||||
|
||||
nextPage() {
|
||||
const previousPage = this.currentPage;
|
||||
|
||||
if (this.isTwoPageView) {
|
||||
if (this.currentPage + 2 < this.pages.length) {
|
||||
this.currentPage += 2;
|
||||
} else if (this.currentPage + 1 < this.pages.length) {
|
||||
this.currentPage += 1;
|
||||
}
|
||||
} else if (this.currentPage < this.pages.length - 1) {
|
||||
this.currentPage++;
|
||||
}
|
||||
|
||||
if (this.currentPage !== previousPage) {
|
||||
this.updateProgress();
|
||||
}
|
||||
}
|
||||
|
||||
previousPage() {
|
||||
if (this.isTwoPageView) {
|
||||
this.currentPage = Math.max(0, this.currentPage - 2);
|
||||
} else {
|
||||
this.currentPage = Math.max(0, this.currentPage - 1);
|
||||
}
|
||||
this.updateProgress();
|
||||
}
|
||||
|
||||
private alignCurrentPageToParity() {
|
||||
if (!this.pages.length || !this.isTwoPageView) return;
|
||||
|
||||
const desiredOdd = this.pageSpread === CbxPageSpread.ODD;
|
||||
for (let i = this.currentPage; i >= 0; i--) {
|
||||
if ((this.pages[i] % 2 === 1) === desiredOdd) {
|
||||
this.currentPage = i;
|
||||
this.updateProgress();
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < this.pages.length; i++) {
|
||||
if ((this.pages[i] % 2 === 1) === desiredOdd) {
|
||||
this.currentPage = i;
|
||||
this.updateProgress();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@HostListener('window:keydown', ['$event'])
|
||||
handleKeyDown(event: KeyboardEvent) {
|
||||
if (event.key === 'ArrowRight') this.nextPage();
|
||||
else if (event.key === 'ArrowLeft') this.previousPage();
|
||||
}
|
||||
|
||||
@HostListener('touchstart', ['$event'])
|
||||
onTouchStart(event: TouchEvent) {
|
||||
this.touchStartX = event.changedTouches[0].screenX;
|
||||
}
|
||||
|
||||
@HostListener('touchend', ['$event'])
|
||||
onTouchEnd(event: TouchEvent) {
|
||||
this.touchEndX = event.changedTouches[0].screenX;
|
||||
this.handleSwipeGesture();
|
||||
}
|
||||
|
||||
@HostListener('window:resize')
|
||||
onResize() {
|
||||
this.enforcePortraitSinglePageView();
|
||||
}
|
||||
|
||||
private handleSwipeGesture() {
|
||||
const delta = this.touchEndX - this.touchStartX;
|
||||
if (Math.abs(delta) >= 50) delta < 0 ? this.nextPage() : this.previousPage();
|
||||
}
|
||||
|
||||
private enforcePortraitSinglePageView() {
|
||||
if (this.isPhonePortrait() && this.isTwoPageView) {
|
||||
this.pageViewMode = CbxPageViewMode.SINGLE_PAGE;
|
||||
this.updateViewerSetting();
|
||||
}
|
||||
}
|
||||
|
||||
private isPhonePortrait(): boolean {
|
||||
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
|
||||
}
|
||||
|
||||
get imageUrls(): string[] {
|
||||
if (!this.pages.length) return [];
|
||||
|
||||
const urls = [this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage])];
|
||||
if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
|
||||
urls.push(this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage + 1]));
|
||||
}
|
||||
|
||||
return urls;
|
||||
}
|
||||
|
||||
private updateViewerSetting(): void {
|
||||
const bookSetting: BookSetting = {
|
||||
cbxSettings: {
|
||||
pageSpread: this.pageSpread,
|
||||
pageViewMode: this.pageViewMode,
|
||||
}
|
||||
}
|
||||
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
|
||||
}
|
||||
|
||||
updateProgress(): void {
|
||||
const percentage = this.pages.length > 0
|
||||
? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
|
||||
: 0;
|
||||
|
||||
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
||||
}
|
||||
goToPage(page: number): void {
|
||||
if (page < 1 || page > this.pages.length) return;
|
||||
|
||||
const targetIndex = page - 1;
|
||||
if (targetIndex === this.currentPage) return;
|
||||
|
||||
this.currentPage = targetIndex;
|
||||
this.alignCurrentPageToParity();
|
||||
this.updateProgress();
|
||||
}
|
||||
}
|
||||
+8
@@ -183,6 +183,14 @@
|
||||
<p-button *ngIf="metadata['isbn13Locked']" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('isbn13')" severity="warn"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 w-1/4">
|
||||
<label for="asin">ASIN</label>
|
||||
<div class="flex justify-between items-center gap-2">
|
||||
<input pInputText id="asin" formControlName="asin" class="w-full"/>
|
||||
<p-button *ngIf="!metadata['asinLocked']" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('asin')" severity="success"></p-button>
|
||||
<p-button *ngIf="metadata['asinLocked']" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('asin')" severity="warn"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 w-1/4">
|
||||
<label for="reviewCount">Rating Count (Legacy)</label>
|
||||
<div class="flex justify-between items-center gap-2">
|
||||
|
||||
+14
-2
@@ -69,6 +69,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDate: new FormControl(''),
|
||||
isbn10: new FormControl(''),
|
||||
isbn13: new FormControl(''),
|
||||
asin: new FormControl(''),
|
||||
description: new FormControl(''),
|
||||
pageCount: new FormControl(''),
|
||||
language: new FormControl(''),
|
||||
@@ -90,6 +91,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDateLocked: new FormControl(false),
|
||||
isbn10Locked: new FormControl(false),
|
||||
isbn13Locked: new FormControl(false),
|
||||
asinLocked: new FormControl(false),
|
||||
descriptionLocked: new FormControl(false),
|
||||
pageCountLocked: new FormControl(false),
|
||||
languageLocked: new FormControl(false),
|
||||
@@ -125,6 +127,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDate: metadata.publishedDate || null,
|
||||
isbn10: metadata.isbn10 || null,
|
||||
isbn13: metadata.isbn13 || null,
|
||||
asin: metadata.asin || null,
|
||||
description: metadata.description || null,
|
||||
pageCount: metadata.pageCount || null,
|
||||
language: metadata.language || null,
|
||||
@@ -146,6 +149,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDateLocked: metadata.publishedDateLocked || false,
|
||||
isbn10Locked: metadata.isbn10Locked || false,
|
||||
isbn13Locked: metadata.isbn13Locked || false,
|
||||
asinLocked: metadata.asinLocked || false,
|
||||
descriptionLocked: metadata.descriptionLocked || false,
|
||||
pageCountLocked: metadata.pageCountLocked || false,
|
||||
languageLocked: metadata.languageLocked || false,
|
||||
@@ -171,6 +175,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
{ key: 'languageLocked', control: 'language' },
|
||||
{ key: 'isbn10Locked', control: 'isbn10' },
|
||||
{ key: 'isbn13Locked', control: 'isbn13' },
|
||||
{ key: 'asinLocked', control: 'asin'},
|
||||
{ key: 'amazonReviewCountLocked', control: 'amazonReviewCount' },
|
||||
{ key: 'amazonRatingLocked', control: 'amazonRating' },
|
||||
{ key: 'goodreadsReviewCountLocked', control: 'goodreadsReviewCount' },
|
||||
@@ -210,8 +215,13 @@ export class MetadataEditorComponent implements OnInit {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book metadata updated'});
|
||||
this.metadataCenterService.emitMetadata(response);
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to update book metadata'});
|
||||
error: (err) => {
|
||||
console.error('Update metadata failed:', err);
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: err?.error?.message || 'Failed to update book metadata'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -276,6 +286,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDate: this.metadataForm.get('publishedDate')?.value,
|
||||
isbn10: this.metadataForm.get('isbn10')?.value,
|
||||
isbn13: this.metadataForm.get('isbn13')?.value,
|
||||
asin: this.metadataForm.get('asin')?.value,
|
||||
description: this.metadataForm.get('description')?.value,
|
||||
pageCount: this.metadataForm.get('pageCount')?.value,
|
||||
rating: this.metadataForm.get('rating')?.value,
|
||||
@@ -297,6 +308,7 @@ export class MetadataEditorComponent implements OnInit {
|
||||
publishedDateLocked: this.metadataForm.get('publishedDateLocked')?.value,
|
||||
isbn10Locked: this.metadataForm.get('isbn10Locked')?.value,
|
||||
isbn13Locked: this.metadataForm.get('isbn13Locked')?.value,
|
||||
asinLocked: this.metadataForm.get('asinLocked')?.value,
|
||||
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
|
||||
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
|
||||
languageLocked: this.metadataForm.get('languageLocked')?.value,
|
||||
|
||||
+8
@@ -54,6 +54,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
{label: 'Book #', controlName: 'seriesNumber', lockedKey: 'seriesNumberLocked', fetchedKey: 'seriesNumber'},
|
||||
{label: 'Total Books', controlName: 'seriesTotal', lockedKey: 'seriesTotalLocked', fetchedKey: 'seriesTotal'},
|
||||
{label: 'ISBN-13', controlName: 'isbn13', lockedKey: 'isbn13Locked', fetchedKey: 'isbn13'},
|
||||
{label: 'ASIN', controlName: 'asin', lockedKey: 'asinLocked', fetchedKey: 'asin'},
|
||||
{label: 'Amazon Reviews', controlName: 'amazonReviewCount', lockedKey: 'amazonReviewCountLocked', fetchedKey: 'amazonReviewCount'},
|
||||
{label: 'Amazon Rating', controlName: 'amazonRating', lockedKey: 'amazonRatingLocked', fetchedKey: 'amazonRating'},
|
||||
{label: 'Goodreads Reviews', controlName: 'goodreadsReviewCount', lockedKey: 'goodreadsReviewCountLocked', fetchedKey: 'goodreadsReviewCount'},
|
||||
@@ -87,6 +88,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDate: new FormControl(''),
|
||||
isbn10: new FormControl(''),
|
||||
isbn13: new FormControl(''),
|
||||
asin: new FormControl(''),
|
||||
description: new FormControl(''),
|
||||
pageCount: new FormControl(''),
|
||||
language: new FormControl(''),
|
||||
@@ -107,6 +109,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDateLocked: new FormControl(false),
|
||||
isbn10Locked: new FormControl(false),
|
||||
isbn13Locked: new FormControl(false),
|
||||
asinLocked: new FormControl(false),
|
||||
descriptionLocked: new FormControl(false),
|
||||
pageCountLocked: new FormControl(false),
|
||||
languageLocked: new FormControl(false),
|
||||
@@ -136,6 +139,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDate: metadata.publishedDate || null,
|
||||
isbn10: metadata.isbn10 || null,
|
||||
isbn13: metadata.isbn13 || null,
|
||||
asin: metadata.asin || null,
|
||||
description: metadata.description || null,
|
||||
pageCount: metadata.pageCount || null,
|
||||
language: metadata.language || null,
|
||||
@@ -156,6 +160,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDateLocked: metadata.publishedDateLocked || false,
|
||||
isbn10Locked: metadata.isbn10Locked || false,
|
||||
isbn13Locked: metadata.isbn13Locked || false,
|
||||
asinLocked: metadata.asinLocked || false,
|
||||
descriptionLocked: metadata.descriptionLocked || false,
|
||||
pageCountLocked: metadata.pageCountLocked || false,
|
||||
languageLocked: metadata.languageLocked || false,
|
||||
@@ -178,6 +183,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
if (metadata.languageLocked) this.metadataForm.get('language')?.disable();
|
||||
if (metadata.isbn10Locked) this.metadataForm.get('isbn10')?.disable();
|
||||
if (metadata.isbn13Locked) this.metadataForm.get('isbn13')?.disable();
|
||||
if (metadata.asinLocked) this.metadataForm.get('asin')?.disable();
|
||||
if (metadata.amazonReviewCountLocked) this.metadataForm.get('amazonReviewCount')?.disable();
|
||||
if (metadata.amazonRatingLocked) this.metadataForm.get('amazonRating')?.disable();
|
||||
if (metadata.goodreadsReviewCountLocked) this.metadataForm.get('goodreadsReviewCount')?.disable();
|
||||
@@ -220,6 +226,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDate: this.metadataForm.get('publishedDate')?.value || this.copiedFields['publishedDate'] ? this.getValueOrCopied('publishedDate') : '',
|
||||
isbn10: this.metadataForm.get('isbn10')?.value || this.copiedFields['isbn10'] ? this.getValueOrCopied('isbn10') : '',
|
||||
isbn13: this.metadataForm.get('isbn13')?.value || this.copiedFields['isbn13'] ? this.getValueOrCopied('isbn13') : '',
|
||||
asin: this.metadataForm.get('asin')?.value || this.copiedFields['asin'] ? this.getValueOrCopied('asin') : '',
|
||||
description: this.metadataForm.get('description')?.value || this.copiedFields['description'] ? this.getValueOrCopied('description') : '',
|
||||
pageCount: this.metadataForm.get('pageCount')?.value || this.copiedFields['pageCount'] ? this.getPageCountOrCopied() : null,
|
||||
language: this.metadataForm.get('language')?.value || this.copiedFields['language'] ? this.getValueOrCopied('language') : '',
|
||||
@@ -240,6 +247,7 @@ export class MetadataPickerComponent implements OnInit {
|
||||
publishedDateLocked: this.metadataForm.get('publishedDateLocked')?.value,
|
||||
isbn10Locked: this.metadataForm.get('isbn10Locked')?.value,
|
||||
isbn13Locked: this.metadataForm.get('isbn13Locked')?.value,
|
||||
asinLocked: this.metadataForm.get('asin')?.value,
|
||||
descriptionLocked: this.metadataForm.get('descriptionLocked')?.value,
|
||||
pageCountLocked: this.metadataForm.get('pageCountLocked')?.value,
|
||||
languageLocked: this.metadataForm.get('languageLocked')?.value,
|
||||
|
||||
+22
-21
@@ -86,6 +86,7 @@
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ metadata.isbn13 || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">ASIN:</span> {{ metadata.asin || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ metadata.pageCount || '-' }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB() }}</p>
|
||||
<p class="whitespace-nowrap"><span class="font-bold">Progress:</span> {{ getProgressPercent() !== null ? getProgressPercent() + '%' : '-' }}</p>
|
||||
@@ -129,28 +130,7 @@
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<ng-container *ngIf="recommendedBooks.length > 0">
|
||||
<div>
|
||||
<h3 class="text-xl font-semibold">Similar Books</h3>
|
||||
<div class="dashboard-scroller-infinite"
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
<div class="dashboard-scroller-card" *ngFor="let book of recommendedBooks">
|
||||
<app-book-card
|
||||
[book]="book.book"
|
||||
[isCheckboxEnabled]="false"
|
||||
[readButtonHidden]="true"
|
||||
[bottomBarHidden]="true">
|
||||
</app-book-card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
|
||||
<ng-container *ngIf="bookInSeries.length > 0">
|
||||
<p-divider></p-divider>
|
||||
<div>
|
||||
<h3 class="text-xl font-semibold pt-2">More in the Series</h3>
|
||||
<div class="dashboard-scroller-infinite"
|
||||
@@ -171,5 +151,26 @@
|
||||
<p-divider></p-divider>
|
||||
</ng-container>
|
||||
|
||||
<ng-container *ngIf="recommendedBooks.length > 0">
|
||||
<div>
|
||||
<h3 class="text-xl font-semibold">Similar Books</h3>
|
||||
<div class="dashboard-scroller-infinite"
|
||||
infiniteScroll
|
||||
[infiniteScrollDistance]="2"
|
||||
[infiniteScrollThrottle]="50"
|
||||
[horizontal]="true">
|
||||
<div class="dashboard-scroller-card" *ngFor="let book of recommendedBooks">
|
||||
<app-book-card
|
||||
[book]="book.book"
|
||||
[isCheckboxEnabled]="false"
|
||||
[readButtonHidden]="true"
|
||||
[bottomBarHidden]="true">
|
||||
</app-book-card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p-divider></p-divider>
|
||||
</ng-container>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+32
-9
@@ -1,4 +1,4 @@
|
||||
import {Component, DestroyRef, inject, Input, OnInit, ViewChild} from '@angular/core';
|
||||
import {Component, DestroyRef, inject, Input, OnInit, OnChanges, SimpleChanges, ViewChild} from '@angular/core';
|
||||
import {Button, ButtonDirective} from 'primeng/button';
|
||||
import {AsyncPipe, DecimalPipe, NgClass, NgForOf, NgIf} from '@angular/common';
|
||||
import {first, Observable} from 'rxjs';
|
||||
@@ -31,10 +31,11 @@ import {ProgressBar} from 'primeng/progressbar';
|
||||
styleUrl: './metadata-viewer.component.scss',
|
||||
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective, Editor, ProgressBar]
|
||||
})
|
||||
export class MetadataViewerComponent implements OnInit {
|
||||
export class MetadataViewerComponent implements OnInit, OnChanges {
|
||||
|
||||
@Input() book: Book | undefined;
|
||||
@Input() recommendedBooks: BookRecommendation[] = [];
|
||||
private originalRecommendedBooks: BookRecommendation[] = [];
|
||||
|
||||
@ViewChild(Editor) quillEditor!: Editor;
|
||||
|
||||
@@ -81,7 +82,7 @@ export class MetadataViewerComponent implements OnInit {
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((metadata) => {
|
||||
if (metadata) {
|
||||
this.getBooksInSeries(metadata.bookId);
|
||||
this.loadBooksInSeriesAndFilterRecommended(metadata.bookId);
|
||||
if (this.quillEditor && this.quillEditor.quill) {
|
||||
this.quillEditor.quill.root.innerHTML = metadata.description;
|
||||
}
|
||||
@@ -89,14 +90,34 @@ export class MetadataViewerComponent implements OnInit {
|
||||
});
|
||||
}
|
||||
|
||||
toggleExpand(): void {
|
||||
this.isExpanded = !this.isExpanded;
|
||||
private loadBooksInSeriesAndFilterRecommended(bookId: number): void {
|
||||
this.bookService.getBooksInSeries(bookId).subscribe((bookInSeries) => {
|
||||
bookInSeries.sort((a, b) => (a.metadata?.seriesNumber ?? 0) - (b.metadata?.seriesNumber ?? 0));
|
||||
this.bookInSeries = bookInSeries;
|
||||
this.originalRecommendedBooks = [...this.recommendedBooks];
|
||||
this.filterRecommendations();
|
||||
});
|
||||
}
|
||||
|
||||
getBooksInSeries(bookId: number): void {
|
||||
this.bookService.getBooksInSeries(bookId).subscribe((bookInSeries) => {
|
||||
this.bookInSeries = bookInSeries;
|
||||
});
|
||||
ngOnChanges(changes: SimpleChanges): void {
|
||||
if (changes['recommendedBooks']) {
|
||||
this.originalRecommendedBooks = [...this.recommendedBooks];
|
||||
this.filterRecommendations();
|
||||
}
|
||||
}
|
||||
|
||||
private filterRecommendations(): void {
|
||||
if (!this.originalRecommendedBooks) {
|
||||
return;
|
||||
}
|
||||
const bookInSeriesIds = new Set(this.bookInSeries.map(book => book.id));
|
||||
this.recommendedBooks = this.originalRecommendedBooks.filter(
|
||||
rec => !bookInSeriesIds.has(rec.book.id)
|
||||
);
|
||||
}
|
||||
|
||||
toggleExpand(): void {
|
||||
this.isExpanded = !this.isExpanded;
|
||||
}
|
||||
|
||||
read(bookId: number): void {
|
||||
@@ -168,6 +189,8 @@ export class MetadataViewerComponent implements OnInit {
|
||||
getProgressPercent(): number | undefined {
|
||||
if (this.book?.bookType === 'PDF') {
|
||||
return this.book.pdfProgress?.percentage;
|
||||
} else if(this.book?.bookType === 'CBX') {
|
||||
return this.book?.cbxProgress?.percentage;
|
||||
} else {
|
||||
return this.book?.epubProgress?.percentage;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {Shelf} from './shelf.model';
|
||||
|
||||
export type BookType = "PDF" | "EPUB";
|
||||
export type BookType = "PDF" | "EPUB" | "CBX";
|
||||
|
||||
export interface Book {
|
||||
id: number;
|
||||
@@ -12,6 +12,7 @@ export interface Book {
|
||||
addedOn?: string;
|
||||
epubProgress?: EpubProgress;
|
||||
pdfProgress?: PdfProgress;
|
||||
cbxProgress?: CbxProgress;
|
||||
filePath?: string;
|
||||
fileSizeKb?: number;
|
||||
}
|
||||
@@ -26,6 +27,11 @@ export interface PdfProgress {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface CbxProgress {
|
||||
page: number;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
bookId: number;
|
||||
title: string;
|
||||
@@ -102,9 +108,15 @@ export interface EpubViewerSetting {
|
||||
flow: string;
|
||||
}
|
||||
|
||||
export interface CbxViewerSetting {
|
||||
pageSpread: CbxPageSpread;
|
||||
pageViewMode: CbxPageViewMode;
|
||||
}
|
||||
|
||||
export interface BookSetting {
|
||||
pdfSettings?: PdfViewerSetting;
|
||||
epubSettings?: EpubViewerSetting;
|
||||
cbxSettings?: CbxViewerSetting;
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
@@ -113,3 +125,13 @@ export interface BookRecommendation {
|
||||
book: Book;
|
||||
similarityScore: number;
|
||||
}
|
||||
|
||||
export const enum CbxPageViewMode {
|
||||
SINGLE_PAGE = 'SINGLE_PAGE',
|
||||
TWO_PAGE = 'TWO_PAGE',
|
||||
}
|
||||
|
||||
export const enum CbxPageSpread {
|
||||
EVEN = 'EVEN',
|
||||
ODD = 'ODD',
|
||||
}
|
||||
|
||||
@@ -128,6 +128,10 @@ export class BookService {
|
||||
const url = `/epub-viewer/book/${book.id}`;
|
||||
window.open(url, '_blank');
|
||||
this.updateLastReadTime(book.id);
|
||||
} else if (book.bookType === "CBX") {
|
||||
const url = `/cbx-viewer/book/${book.id}`;
|
||||
window.open(url, '_blank');
|
||||
this.updateLastReadTime(book.id);
|
||||
} else {
|
||||
console.error('Unsupported book type:', book.bookType);
|
||||
}
|
||||
@@ -207,6 +211,17 @@ export class BookService {
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
|
||||
const body = {
|
||||
bookId: bookId,
|
||||
cbxProgress: {
|
||||
page: page,
|
||||
percentage: percentage
|
||||
}
|
||||
};
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
regenerateCovers(): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CbxReaderService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/cbx`;
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
getAvailablePages(bookId: number) {
|
||||
return this.http.get<number[]>(`${this.url}/${bookId}/pages`);
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number): string {
|
||||
return `${this.url}/${bookId}/pages/${page}`;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,15 @@ export class SortService {
|
||||
|
||||
private readonly fieldExtractors: Record<string, (book: Book) => any> = {
|
||||
title: (book) => book.metadata?.title?.toLowerCase() || null,
|
||||
titleSeries: (book) => {
|
||||
const title = book.metadata?.title?.toLowerCase() || '';
|
||||
const series = book.metadata?.seriesName?.toLowerCase();
|
||||
const seriesNumber = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
|
||||
if (series) {
|
||||
return [series, seriesNumber];
|
||||
}
|
||||
return [title, Number.MAX_SAFE_INTEGER];
|
||||
},
|
||||
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
|
||||
publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(),
|
||||
publisher: (book) => book.metadata?.publisher || null,
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface AppSettings {
|
||||
oidcEnabled: boolean;
|
||||
oidcProviderDetails: OidcProviderDetails;
|
||||
oidcAutoProvisionDetails: OidcAutoProvisionDetails;
|
||||
cbxCacheSizeInMb: number;
|
||||
maxFileUploadSizeInMb: number;
|
||||
}
|
||||
|
||||
export enum AppSettingKey {
|
||||
@@ -40,5 +42,7 @@ export enum AppSettingKey {
|
||||
OPDS_SERVER_ENABLED = 'OPDS_SERVER_ENABLED',
|
||||
OIDC_ENABLED = 'OIDC_ENABLED',
|
||||
OIDC_PROVIDER_DETAILS = 'OIDC_PROVIDER_DETAILS',
|
||||
OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS'
|
||||
OIDC_AUTO_PROVISION_DETAILS = 'OIDC_AUTO_PROVISION_DETAILS',
|
||||
CBX_CACHE_SIZE_IN_MB = 'CBX_CACHE_SIZE_IN_MB',
|
||||
MAX_FILE_UPLOAD_SIZE_IN_MB = 'MAX_FILE_UPLOAD_SIZE_IN_MB'
|
||||
}
|
||||
|
||||
@@ -13,14 +13,13 @@
|
||||
<div class="grid grid-cols-[auto,1fr] pl-6 gap-y-4 gap-x-4 items-center">
|
||||
<p class=" py-1">Resolution:
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Specifies the resolution of the generated cover image. Higher resolutions result in sharper images but may increase file size. This setting will apply to future books, or else use 'Regenerate' button."
|
||||
pTooltip="Sets the resolution for generated cover images. Higher resolutions produce sharper covers but increase file size. Applies only to future books unless covers are regenerated."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="resolutionOptions"
|
||||
[(ngModel)]="selectedResolution"
|
||||
(ngModelChange)="onResolutionChange()"
|
||||
@@ -30,7 +29,7 @@
|
||||
|
||||
<p class=" py-1">Regenerate Covers?
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="This option will regenerate the covers for all EPUB and PDF books (except locked ones) using the selected resolution."
|
||||
pTooltip="Regenerates cover images for all EPUB and PDF books (excluding locked ones) using the selected resolution."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
@@ -50,7 +49,7 @@
|
||||
<div>
|
||||
<p class="text-lg pb-4 ">Auto Book Search
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="If enabled, Booklore will automatically perform a metadata match/search when the book information tab is opened."
|
||||
pTooltip="Automatically attempts metadata matching when the book information panel is opened."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
@@ -68,7 +67,7 @@
|
||||
<div>
|
||||
<p class="text-lg pb-4 ">Similar Book Recommendation
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Enable or disable similar book recommendations entirely."
|
||||
pTooltip="Enables or disables similar book recommendations based on your library."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
@@ -89,6 +88,55 @@
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row gap-11 p-4">
|
||||
<div>
|
||||
<p class="text-lg pb-4 ">Max File Upload Size:
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Defines the maximum allowed size (in MB) for each uploaded file. Applies to EPUB, PDF, CBZ, CBR, and CB7 formats."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<div class="flex gap-4 items-center">
|
||||
<div class="relative w-28">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="maxFileUploadSizeInMb"
|
||||
class="pr-10 w-full"
|
||||
placeholder="Max size"/>
|
||||
<span class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 text-sm pointer-events-none">MB</span>
|
||||
</div>
|
||||
<p-button label="Save" outlined (onClick)="saveFileSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-lg pb-4 ">CBX Cache Size:
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Limits the total size (in MB) of the CBX image cache. If exceeded, older cache entries are removed automatically."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<div class="flex gap-4 items-center">
|
||||
<div class="relative w-28">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
[(ngModel)]="cbxCacheValue"
|
||||
class="pr-10 w-full"
|
||||
placeholder="Cache size"/>
|
||||
<span class="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 text-sm pointer-events-none">MB</span>
|
||||
</div>
|
||||
<p-button label="Save" outlined (onClick)="saveCacheSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pt-2 pb-4">
|
||||
<p-divider></p-divider>
|
||||
</div>
|
||||
|
||||
<div class="p-4">
|
||||
<app-opds-settings></app-opds-settings>
|
||||
</div>
|
||||
@@ -114,7 +162,8 @@
|
||||
style="cursor: pointer;">
|
||||
</i>
|
||||
</p>
|
||||
<app-metadata-advanced-fetch-options (metadataOptionsSubmitted)="onMetadataSubmit($event)" [currentMetadataOptions]="currentMetadataOptions"></app-metadata-advanced-fetch-options>
|
||||
<app-metadata-advanced-fetch-options (metadataOptionsSubmitted)="onMetadataSubmit($event)"
|
||||
[currentMetadataOptions]="currentMetadataOptions"></app-metadata-advanced-fetch-options>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -18,6 +18,7 @@ import {MetadataAdvancedFetchOptionsComponent} from '../../book/metadata/metadat
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {FileUploadPatternComponent} from './file-upload-pattern/file-upload-pattern.component';
|
||||
import {OpdsSettingsComponent} from './opds-settings/opds-settings.component';
|
||||
import {InputText} from 'primeng/inputtext';
|
||||
|
||||
@Component({
|
||||
selector: 'app-global-preferences',
|
||||
@@ -32,7 +33,8 @@ import {OpdsSettingsComponent} from './opds-settings/opds-settings.component';
|
||||
FormsModule,
|
||||
MetadataAdvancedFetchOptionsComponent,
|
||||
FileUploadPatternComponent,
|
||||
OpdsSettingsComponent
|
||||
OpdsSettingsComponent,
|
||||
InputText
|
||||
],
|
||||
templateUrl: './global-preferences.component.html',
|
||||
styleUrl: './global-preferences.component.scss'
|
||||
@@ -59,6 +61,8 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
private messageService = inject(MessageService);
|
||||
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
cbxCacheValue?: number;
|
||||
maxFileUploadSizeInMb?: number;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$.pipe(
|
||||
@@ -68,9 +72,15 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
if (settings?.coverResolution) {
|
||||
this.selectedResolution = settings.coverResolution;
|
||||
}
|
||||
if (settings.metadataRefreshOptions) {
|
||||
if (settings?.metadataRefreshOptions) {
|
||||
this.currentMetadataOptions = settings.metadataRefreshOptions;
|
||||
}
|
||||
if (settings?.cbxCacheSizeInMb) {
|
||||
this.cbxCacheValue = settings.cbxCacheSizeInMb;
|
||||
}
|
||||
if (settings?.maxFileUploadSizeInMb) {
|
||||
this.maxFileUploadSizeInMb = settings.maxFileUploadSizeInMb;
|
||||
}
|
||||
this.toggles.autoBookSearch = settings.autoBookSearch ?? false;
|
||||
this.toggles.similarBookRecommendation = settings.similarBookRecommendation ?? false;
|
||||
});
|
||||
@@ -98,6 +108,23 @@ export class GlobalPreferencesComponent implements OnInit {
|
||||
this.saveSetting(AppSettingKey.QUICK_BOOK_MATCH, metadataRefreshOptions);
|
||||
}
|
||||
|
||||
saveCacheSize(): void {
|
||||
if (!this.cbxCacheValue || this.cbxCacheValue <= 0) {
|
||||
this.showMessage('error', 'Invalid Input', 'Please enter a valid cache size in MB.');
|
||||
return;
|
||||
}
|
||||
|
||||
this.saveSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, this.cbxCacheValue);
|
||||
}
|
||||
|
||||
saveFileSize() {
|
||||
if (!this.maxFileUploadSizeInMb || this.maxFileUploadSizeInMb <= 0) {
|
||||
this.showMessage('error', 'Invalid Input', 'Please enter a valid max file upload size in MB.');
|
||||
return;
|
||||
}
|
||||
this.saveSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, this.maxFileUploadSizeInMb);
|
||||
}
|
||||
|
||||
regenerateCovers(): void {
|
||||
this.bookService.regenerateCovers().subscribe({
|
||||
next: () =>
|
||||
|
||||
@@ -5,6 +5,7 @@ import {API_CONFIG} from '../../config/api-config';
|
||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||
import {Library} from '../../book/model/library.model';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
import {CbxPageSpread, CbxPageViewMode} from '../../book/model/book.model';
|
||||
|
||||
export interface SidebarLibrarySorting {
|
||||
field: string;
|
||||
@@ -19,6 +20,7 @@ export interface SidebarShelfSorting {
|
||||
export interface PerBookSetting {
|
||||
pdf: string;
|
||||
epub: string;
|
||||
cbx: string;
|
||||
}
|
||||
|
||||
export type PageSpread = 'off' | 'even' | 'odd';
|
||||
@@ -36,10 +38,16 @@ export interface EpubReaderSetting {
|
||||
flow: string;
|
||||
}
|
||||
|
||||
export interface CbxReaderSetting {
|
||||
pageSpread: CbxPageSpread;
|
||||
pageViewMode: CbxPageViewMode;
|
||||
}
|
||||
|
||||
export interface UserSettings {
|
||||
perBookSetting: PerBookSetting;
|
||||
pdfReaderSetting: PdfReaderSetting;
|
||||
epubReaderSetting: EpubReaderSetting;
|
||||
cbxReaderSetting: CbxReaderSetting;
|
||||
sidebarLibrarySorting: SidebarLibrarySorting;
|
||||
sidebarShelfSorting: SidebarShelfSorting
|
||||
}
|
||||
|
||||
@@ -38,6 +38,20 @@
|
||||
<label [for]="item">{{ item }}</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="py-1">CBX:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<div *ngFor="let item of scopeOptions" class="flex items-center gap-2">
|
||||
<p-radiobutton
|
||||
[inputId]="item"
|
||||
name="spread"
|
||||
[value]="item"
|
||||
[(ngModel)]="selectedCbxScope"
|
||||
(ngModelChange)="onCbxScopeChange()">
|
||||
</p-radiobutton>
|
||||
<label [for]="item">{{ item }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -97,12 +111,13 @@
|
||||
<p>Theme:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="themes"
|
||||
[(ngModel)]="selectedTheme"
|
||||
optionLabel="name"
|
||||
optionValue="key"
|
||||
placeholder="Select a Theme"
|
||||
class="w-full md:w-56"
|
||||
class="w-full md:w-32"
|
||||
(ngModelChange)="onThemeChange()">
|
||||
</p-select>
|
||||
</div>
|
||||
@@ -110,12 +125,13 @@
|
||||
<p>Font:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="fonts"
|
||||
[(ngModel)]="selectedFont"
|
||||
optionLabel="name"
|
||||
optionValue="key"
|
||||
placeholder="Select a Font"
|
||||
class="w-full md:w-56"
|
||||
class="w-full md:w-32"
|
||||
(ngModelChange)="onFontChange()">
|
||||
</p-select>
|
||||
</div>
|
||||
@@ -123,21 +139,64 @@
|
||||
<p>Flow:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="flowOptions"
|
||||
[(ngModel)]="selectedFlow"
|
||||
optionLabel="name"
|
||||
optionValue="key"
|
||||
placeholder="Select a Flow"
|
||||
class="w-full md:w-56"
|
||||
class="w-full md:w-32"
|
||||
(ngModelChange)="onFlowChange()">
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<p class="py-1">Font Size:</p>
|
||||
<div class="flex gap-4 justify-start items-center">
|
||||
<p-button icon="pi pi-minus" rounded="true" size="small" (click)="decreaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-minus" size="small" (click)="decreaseFontSize()"></p-button>
|
||||
<p>{{ fontSize }}%</p>
|
||||
<p-button icon="pi pi-plus" rounded="true" size="small" (click)="increaseFontSize()"></p-button>
|
||||
<p-button icon="pi pi-plus" size="small" (click)="increaseFontSize()"></p-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="p-4">
|
||||
<p class="text-lg pb-6 pt-4 ">
|
||||
CBX Reader: Global Preferences
|
||||
<i class="pi pi-info-circle text-sky-600"
|
||||
pTooltip="Configure global PDF reading options such as page spread, zoom level, and sidebar visibility that apply to all PDFs."
|
||||
tooltipPosition="right"
|
||||
style="cursor: pointer;"></i>
|
||||
</p>
|
||||
|
||||
<div class="grid grid-cols-[auto,1fr] pl-6 gap-y-4 gap-x-4 items-center">
|
||||
<p class="py-1">Page Spread:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<div *ngFor="let spread of cbxSpreads" class="flex items-center gap-2">
|
||||
<p-radiobutton
|
||||
[inputId]="spread.key"
|
||||
name="spread"
|
||||
[value]="spread.key"
|
||||
[(ngModel)]="selectedCbxSpread"
|
||||
(ngModelChange)="onCbxSpreadChange()">
|
||||
</p-radiobutton>
|
||||
<label [for]="spread.key">{{ spread.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="py-1">Page Zoom:</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<div *ngFor="let mode of cbxViewModes" class="flex items-center gap-2">
|
||||
<p-radiobutton
|
||||
[inputId]="mode.key"
|
||||
name="zoom"
|
||||
[value]="mode.key"
|
||||
[(ngModel)]="selectedCbxViewMode"
|
||||
(ngModelChange)="onCbxViewModeChange()">
|
||||
</p-radiobutton>
|
||||
<label [for]="mode.key">{{ mode.name }}</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -164,6 +223,7 @@
|
||||
</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="sortingOptions"
|
||||
[(ngModel)]="selectedLibrarySorting"
|
||||
(ngModelChange)="onLibrarySortingChange()"
|
||||
@@ -180,6 +240,7 @@
|
||||
</p>
|
||||
<div class="flex gap-4 justify-start">
|
||||
<p-select
|
||||
size="small"
|
||||
[options]="sortingOptions"
|
||||
[(ngModel)]="selectedShelfSorting"
|
||||
(ngModelChange)="onShelfSortingChange()"
|
||||
|
||||
@@ -9,6 +9,7 @@ import {Button} from 'primeng/button';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {SidebarLibrarySorting, SidebarShelfSorting, User, UserService, UserSettings} from '../user-management/user.service';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {CbxPageSpread, CbxPageViewMode} from '../../book/model/book.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-user-preferences',
|
||||
@@ -19,10 +20,22 @@ import {MessageService} from 'primeng/api';
|
||||
})
|
||||
export class UserPreferences implements OnInit, OnDestroy {
|
||||
|
||||
|
||||
readonly cbxSpreads = [
|
||||
{name: 'Even', key: 'EVEN'},
|
||||
{name: 'Odd', key: 'ODD'}
|
||||
];
|
||||
|
||||
readonly cbxViewModes = [
|
||||
{name: 'Single Page', key: 'SINGLE_PAGE'},
|
||||
{name: 'Two Page', key: 'TWO_PAGE'},
|
||||
];
|
||||
|
||||
|
||||
readonly spreads = [
|
||||
{name: 'Even Spread', key: 'even'},
|
||||
{name: 'Odd Spread', key: 'odd'},
|
||||
{name: 'No Spread', key: 'off'}
|
||||
{name: 'Even', key: 'even'},
|
||||
{name: 'Odd', key: 'odd'},
|
||||
{name: 'None', key: 'off'}
|
||||
];
|
||||
|
||||
readonly zooms = [
|
||||
@@ -47,7 +60,7 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
{name: 'Monospace', key: 'monospace'}
|
||||
];
|
||||
|
||||
flowOptions = [
|
||||
readonly flowOptions = [
|
||||
{name: 'Paginated', key: 'paginated'},
|
||||
{name: 'Scrolled', key: 'scrolled'}
|
||||
];
|
||||
@@ -60,6 +73,11 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
];
|
||||
|
||||
readonly scopeOptions = ['Global', 'Individual'];
|
||||
|
||||
|
||||
selectedCbxSpread!: CbxPageSpread;
|
||||
selectedCbxViewMode!: CbxPageViewMode;
|
||||
|
||||
selectedSpread!: 'even' | 'odd' | 'off';
|
||||
selectedZoom!: string;
|
||||
selectedTheme!: string;
|
||||
@@ -67,8 +85,11 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
selectedFlow!: string;
|
||||
fontSize = 100;
|
||||
showSidebar = false;
|
||||
|
||||
selectedPdfScope!: string;
|
||||
selectedEpubScope!: string;
|
||||
selectedCbxScope!: string;
|
||||
|
||||
selectedLibrarySorting: SidebarLibrarySorting = {field: 'id', order: 'asc'};
|
||||
selectedShelfSorting: SidebarShelfSorting = {field: 'id', order: 'asc'};
|
||||
|
||||
@@ -95,13 +116,20 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
private loadPreferences(settings: UserSettings): void {
|
||||
this.selectedPdfScope = settings.perBookSetting.pdf;
|
||||
this.selectedEpubScope = settings.perBookSetting.epub;
|
||||
this.selectedCbxScope = settings.perBookSetting.cbx;
|
||||
|
||||
this.selectedSpread = settings.pdfReaderSetting.pageSpread;
|
||||
this.selectedZoom = settings.pdfReaderSetting.pageZoom;
|
||||
this.showSidebar = settings.pdfReaderSetting.showSidebar;
|
||||
|
||||
this.selectedTheme = settings.epubReaderSetting.theme;
|
||||
this.selectedFlow = settings.epubReaderSetting.flow;
|
||||
this.fontSize = settings.epubReaderSetting.fontSize;
|
||||
this.selectedFont = settings.epubReaderSetting.font;
|
||||
|
||||
this.selectedCbxSpread = settings.cbxReaderSetting.pageSpread;
|
||||
this.selectedCbxViewMode = settings.cbxReaderSetting.pageViewMode;
|
||||
|
||||
this.selectedLibrarySorting = settings.sidebarLibrarySorting;
|
||||
this.selectedShelfSorting = settings.sidebarShelfSorting;
|
||||
}
|
||||
@@ -145,6 +173,14 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
this.updatePreference(['pdfReaderSetting', 'pageSpread'], this.selectedSpread);
|
||||
}
|
||||
|
||||
onCbxSpreadChange() {
|
||||
this.updatePreference(['cbxReaderSetting', 'pageSpread'], this.selectedCbxSpread);
|
||||
}
|
||||
|
||||
onCbxViewModeChange() {
|
||||
this.updatePreference(['cbxReaderSetting', 'pageViewMode'], this.selectedCbxViewMode);
|
||||
}
|
||||
|
||||
onZoomChange() {
|
||||
this.updatePreference(['pdfReaderSetting', 'pageZoom'], this.selectedZoom);
|
||||
}
|
||||
@@ -157,6 +193,10 @@ export class UserPreferences implements OnInit, OnDestroy {
|
||||
this.updatePreference(['perBookSetting', 'epub'], this.selectedEpubScope);
|
||||
}
|
||||
|
||||
onCbxScopeChange() {
|
||||
this.updatePreference(['perBookSetting', 'cbx'], this.selectedCbxScope);
|
||||
}
|
||||
|
||||
onLibrarySortingChange() {
|
||||
this.updatePreference(['sidebarLibrarySorting'], this.selectedLibrarySorting);
|
||||
}
|
||||
|
||||
@@ -18,9 +18,9 @@
|
||||
class="w-full"></p-select>
|
||||
|
||||
<p-fileupload class="w-full" name="file"
|
||||
maxFileSize="104857600"
|
||||
[maxFileSize]="maxFileSizeBytes"
|
||||
[customUpload]="true"
|
||||
[multiple]="true" accept=".pdf,.epub"
|
||||
[multiple]="true" accept=".pdf,.epub,.cbz,.cbr,.cb7"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="!selectedLibrary || !selectedPath">
|
||||
@@ -101,7 +101,9 @@
|
||||
<div class="flex items-center justify-center flex-col text-center">
|
||||
<i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl !text-muted-color"></i>
|
||||
<p class="mt-6 mb-2">Drag and drop files here to upload.</p>
|
||||
<p class="mt-2 mb-2">Only <strong>.epub</strong> and <strong>.pdf</strong> files are supported (max size: 100 MB per file).</p>
|
||||
<p class="mt-2 mb-2">
|
||||
Only <strong>.pdf</strong>, <strong>.epub</strong>, <strong>.cbz</strong>, <strong>.cbr</strong>, and <strong>.cb7</strong> files are supported (max size: 100 MB per file).
|
||||
</p>
|
||||
</div>
|
||||
</ng-template>
|
||||
</p-fileupload>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Component, inject} from '@angular/core';
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
|
||||
import {Button} from 'primeng/button';
|
||||
import {AsyncPipe, NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';
|
||||
@@ -14,6 +14,9 @@ import {API_CONFIG} from '../../../config/api-config';
|
||||
import {Book} from '../../../book/model/book.model';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Tooltip} from 'primeng/tooltip';
|
||||
import {AppSettingsService} from '../../../core/service/app-settings.service';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {AppSettings} from '../../../core/model/app-settings.model';
|
||||
|
||||
interface UploadingFile {
|
||||
file: File;
|
||||
@@ -40,7 +43,7 @@ interface UploadingFile {
|
||||
templateUrl: './book-uploader.component.html',
|
||||
styleUrl: './book-uploader.component.scss'
|
||||
})
|
||||
export class BookUploaderComponent {
|
||||
export class BookUploaderComponent implements OnInit {
|
||||
files: UploadingFile[] = [];
|
||||
isUploading: boolean = false;
|
||||
selectedLibrary: Library | null = null;
|
||||
@@ -48,9 +51,23 @@ export class BookUploaderComponent {
|
||||
|
||||
private readonly libraryService = inject(LibraryService);
|
||||
private readonly messageService = inject(MessageService);
|
||||
private readonly appSettingsService = inject(AppSettingsService);
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
maxFileSizeBytes?: number;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$
|
||||
.pipe(
|
||||
filter(settings => settings != null),
|
||||
take(1)
|
||||
)
|
||||
.subscribe(settings => {
|
||||
this.maxFileSizeBytes = (settings?.maxFileUploadSizeInMb ?? 100) * 1024 * 1024;
|
||||
});
|
||||
}
|
||||
|
||||
hasPendingFiles(): boolean {
|
||||
return this.files.some(f => f.status === 'Pending');
|
||||
|
||||
Reference in New Issue
Block a user