Build a lazy-loading PDF viewer for large files
This commit is contained in:
committed by
aditya.chandel
parent
e8a8e0d64c
commit
0e808df1df
+2
-1
@@ -52,7 +52,8 @@ public class SecurityConfig {
|
|||||||
"/api/v1/setup",
|
"/api/v1/setup",
|
||||||
"/api/v1/setup/**",
|
"/api/v1/setup/**",
|
||||||
"/api/v1/opds/*/cover.jpg",
|
"/api/v1/opds/*/cover.jpg",
|
||||||
"/api/v1/cbx/*/pages/*"
|
"/api/v1/cbx/*/pages/*",
|
||||||
|
"/api/v1/pdf/*/pages/*"
|
||||||
).permitAll()
|
).permitAll()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
)
|
)
|
||||||
|
|||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package com.adityachandel.booklore.controller;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.service.CbxReaderService;
|
||||||
|
import com.adityachandel.booklore.service.PdfReaderService;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/v1/pdf")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PdfReaderController {
|
||||||
|
|
||||||
|
private final PdfReaderService pdfReaderService;
|
||||||
|
|
||||||
|
@GetMapping("/{bookId}/pages")
|
||||||
|
public List<Integer> listPages(@PathVariable Long bookId) throws IOException {
|
||||||
|
return pdfReaderService.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);
|
||||||
|
pdfReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
@@ -64,6 +64,10 @@ public class BookLoreUserTransformer {
|
|||||||
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
|
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
|
||||||
userSettings.setCbxReaderSetting(value);
|
userSettings.setCbxReaderSetting(value);
|
||||||
}
|
}
|
||||||
|
case NEW_PDF_READER_SETTING -> {
|
||||||
|
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.NewPdfReaderSetting.class);
|
||||||
|
userSettings.setNewPdfReaderSetting(value);
|
||||||
|
}
|
||||||
case SIDEBAR_LIBRARY_SORTING -> {
|
case SIDEBAR_LIBRARY_SORTING -> {
|
||||||
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
|
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
|
||||||
userSettings.setSidebarLibrarySorting(value);
|
userSettings.setSidebarLibrarySorting(value);
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package com.adityachandel.booklore.model.dto;
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
||||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
import com.adityachandel.booklore.model.enums.*;
|
||||||
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
|
|
||||||
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
|
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
@@ -37,6 +35,7 @@ public class BookLoreUser {
|
|||||||
public static class UserSettings {
|
public static class UserSettings {
|
||||||
public PerBookSetting perBookSetting;
|
public PerBookSetting perBookSetting;
|
||||||
public PdfReaderSetting pdfReaderSetting;
|
public PdfReaderSetting pdfReaderSetting;
|
||||||
|
public NewPdfReaderSetting newPdfReaderSetting;
|
||||||
public EpubReaderSetting epubReaderSetting;
|
public EpubReaderSetting epubReaderSetting;
|
||||||
public CbxReaderSetting cbxReaderSetting;
|
public CbxReaderSetting cbxReaderSetting;
|
||||||
public SidebarSortOption sidebarLibrarySorting;
|
public SidebarSortOption sidebarLibrarySorting;
|
||||||
@@ -111,6 +110,15 @@ public class BookLoreUser {
|
|||||||
private CbxPageViewMode pageViewMode;
|
private CbxPageViewMode pageViewMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
public static class NewPdfReaderSetting {
|
||||||
|
private NewPdfPageSpread pageSpread;
|
||||||
|
private NewPdfPageViewMode pageViewMode;
|
||||||
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Builder
|
@Builder
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
|||||||
+1
@@ -7,6 +7,7 @@ import lombok.Data;
|
|||||||
@Data
|
@Data
|
||||||
public class BookViewerSettings {
|
public class BookViewerSettings {
|
||||||
private PdfViewerPreferences pdfSettings;
|
private PdfViewerPreferences pdfSettings;
|
||||||
|
private NewPdfViewerPreferences newPdfSettings;
|
||||||
private EpubViewerPreferences epubSettings;
|
private EpubViewerPreferences epubSettings;
|
||||||
private CbxViewerPreferences cbxSettings;
|
private CbxViewerPreferences cbxSettings;
|
||||||
}
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.enums.NewPdfPageViewMode;
|
||||||
|
import com.adityachandel.booklore.model.enums.NewPdfPageSpread;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
public class NewPdfViewerPreferences {
|
||||||
|
private Long bookId;
|
||||||
|
private NewPdfPageSpread pageSpread;
|
||||||
|
private NewPdfPageViewMode pageViewMode;
|
||||||
|
}
|
||||||
+1
@@ -18,6 +18,7 @@ public enum AppSettingKey {
|
|||||||
OPDS_SERVER_ENABLED("opds_server_enabled", false),
|
OPDS_SERVER_ENABLED("opds_server_enabled", false),
|
||||||
OIDC_ENABLED("oidc_enabled", false),
|
OIDC_ENABLED("oidc_enabled", false),
|
||||||
CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false),
|
CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false),
|
||||||
|
PDF_CACHE_SIZE_IN_MB("pdf_cache_size_in_mb", false),
|
||||||
MAX_FILE_UPLOAD_SIZE_IN_MB("max_file_upload_size_in_mb", false);
|
MAX_FILE_UPLOAD_SIZE_IN_MB("max_file_upload_size_in_mb", false);
|
||||||
|
|
||||||
private final String dbKey;
|
private final String dbKey;
|
||||||
|
|||||||
+1
@@ -18,6 +18,7 @@ public class AppSettings {
|
|||||||
private boolean opdsServerEnabled;
|
private boolean opdsServerEnabled;
|
||||||
private String uploadPattern;
|
private String uploadPattern;
|
||||||
private Integer cbxCacheSizeInMb;
|
private Integer cbxCacheSizeInMb;
|
||||||
|
private Integer pdfCacheSizeInMb;
|
||||||
private Integer maxFileUploadSizeInMb;
|
private Integer maxFileUploadSizeInMb;
|
||||||
|
|
||||||
private boolean remoteAuthEnabled;
|
private boolean remoteAuthEnabled;
|
||||||
|
|||||||
+1
@@ -6,6 +6,7 @@ import lombok.Getter;
|
|||||||
public enum UserSettingKey {
|
public enum UserSettingKey {
|
||||||
PER_BOOK_SETTING("perBookSetting", true),
|
PER_BOOK_SETTING("perBookSetting", true),
|
||||||
PDF_READER_SETTING("pdfReaderSetting", true),
|
PDF_READER_SETTING("pdfReaderSetting", true),
|
||||||
|
NEW_PDF_READER_SETTING("newPdfReaderSetting", true),
|
||||||
EPUB_READER_SETTING("epubReaderSetting", true),
|
EPUB_READER_SETTING("epubReaderSetting", true),
|
||||||
CBX_READER_SETTING("cbxReaderSetting", true),
|
CBX_READER_SETTING("cbxReaderSetting", true),
|
||||||
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
||||||
|
|||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
package com.adityachandel.booklore.model.entity;
|
||||||
|
|
||||||
|
import com.adityachandel.booklore.model.enums.NewPdfPageSpread;
|
||||||
|
import com.adityachandel.booklore.model.enums.NewPdfPageViewMode;
|
||||||
|
import jakarta.persistence.*;
|
||||||
|
import lombok.*;
|
||||||
|
|
||||||
|
@Entity
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Table(name = "new_pdf_viewer_preference", uniqueConstraints = {
|
||||||
|
@UniqueConstraint(columnNames = {"user_id", "book_id"})
|
||||||
|
})
|
||||||
|
public class NewPdfViewerPreferencesEntity {
|
||||||
|
|
||||||
|
@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 NewPdfPageSpread pageSpread;
|
||||||
|
|
||||||
|
@Column(name = "view_mode")
|
||||||
|
@Enumerated(EnumType.STRING)
|
||||||
|
private NewPdfPageViewMode pageViewMode;
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
package com.adityachandel.booklore.model.enums;
|
||||||
|
|
||||||
|
public enum NewPdfPageSpread {
|
||||||
|
EVEN,
|
||||||
|
ODD
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
package com.adityachandel.booklore.model.enums;
|
||||||
|
|
||||||
|
public enum NewPdfPageViewMode {
|
||||||
|
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.NewPdfViewerPreferencesEntity;
|
||||||
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface NewPdfViewerPreferencesRepository extends JpaRepository<NewPdfViewerPreferencesEntity, Long> {
|
||||||
|
|
||||||
|
Optional<NewPdfViewerPreferencesEntity> findByBookIdAndUserId(long bookId, Long id);
|
||||||
|
}
|
||||||
+42
@@ -110,4 +110,46 @@ public class AppMigrationService {
|
|||||||
|
|
||||||
log.info("Migration '{}' completed. Added CBX setting to {} users and updated PER_BOOK_SETTING for {} users.", migrationKey, updatedCount, perBookUpdatedCount);
|
log.info("Migration '{}' completed. Added CBX setting to {} users and updated PER_BOOK_SETTING for {} users.", migrationKey, updatedCount, perBookUpdatedCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void addNewPdfReaderSettingToExistingUsers(UserRepository userRepository, ObjectMapper objectMapper) {
|
||||||
|
final String migrationKey = "addNewPdfReaderSetting";
|
||||||
|
|
||||||
|
if (migrationRepository.existsById(migrationKey)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<BookLoreUserEntity> users = userRepository.findAll();
|
||||||
|
int updatedCount = 0;
|
||||||
|
AtomicInteger perBookUpdatedCount = new AtomicInteger();
|
||||||
|
|
||||||
|
for (BookLoreUserEntity user : users) {
|
||||||
|
boolean hasNewPdfSetting = user.getSettings().stream().anyMatch(s -> s.getSettingKey().equals(UserSettingKey.NEW_PDF_READER_SETTING.getDbKey()));
|
||||||
|
|
||||||
|
if (!hasNewPdfSetting) {
|
||||||
|
try {
|
||||||
|
UserSettingEntity setting = UserSettingEntity.builder()
|
||||||
|
.user(user)
|
||||||
|
.settingKey(UserSettingKey.NEW_PDF_READER_SETTING.getDbKey())
|
||||||
|
.settingValue(objectMapper.writeValueAsString(userProvisioningService.buildDefaultNewPdfReaderSetting()))
|
||||||
|
.build();
|
||||||
|
user.getSettings().add(setting);
|
||||||
|
updatedCount++;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to create New PDF setting for user {}", user.getUsername(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
userRepository.saveAll(users);
|
||||||
|
|
||||||
|
AppMigrationEntity migration = new AppMigrationEntity();
|
||||||
|
migration.setKey(migrationKey);
|
||||||
|
migration.setExecutedAt(LocalDateTime.now());
|
||||||
|
migration.setDescription("Add New PDF reader setting and update PER_BOOK_SETTING to include CBX for existing users");
|
||||||
|
migrationRepository.save(migration);
|
||||||
|
|
||||||
|
log.info("Migration '{}' completed. Added New PDF setting to {} users and updated PER_BOOK_SETTING for {} users.", migrationKey, updatedCount, perBookUpdatedCount);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,5 +19,6 @@ public class AppMigrationStartup {
|
|||||||
public void runMigrationsOnce() {
|
public void runMigrationsOnce() {
|
||||||
appMigrationService.populateMissingFileSizesOnce();
|
appMigrationService.populateMissingFileSizesOnce();
|
||||||
appMigrationService.addCbxReaderSettingToExistingUsers(userRepository, objectMapper);
|
appMigrationService.addCbxReaderSettingToExistingUsers(userRepository, objectMapper);
|
||||||
|
appMigrationService.addNewPdfReaderSettingToExistingUsers(userRepository, objectMapper);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,6 +79,7 @@ public class AppSettingService {
|
|||||||
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
|
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
|
||||||
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
|
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
|
||||||
builder.cbxCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
|
builder.cbxCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
|
||||||
|
builder.pdfCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.PDF_CACHE_SIZE_IN_MB, "5120")));
|
||||||
builder.maxFileUploadSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
|
builder.maxFileUploadSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
|
||||||
|
|
||||||
return builder.build();
|
return builder.build();
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ public class BooksService {
|
|||||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||||
|
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||||
private final ShelfRepository shelfRepository;
|
private final ShelfRepository shelfRepository;
|
||||||
private final FileService fileService;
|
private final FileService fileService;
|
||||||
private final BookMapper bookMapper;
|
private final BookMapper bookMapper;
|
||||||
@@ -68,6 +69,12 @@ public class BooksService {
|
|||||||
.zoom(pdfPref.getZoom())
|
.zoom(pdfPref.getZoom())
|
||||||
.spread(pdfPref.getSpread())
|
.spread(pdfPref.getSpread())
|
||||||
.build()));
|
.build()));
|
||||||
|
newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||||
|
.ifPresent(pdfPref -> settingsBuilder.newPdfSettings(NewPdfViewerPreferences.builder()
|
||||||
|
.bookId(bookId)
|
||||||
|
.pageViewMode(pdfPref.getPageViewMode())
|
||||||
|
.pageSpread(pdfPref.getPageSpread())
|
||||||
|
.build()));
|
||||||
} else if (bookEntity.getBookType() == BookFileType.CBX) {
|
} else if (bookEntity.getBookType() == BookFileType.CBX) {
|
||||||
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||||
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
|
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
|
||||||
@@ -86,21 +93,35 @@ public class BooksService {
|
|||||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||||
|
|
||||||
if (bookEntity.getBookType() == BookFileType.PDF) {
|
if (bookEntity.getBookType() == BookFileType.PDF) {
|
||||||
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
|
if (bookViewerSettings.getPdfSettings() != null) {
|
||||||
.findByBookIdAndUserId(bookId, user.getId())
|
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
|
||||||
.orElseGet(() -> {
|
.findByBookIdAndUserId(bookId, user.getId())
|
||||||
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
|
.orElseGet(() -> {
|
||||||
.bookId(bookId)
|
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
|
||||||
.userId(user.getId())
|
.bookId(bookId)
|
||||||
.build();
|
.userId(user.getId())
|
||||||
return pdfViewerPreferencesRepository.save(newPrefs);
|
.build();
|
||||||
});
|
return pdfViewerPreferencesRepository.save(newPrefs);
|
||||||
|
});
|
||||||
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
|
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
|
||||||
pdfPrefs.setZoom(pdfSettings.getZoom());
|
pdfPrefs.setZoom(pdfSettings.getZoom());
|
||||||
pdfPrefs.setSpread(pdfSettings.getSpread());
|
pdfPrefs.setSpread(pdfSettings.getSpread());
|
||||||
pdfViewerPreferencesRepository.save(pdfPrefs);
|
pdfViewerPreferencesRepository.save(pdfPrefs);
|
||||||
|
}
|
||||||
|
if (bookViewerSettings.getNewPdfSettings() != null) {
|
||||||
|
NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||||
|
.orElseGet(() -> {
|
||||||
|
NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder()
|
||||||
|
.bookId(bookId)
|
||||||
|
.userId(user.getId())
|
||||||
|
.build();
|
||||||
|
return newPdfViewerPreferencesRepository.save(entity);
|
||||||
|
});
|
||||||
|
NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings();
|
||||||
|
pdfPrefs.setPageSpread(pdfSettings.getPageSpread());
|
||||||
|
pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||||
|
newPdfViewerPreferencesRepository.save(pdfPrefs);
|
||||||
|
}
|
||||||
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
|
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
|
||||||
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
|
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
|
||||||
.findByBookIdAndUserId(bookId, user.getId())
|
.findByBookIdAndUserId(bookId, user.getId())
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
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 lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.apache.pdfbox.Loader;
|
||||||
|
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||||
|
import org.apache.pdfbox.rendering.ImageType;
|
||||||
|
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.imageio.ImageIO;
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import java.io.*;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PdfReaderService {
|
||||||
|
|
||||||
|
private static final String CACHE_INFO_FILENAME = ".cache-info";
|
||||||
|
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
private final AppSettingService appSettingService;
|
||||||
|
private final FileService fileService;
|
||||||
|
|
||||||
|
public List<Integer> getAvailablePages(Long bookId) throws IOException {
|
||||||
|
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
|
||||||
|
|
||||||
|
Path pdfPath = Path.of(bookFullPath);
|
||||||
|
Path cacheDir = Path.of(fileService.getPdfCachePath(), String.valueOf(bookId));
|
||||||
|
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
|
||||||
|
long maxCacheSizeBytes = appSettingService.getAppSettings().getPdfCacheSizeInMb() * 1024L * 1024L;
|
||||||
|
long estimatedSize = Files.size(pdfPath);
|
||||||
|
if (estimatedSize > maxCacheSizeBytes) {
|
||||||
|
log.warn("Cache skipped: Estimated PDF size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
|
||||||
|
throw ApiError.CACHE_TOO_LARGE.createException();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (needsCacheRefresh(pdfPath, cacheInfoPath)) {
|
||||||
|
log.info("Invalidating cache for PDF book {}", bookId);
|
||||||
|
if (Files.exists(cacheDir)) FileUtils.deleteDirectoryRecursively(cacheDir);
|
||||||
|
Files.createDirectories(cacheDir);
|
||||||
|
extractPdfPages(pdfPath, cacheDir);
|
||||||
|
writeCacheInfo(pdfPath, cacheInfoPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Stream<Path> stream = Files.list(cacheDir)) {
|
||||||
|
return stream
|
||||||
|
.filter(p -> p.toString().endsWith(".jpg"))
|
||||||
|
.sorted()
|
||||||
|
.map(p -> extractPageNumber(p.getFileName().toString()))
|
||||||
|
.filter(p -> p != -1)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to extract pages for book {}", bookId, e);
|
||||||
|
throw new UncheckedIOException("Failed to extract pages from PDF for bookId: " + bookId, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
|
||||||
|
Path pagePath = Path.of(fileService.getPdfCachePath(), 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)) {
|
||||||
|
try {
|
||||||
|
in.transferTo(outputStream);
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Error streaming page {} of book {}", page, bookId, e);
|
||||||
|
throw new UncheckedIOException("Failed to stream PDF page image for bookId: " + bookId, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void extractPdfPages(Path pdfPath, Path targetDir) throws IOException {
|
||||||
|
if (!Files.isReadable(pdfPath)) {
|
||||||
|
throw new FileNotFoundException("PDF file is not readable: " + pdfPath);
|
||||||
|
}
|
||||||
|
try (PDDocument document = Loader.loadPDF(new File(pdfPath.toFile().toURI()))) {
|
||||||
|
PDFRenderer renderer = new PDFRenderer(document);
|
||||||
|
for (int i = 0; i < document.getNumberOfPages(); i++) {
|
||||||
|
BufferedImage image = renderer.renderImageWithDPI(i, 200, ImageType.RGB);
|
||||||
|
Path outputFile = targetDir.resolve(String.format("%04d.jpg", i + 1));
|
||||||
|
ImageIO.write(image, "JPEG", outputFile.toFile());
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.error("Failed to render PDF pages from {}", pdfPath, e);
|
||||||
|
throw new UncheckedIOException("Error rendering PDF to images", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean needsCacheRefresh(Path pdfPath, Path cacheInfoPath) throws IOException {
|
||||||
|
if (!Files.exists(cacheInfoPath)) return true;
|
||||||
|
|
||||||
|
long currentLastModified = Files.getLastModifiedTime(pdfPath).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 pdfPath, Path cacheInfoPath) throws IOException {
|
||||||
|
long lastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||||
|
Files.writeString(cacheInfoPath, String.valueOf(lastModified), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int extractPageNumber(String filename) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(filename.replaceAll("\\D+", ""));
|
||||||
|
} catch (Exception e) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-3
@@ -9,9 +9,7 @@ import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
|
|||||||
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
|
||||||
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
|
||||||
import com.adityachandel.booklore.model.entity.*;
|
import com.adityachandel.booklore.model.entity.*;
|
||||||
import com.adityachandel.booklore.model.enums.CbxPageSpread;
|
import com.adityachandel.booklore.model.enums.*;
|
||||||
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.LibraryRepository;
|
||||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||||
import com.adityachandel.booklore.repository.UserRepository;
|
import com.adityachandel.booklore.repository.UserRepository;
|
||||||
@@ -182,6 +180,7 @@ public class UserProvisioningService {
|
|||||||
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
|
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
|
||||||
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
|
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
|
||||||
addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultCbxReaderSetting());
|
addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultCbxReaderSetting());
|
||||||
|
addUserSetting(user, UserSettingKey.NEW_PDF_READER_SETTING, buildDefaultNewPdfReaderSetting());
|
||||||
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
|
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
|
||||||
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
|
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
|
||||||
|
|
||||||
@@ -233,6 +232,14 @@ public class UserProvisioningService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public BookLoreUser.UserSettings.NewPdfReaderSetting buildDefaultNewPdfReaderSetting() {
|
||||||
|
return BookLoreUser.UserSettings.NewPdfReaderSetting.builder()
|
||||||
|
.pageViewMode(NewPdfPageViewMode.SINGLE_PAGE)
|
||||||
|
.pageSpread(NewPdfPageSpread.ODD)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private Object buildDefaultSidebarLibrarySorting() {
|
private Object buildDefaultSidebarLibrarySorting() {
|
||||||
return SidebarSortOption.builder()
|
return SidebarSortOption.builder()
|
||||||
.field("id")
|
.field("id")
|
||||||
|
|||||||
@@ -122,6 +122,10 @@ public class FileService {
|
|||||||
return appProperties.getPathConfig() + "/cbx_cache";
|
return appProperties.getPathConfig() + "/cbx_cache";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getPdfCachePath() {
|
||||||
|
return appProperties.getPathConfig() + "/pdf_cache";
|
||||||
|
}
|
||||||
|
|
||||||
public String getMissingThumbnailPath() {
|
public String getMissingThumbnailPath() {
|
||||||
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
|
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS new_pdf_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)
|
||||||
|
);
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
<div class="comic-reader-container">
|
<div class="comic-reader-container">
|
||||||
<div class="navigation">
|
<div class="navigation">
|
||||||
<div class="goto-page-controls" style="display: flex; align-items: center; margin-right: auto;">
|
<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">
|
<input
|
||||||
|
type="number"
|
||||||
|
[(ngModel)]="goToPageInput"
|
||||||
|
[min]="1"
|
||||||
|
[max]="pages.length"
|
||||||
|
placeholder="Page"
|
||||||
|
/>
|
||||||
<button
|
<button
|
||||||
(click)="goToPageInput !== null && goToPage(goToPageInput)"
|
(click)="goToPageInput !== null && goToPage(goToPageInput)"
|
||||||
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > pages.length">
|
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > pages.length">
|
||||||
@@ -13,7 +19,8 @@
|
|||||||
<button class="mr-2" (click)="goToPage(1)" [disabled]="currentPage === 0"><<</button>
|
<button class="mr-2" (click)="goToPage(1)" [disabled]="currentPage === 0"><<</button>
|
||||||
<button (click)="previousPage()" [disabled]="currentPage === 0"><</button>
|
<button (click)="previousPage()" [disabled]="currentPage === 0"><</button>
|
||||||
<span>
|
<span>
|
||||||
Page {{ currentPage + 1 }}{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
|
Page {{ currentPage + 1 }}
|
||||||
|
{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
|
||||||
</span>
|
</span>
|
||||||
<button (click)="nextPage()" [disabled]="currentPage >= pages.length - 1">></button>
|
<button (click)="nextPage()" [disabled]="currentPage >= pages.length - 1">></button>
|
||||||
<button class="ml-2" (click)="goToPage(pages.length)" [disabled]="currentPage >= pages.length - 1">>></button>
|
<button class="ml-2" (click)="goToPage(pages.length)" [disabled]="currentPage >= pages.length - 1">>></button>
|
||||||
@@ -32,15 +39,16 @@
|
|||||||
<div class="image-container" [class.two-page-view]="isTwoPageView">
|
<div class="image-container" [class.two-page-view]="isTwoPageView">
|
||||||
<ng-container *ngIf="!isLoading; else loading">
|
<ng-container *ngIf="!isLoading; else loading">
|
||||||
<ng-container *ngIf="pages.length > 0; else noPages">
|
<ng-container *ngIf="pages.length > 0; else noPages">
|
||||||
<img *ngFor="let url of imageUrls" [src]="url" alt="Comic Page"/>
|
<img *ngFor="let url of imageUrls" [src]="url" alt="Page Image"/>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
<ng-template #noPages>
|
<ng-template #noPages>
|
||||||
<p>No pages available.</p>
|
<p>No pages available.</p>
|
||||||
</ng-template>
|
</ng-template>
|
||||||
<ng-template #loading>
|
<ng-template #loading>
|
||||||
<div style="display: flex; justify-content: center; align-items: center; height: 100%;">
|
<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%;">
|
||||||
<p-progressSpinner></p-progressSpinner>
|
<p-progressSpinner></p-progressSpinner>
|
||||||
|
<p style="margin-top: 1rem; color: #ccc;">Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.</p>
|
||||||
</div>
|
</div>
|
||||||
</ng-template>
|
</ng-template>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ import {BookService} from '../../service/book.service';
|
|||||||
import {UserService} from '../../../settings/user-management/user.service';
|
import {UserService} from '../../../settings/user-management/user.service';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {forkJoin} from 'rxjs';
|
import {forkJoin} from 'rxjs';
|
||||||
import {BookSetting, CbxPageSpread, CbxPageViewMode} from '../../model/book.model';
|
import {BookSetting, BookType, CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../model/book.model';
|
||||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||||
import {FormsModule} from "@angular/forms";
|
import {FormsModule} from "@angular/forms";
|
||||||
|
import {NewPdfReaderService} from '../../service/new-pdf-reader.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-cbx-reader',
|
selector: 'app-cbx-reader',
|
||||||
@@ -18,20 +19,24 @@ import {FormsModule} from "@angular/forms";
|
|||||||
styleUrl: './cbx-reader.component.scss'
|
styleUrl: './cbx-reader.component.scss'
|
||||||
})
|
})
|
||||||
export class CbxReaderComponent implements OnInit {
|
export class CbxReaderComponent implements OnInit {
|
||||||
|
|
||||||
|
bookType!: BookType;
|
||||||
|
|
||||||
goToPageInput: number | null = null;
|
goToPageInput: number | null = null;
|
||||||
bookId!: number;
|
bookId!: number;
|
||||||
pages: number[] = [];
|
pages: number[] = [];
|
||||||
currentPage = 0;
|
currentPage = 0;
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
|
|
||||||
pageSpread: CbxPageSpread = CbxPageSpread.ODD;
|
pageSpread: CbxPageSpread | PdfPageSpread = CbxPageSpread.ODD;
|
||||||
pageViewMode: CbxPageViewMode = CbxPageViewMode.SINGLE_PAGE;
|
pageViewMode: CbxPageViewMode | PdfPageViewMode = CbxPageViewMode.SINGLE_PAGE;
|
||||||
|
|
||||||
private touchStartX = 0;
|
private touchStartX = 0;
|
||||||
private touchEndX = 0;
|
private touchEndX = 0;
|
||||||
|
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private cbxReaderService = inject(CbxReaderService);
|
private cbxReaderService = inject(CbxReaderService);
|
||||||
|
private pdfReaderService = inject(NewPdfReaderService);
|
||||||
private bookService = inject(BookService);
|
private bookService = inject(BookService);
|
||||||
private userService = inject(UserService);
|
private userService = inject(UserService);
|
||||||
private messageService = inject(MessageService);
|
private messageService = inject(MessageService);
|
||||||
@@ -44,25 +49,54 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
forkJoin([
|
forkJoin([
|
||||||
this.bookService.getBookByIdFromAPI(this.bookId, false),
|
this.bookService.getBookByIdFromAPI(this.bookId, false),
|
||||||
this.bookService.getBookSetting(this.bookId),
|
this.bookService.getBookSetting(this.bookId),
|
||||||
this.userService.getMyself(),
|
this.userService.getMyself()
|
||||||
this.cbxReaderService.getAvailablePages(this.bookId)
|
|
||||||
]).subscribe({
|
]).subscribe({
|
||||||
next: ([cbxMeta, bookSettings, myself, pages]) => {
|
next: ([book, bookSettings, myself]) => {
|
||||||
const userSettings = myself.userSettings;
|
const userSettings = myself.userSettings;
|
||||||
const global = userSettings.perBookSetting.cbx === 'Global';
|
this.bookType = book.bookType;
|
||||||
|
|
||||||
this.pageViewMode = global
|
const pagesObservable = this.bookType === 'PDF'
|
||||||
? userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE
|
? this.pdfReaderService.getAvailablePages(this.bookId)
|
||||||
: bookSettings.cbxSettings?.pageViewMode || userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE;
|
: this.cbxReaderService.getAvailablePages(this.bookId);
|
||||||
|
|
||||||
this.pageSpread = global
|
pagesObservable.subscribe({
|
||||||
? userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD
|
next: (pages) => {
|
||||||
: bookSettings.cbxSettings?.pageSpread || userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD;
|
|
||||||
|
|
||||||
this.pages = pages;
|
this.pages = pages;
|
||||||
this.currentPage = (cbxMeta.cbxProgress?.page || 1) - 1;
|
if (this.bookType === 'CBX') {
|
||||||
this.alignCurrentPageToParity();
|
const global = userSettings.perBookSetting.cbx === 'Global';
|
||||||
this.isLoading = false;
|
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.currentPage = (book.cbxProgress?.page || 1) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.bookType === 'PDF') {
|
||||||
|
const global = userSettings.perBookSetting.pdf === 'Global';
|
||||||
|
this.pageViewMode = global
|
||||||
|
? userSettings.newPdfReaderSetting.pageViewMode || PdfPageViewMode.SINGLE_PAGE
|
||||||
|
: bookSettings.newPdfSettings?.pageViewMode || userSettings.newPdfReaderSetting.pageViewMode || PdfPageViewMode.SINGLE_PAGE;
|
||||||
|
|
||||||
|
this.pageSpread = global
|
||||||
|
? userSettings.newPdfReaderSetting.pageSpread || PdfPageSpread.ODD
|
||||||
|
: bookSettings.newPdfSettings?.pageSpread || userSettings.newPdfReaderSetting.pageSpread || PdfPageSpread.ODD;
|
||||||
|
|
||||||
|
this.currentPage = (book.pdfProgress?.page || 1) - 1;
|
||||||
|
}
|
||||||
|
this.alignCurrentPageToParity();
|
||||||
|
this.isLoading = false;
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
const errorMessage = err?.error?.message || 'Failed to load pages';
|
||||||
|
this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
|
||||||
|
this.isLoading = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
},
|
},
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
const errorMessage = err?.error?.message || 'Failed to load the book';
|
const errorMessage = err?.error?.message || 'Failed to load the book';
|
||||||
@@ -74,18 +108,22 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get isTwoPageView(): boolean {
|
get isTwoPageView(): boolean {
|
||||||
return this.pageViewMode === CbxPageViewMode.TWO_PAGE;
|
return this.pageViewMode === CbxPageViewMode.TWO_PAGE || this.pageViewMode === PdfPageViewMode.TWO_PAGE;
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleView() {
|
toggleView() {
|
||||||
if (!this.isTwoPageView && this.isPhonePortrait()) return;
|
if (!this.isTwoPageView && this.isPhonePortrait()) return;
|
||||||
this.pageViewMode = this.isTwoPageView ? CbxPageViewMode.SINGLE_PAGE : CbxPageViewMode.TWO_PAGE;
|
this.pageViewMode = this.isTwoPageView ? (this.bookType === "CBX" ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE) : (this.bookType === "CBX" ? CbxPageViewMode.TWO_PAGE : PdfPageViewMode.TWO_PAGE);
|
||||||
this.alignCurrentPageToParity();
|
this.alignCurrentPageToParity();
|
||||||
this.updateViewerSetting();
|
this.updateViewerSetting();
|
||||||
}
|
}
|
||||||
|
|
||||||
toggleSpreadDirection() {
|
toggleSpreadDirection() {
|
||||||
this.pageSpread = this.pageSpread === CbxPageSpread.ODD ? CbxPageSpread.EVEN : CbxPageSpread.ODD;
|
if (this.pageSpread === CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD) {
|
||||||
|
this.pageSpread = this.bookType === "CBX" ? CbxPageSpread.EVEN : PdfPageSpread.EVEN;
|
||||||
|
} else {
|
||||||
|
this.pageSpread = this.bookType === "CBX" ? CbxPageSpread.ODD : PdfPageSpread.ODD;
|
||||||
|
}
|
||||||
this.alignCurrentPageToParity();
|
this.alignCurrentPageToParity();
|
||||||
this.updateViewerSetting();
|
this.updateViewerSetting();
|
||||||
}
|
}
|
||||||
@@ -120,7 +158,7 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
private alignCurrentPageToParity() {
|
private alignCurrentPageToParity() {
|
||||||
if (!this.pages.length || !this.isTwoPageView) return;
|
if (!this.pages.length || !this.isTwoPageView) return;
|
||||||
|
|
||||||
const desiredOdd = this.pageSpread === CbxPageSpread.ODD;
|
const desiredOdd = this.pageSpread === CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD;
|
||||||
for (let i = this.currentPage; i >= 0; i--) {
|
for (let i = this.currentPage; i >= 0; i--) {
|
||||||
if ((this.pages[i] % 2 === 1) === desiredOdd) {
|
if ((this.pages[i] % 2 === 1) === desiredOdd) {
|
||||||
this.currentPage = i;
|
this.currentPage = i;
|
||||||
@@ -166,7 +204,7 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
|
|
||||||
private enforcePortraitSinglePageView() {
|
private enforcePortraitSinglePageView() {
|
||||||
if (this.isPhonePortrait() && this.isTwoPageView) {
|
if (this.isPhonePortrait() && this.isTwoPageView) {
|
||||||
this.pageViewMode = CbxPageViewMode.SINGLE_PAGE;
|
this.pageViewMode = this.bookType === "CBX" ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE;
|
||||||
this.updateViewerSetting();
|
this.updateViewerSetting();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -175,24 +213,37 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
|
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getPageImageUrl(pageIndex: number): string {
|
||||||
|
return this.bookType === 'PDF'
|
||||||
|
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex])
|
||||||
|
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]);
|
||||||
|
}
|
||||||
|
|
||||||
get imageUrls(): string[] {
|
get imageUrls(): string[] {
|
||||||
if (!this.pages.length) return [];
|
if (!this.pages.length) return [];
|
||||||
|
|
||||||
const urls = [this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage])];
|
const urls = [this.getPageImageUrl(this.currentPage)];
|
||||||
if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
|
if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
|
||||||
urls.push(this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage + 1]));
|
urls.push(this.getPageImageUrl(this.currentPage + 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
return urls;
|
return urls;
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateViewerSetting(): void {
|
private updateViewerSetting(): void {
|
||||||
const bookSetting: BookSetting = {
|
const bookSetting: BookSetting = this.bookType === "CBX"
|
||||||
cbxSettings: {
|
? {
|
||||||
pageSpread: this.pageSpread,
|
cbxSettings: {
|
||||||
pageViewMode: this.pageViewMode,
|
pageSpread: this.pageSpread as CbxPageSpread,
|
||||||
}
|
pageViewMode: this.pageViewMode as CbxPageViewMode,
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
newPdfSettings: {
|
||||||
|
pageSpread: this.pageSpread as PdfPageSpread,
|
||||||
|
pageViewMode: this.pageViewMode as PdfPageViewMode,
|
||||||
|
}
|
||||||
|
};
|
||||||
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
|
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,7 +252,12 @@ export class CbxReaderComponent implements OnInit {
|
|||||||
? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
|
? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
|
||||||
: 0;
|
: 0;
|
||||||
|
|
||||||
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
if(this.bookType === 'CBX') {
|
||||||
|
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
||||||
|
}
|
||||||
|
if(this.bookType === 'PDF') {
|
||||||
|
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
goToPage(page: number): void {
|
goToPage(page: number): void {
|
||||||
if (page < 1 || page > this.pages.length) return;
|
if (page < 1 || page > this.pages.length) return;
|
||||||
|
|||||||
+1
-1
@@ -129,7 +129,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div *ngIf="userService.userState$ | async as userData" class="pl-6 pt-4 flex flex-row w-full gap-4">
|
<div *ngIf="userService.userState$ | async as userData" class="pl-6 pt-4 flex flex-row w-full gap-4">
|
||||||
<p-button label="Read" icon="pi pi-book" severity="info" (onClick)="read(metadata.bookId)"></p-button>
|
<p-splitbutton label="Read" icon="pi pi-book" [model]="readMenuItems" (onClick)="read(metadata.bookId, 'ngx')" severity="info"/>
|
||||||
<p-button label="Assign Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(metadata.bookId)"></p-button>
|
<p-button label="Assign Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(metadata.bookId)"></p-button>
|
||||||
<p-button *ngIf="userData.permissions.canDownload || userData.permissions.admin" label="Download" icon="pi pi-download" severity="info" outlined
|
<p-button *ngIf="userData.permissions.canDownload || userData.permissions.admin" label="Download" icon="pi pi-download" severity="info" outlined
|
||||||
(onClick)="download(metadata.bookId)"></p-button>
|
(onClick)="download(metadata.bookId)"></p-button>
|
||||||
|
|||||||
+12
-2
@@ -54,6 +54,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
|||||||
|
|
||||||
metadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
|
metadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
|
||||||
emailMenuItems: MenuItem[] | undefined;
|
emailMenuItems: MenuItem[] | undefined;
|
||||||
|
readMenuItems: MenuItem[] | undefined;
|
||||||
refreshMenuItems: MenuItem[] | undefined;
|
refreshMenuItems: MenuItem[] | undefined;
|
||||||
bookInSeries: Book[] = [];
|
bookInSeries: Book[] = [];
|
||||||
isExpanded = false;
|
isExpanded = false;
|
||||||
@@ -102,6 +103,15 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
this.readMenuItems = [
|
||||||
|
{
|
||||||
|
label: 'Streaming Reader',
|
||||||
|
command: () => {
|
||||||
|
this.read(this.book?.id, "streaming")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
this.metadata$
|
this.metadata$
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
.subscribe((metadata) => {
|
.subscribe((metadata) => {
|
||||||
@@ -144,8 +154,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
|
|||||||
this.isExpanded = !this.isExpanded;
|
this.isExpanded = !this.isExpanded;
|
||||||
}
|
}
|
||||||
|
|
||||||
read(bookId: number): void {
|
read(bookId: number | undefined, reader: "ngx" | "streaming"): void {
|
||||||
this.bookService.readBook(bookId);
|
this.bookService.readPdf(bookId!, reader);
|
||||||
}
|
}
|
||||||
|
|
||||||
getAuthorNames(authors: string[]): string {
|
getAuthorNames(authors: string[]): string {
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {Shelf} from './shelf.model';
|
import {Shelf} from './shelf.model';
|
||||||
|
import {NewPdfReaderSetting} from '../../settings/user-management/user.service';
|
||||||
|
|
||||||
export type BookType = "PDF" | "EPUB" | "CBX";
|
export type BookType = "PDF" | "EPUB" | "CBX";
|
||||||
|
|
||||||
@@ -121,6 +122,7 @@ export interface BookSetting {
|
|||||||
pdfSettings?: PdfViewerSetting;
|
pdfSettings?: PdfViewerSetting;
|
||||||
epubSettings?: EpubViewerSetting;
|
epubSettings?: EpubViewerSetting;
|
||||||
cbxSettings?: CbxViewerSetting;
|
cbxSettings?: CbxViewerSetting;
|
||||||
|
newPdfSettings?: NewPdfReaderSetting;
|
||||||
|
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
@@ -139,3 +141,13 @@ export const enum CbxPageSpread {
|
|||||||
EVEN = 'EVEN',
|
EVEN = 'EVEN',
|
||||||
ODD = 'ODD',
|
ODD = 'ODD',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const enum PdfPageViewMode {
|
||||||
|
SINGLE_PAGE = 'SINGLE_PAGE',
|
||||||
|
TWO_PAGE = 'TWO_PAGE',
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enum PdfPageSpread {
|
||||||
|
EVEN = 'EVEN',
|
||||||
|
ODD = 'ODD',
|
||||||
|
}
|
||||||
|
|||||||
@@ -116,6 +116,25 @@ export class BookService {
|
|||||||
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
readPdf(bookId: number, reader: "ngx" | "streaming") {
|
||||||
|
const currentBooks = this.bookStateSubject.value.books;
|
||||||
|
const book = currentBooks?.find(book => book.id === bookId);
|
||||||
|
if (book) {
|
||||||
|
if (book.bookType === "PDF") {
|
||||||
|
if (reader === "ngx") {
|
||||||
|
const url = `/pdf-viewer/book/${book.id}`;
|
||||||
|
window.open(url, '_blank');
|
||||||
|
} else {
|
||||||
|
const url = `/cbx-viewer/book/${book.id}`;
|
||||||
|
window.open(url, '_blank');
|
||||||
|
}
|
||||||
|
this.updateLastReadTime(book.id);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.error('Book not found');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
readBook(bookId: number): void {
|
readBook(bookId: number): void {
|
||||||
const currentBooks = this.bookStateSubject.value.books;
|
const currentBooks = this.bookStateSubject.value.books;
|
||||||
const book = currentBooks?.find(book => book.id === bookId);
|
const book = currentBooks?.find(book => book.id === bookId);
|
||||||
@@ -377,9 +396,9 @@ export class BookService {
|
|||||||
const currentState = this.bookStateSubject.value;
|
const currentState = this.bookStateSubject.value;
|
||||||
const updatedBooks = (currentState.books || []).map(book => {
|
const updatedBooks = (currentState.books || []).map(book => {
|
||||||
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
|
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
|
||||||
return updatedMetadata ? { ...book, metadata: updatedMetadata } : book;
|
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
|
||||||
});
|
});
|
||||||
this.bookStateSubject.next({ ...currentState, books: updatedBooks });
|
this.bookStateSubject.next({...currentState, books: updatedBooks});
|
||||||
}),
|
}),
|
||||||
map(() => void 0),
|
map(() => void 0),
|
||||||
catchError((error) => {
|
catchError((error) => {
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { Injectable } from '@angular/core';
|
||||||
|
import {API_CONFIG} from '../../config/api-config';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class NewPdfReaderService {
|
||||||
|
|
||||||
|
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/pdf`;
|
||||||
|
|
||||||
|
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}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,7 @@ import {API_CONFIG} from '../../config/api-config';
|
|||||||
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
|
||||||
import {Library} from '../../book/model/library.model';
|
import {Library} from '../../book/model/library.model';
|
||||||
import {catchError} from 'rxjs/operators';
|
import {catchError} from 'rxjs/operators';
|
||||||
import {CbxPageSpread, CbxPageViewMode} from '../../book/model/book.model';
|
import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model';
|
||||||
|
|
||||||
export interface EntityViewPreferences {
|
export interface EntityViewPreferences {
|
||||||
global: EntityViewPreference;
|
global: EntityViewPreference;
|
||||||
@@ -60,11 +60,17 @@ export interface CbxReaderSetting {
|
|||||||
pageViewMode: CbxPageViewMode;
|
pageViewMode: CbxPageViewMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface NewPdfReaderSetting {
|
||||||
|
pageSpread: PdfPageSpread;
|
||||||
|
pageViewMode: PdfPageViewMode;
|
||||||
|
}
|
||||||
|
|
||||||
export interface UserSettings {
|
export interface UserSettings {
|
||||||
perBookSetting: PerBookSetting;
|
perBookSetting: PerBookSetting;
|
||||||
pdfReaderSetting: PdfReaderSetting;
|
pdfReaderSetting: PdfReaderSetting;
|
||||||
epubReaderSetting: EpubReaderSetting;
|
epubReaderSetting: EpubReaderSetting;
|
||||||
cbxReaderSetting: CbxReaderSetting;
|
cbxReaderSetting: CbxReaderSetting;
|
||||||
|
newPdfReaderSetting: NewPdfReaderSetting;
|
||||||
sidebarLibrarySorting: SidebarLibrarySorting;
|
sidebarLibrarySorting: SidebarLibrarySorting;
|
||||||
sidebarShelfSorting: SidebarShelfSorting;
|
sidebarShelfSorting: SidebarShelfSorting;
|
||||||
entityViewPreferences: EntityViewPreferences;
|
entityViewPreferences: EntityViewPreferences;
|
||||||
|
|||||||
Reference in New Issue
Block a user