Remove file name from subpath. Fix progress for pdf.

This commit is contained in:
aditya.chandel
2025-01-19 15:57:08 -07:00
parent 5f7a5f55b4
commit 26b041e409
17 changed files with 98 additions and 62 deletions
@@ -59,11 +59,6 @@ public class BookController {
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@PutMapping("/{bookId}/update-last-read")
public ResponseEntity<Book> updateBookViewerSettings(@PathVariable long bookId) {
return ResponseEntity.ok(booksService.updateLastReadTime(bookId));
}
@PostMapping("/assign-shelves") @PostMapping("/assign-shelves")
public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) { public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) {
return ResponseEntity.ok(booksService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign())); return ResponseEntity.ok(booksService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
@@ -13,6 +13,7 @@ import lombok.Data;
public class LibraryFile { public class LibraryFile {
private LibraryEntity libraryEntity; private LibraryEntity libraryEntity;
private LibraryPathEntity libraryPathEntity; private LibraryPathEntity libraryPathEntity;
private String fileSubPath;
private String fileName; private String fileName;
private BookFileType bookFileType; private BookFileType bookFileType;
} }
@@ -23,6 +23,9 @@ public class BookEntity {
@Column(name = "file_name", length = 1000) @Column(name = "file_name", length = 1000)
private String fileName; private String fileName;
@Column(name = "file_sub_path")
private String fileSubPath;
@Column(name = "book_type") @Column(name = "book_type")
private BookFileType bookType; private BookFileType bookType;
@@ -24,11 +24,11 @@ public class BookCreatorService {
private EpubViewerPreferencesRepository epubViewerPreferencesRepository; private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) { public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
File bookFile = new File(libraryFile.getLibraryPathEntity().getPath() + "/" + libraryFile.getFileName());
BookEntity bookEntity = BookEntity.builder() BookEntity bookEntity = BookEntity.builder()
.library(libraryFile.getLibraryEntity()) .library(libraryFile.getLibraryEntity())
.libraryPath(libraryFile.getLibraryPathEntity()) .libraryPath(libraryFile.getLibraryPathEntity())
.fileName(bookFile.getName()) .fileName(libraryFile.getFileName())
.fileSubPath(libraryFile.getFileSubPath())
.bookType(bookFileType) .bookType(bookFileType)
.addedOn(Instant.now()) .addedOn(Instant.now())
.build(); .build();
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository; import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
import com.adityachandel.booklore.repository.ShelfRepository; import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@@ -99,7 +100,7 @@ public class BooksService {
public ResponseEntity<byte[]> getBookData(long bookId) throws IOException { public ResponseEntity<byte[]> getBookData(long bookId) throws IOException {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
byte[] pdfBytes = Files.readAllBytes(new File(bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileName()).toPath()); byte[] pdfBytes = Files.readAllBytes(new File(FileUtils.getBookFullPath(bookEntity)).toPath());
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/pdf") .header(HttpHeaders.CONTENT_TYPE, "application/pdf")
.body(pdfBytes); .body(pdfBytes);
@@ -110,12 +111,6 @@ public class BooksService {
return bookEntities.stream().map(bookMapper::toBook).toList(); return bookEntities.stream().map(bookMapper::toBook).toList();
} }
public Book updateLastReadTime(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookEntity.setLastReadTime(Instant.now());
return bookMapper.toBook(bookRepository.save(bookEntity));
}
@Transactional @Transactional
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) { public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds); List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
@@ -158,8 +153,7 @@ public class BooksService {
public ResponseEntity<Resource> prepareFileForDownload(Long bookId) { public ResponseEntity<Resource> prepareFileForDownload(Long bookId) {
try { try {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
String filePath = bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileName(); Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
Path file = Paths.get(filePath).toAbsolutePath().normalize();
Resource resource = new UrlResource(file.toUri()); Resource resource = new UrlResource(file.toUri());
String contentType = Files.probeContentType(file); String contentType = Files.probeContentType(file);
if (contentType == null) { if (contentType == null) {
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -18,7 +19,7 @@ public class EpubService {
public ByteArrayResource getEpubFile(Long bookId) throws IOException { public ByteArrayResource getEpubFile(Long bookId) throws IOException {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
try (FileInputStream inputStream = new FileInputStream(bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileName())) { try (FileInputStream inputStream = new FileInputStream(FileUtils.getBookFullPath(bookEntity))) {
byte[] fileContent = inputStream.readAllBytes(); byte[] fileContent = inputStream.readAllBytes();
return new ByteArrayResource(fileContent); return new ByteArrayResource(fileContent);
} }
@@ -10,9 +10,11 @@ import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
@@ -20,6 +22,7 @@ import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
@RequiredArgsConstructor @RequiredArgsConstructor
@Service @Service
@@ -36,18 +39,19 @@ public class FileUploadService {
private final EpubProcessor epubProcessor; private final EpubProcessor epubProcessor;
private final NotificationService notificationService; private final NotificationService notificationService;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) { public Book uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file); validateFile(file);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity libraryPath = libraryEntity.getLibraryPaths() LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
.stream() .stream()
.filter(p -> p.getId() == pathId) .filter(p -> p.getId() == pathId)
.findFirst() .findFirst()
.orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId));
Path storagePath = Paths.get(libraryPath.getPath(), Objects.requireNonNull(file.getOriginalFilename())); Path storagePath = Paths.get(libraryPathEntity.getPath(), Objects.requireNonNull(file.getOriginalFilename()));
File storageFile = storagePath.toFile(); File storageFile = storagePath.toFile();
if (storageFile.exists()) { if (storageFile.exists()) {
@@ -57,7 +61,7 @@ public class FileUploadService {
try { try {
file.transferTo(storageFile); file.transferTo(storageFile);
log.info("File uploaded successfully: {}", storageFile.getAbsolutePath()); log.info("File uploaded successfully: {}", storageFile.getAbsolutePath());
Book book = processFile(file, libraryEntity, storageFile); Book book = processFile(file, libraryEntity, libraryPathEntity, storageFile);
notificationService.sendMessage(Topic.BOOK_ADD, book); notificationService.sendMessage(Topic.BOOK_ADD, book);
log.info("Book processed successfully: {}", book.getMetadata().getTitle()); log.info("Book processed successfully: {}", book.getMetadata().getTitle());
return book; return book;
@@ -77,16 +81,20 @@ public class FileUploadService {
} }
} }
private Book processFile(MultipartFile file, LibraryEntity libraryEntity, File storageFile) { private Book processFile(MultipartFile file, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile) {
BookFileType fileType = determineFileType(file.getContentType()); BookFileType fileType = determineFileType(Objects.requireNonNull(file.getContentType()));
if (fileType == null) { if (fileType == null) {
throw ApiError.INVALID_FILE_FORMAT.createException(); throw ApiError.INVALID_FILE_FORMAT.createException();
} }
String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath());
LibraryFile libraryFile = LibraryFile.builder() LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity) .libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(subPath)
.bookFileType(fileType) .bookFileType(fileType)
.fileName(storageFile.getAbsolutePath()) .fileName(file.getOriginalFilename())
.build(); .build();
switch (fileType) { switch (fileType) {
@@ -12,6 +12,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository; import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor; import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor; import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -124,15 +125,26 @@ public class LibraryProcessingService {
private List<LibraryFile> findLibraryFiles(LibraryPathEntity libraryPathEntity, LibraryEntity libraryEntity) throws IOException { private List<LibraryFile> findLibraryFiles(LibraryPathEntity libraryPathEntity, LibraryEntity libraryEntity) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>(); List<LibraryFile> libraryFiles = new ArrayList<>();
try (var stream = Files.walk(Path.of(libraryPathEntity.getPath()))) { Path libraryPath = Path.of(libraryPathEntity.getPath());
try (var stream = Files.walk(libraryPath)) {
stream.filter(Files::isRegularFile) stream.filter(Files::isRegularFile)
.filter(file -> { .filter(file -> {
String fileName = file.getFileName().toString().toLowerCase(); String fileName = file.getFileName().toString().toLowerCase();
return fileName.endsWith(".pdf") || fileName.endsWith(".epub"); return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
}) })
.forEach(file -> { .forEach(fullFilePath -> {
BookFileType fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? BookFileType.PDF : BookFileType.EPUB; BookFileType fileType = fullFilePath.getFileName().toString().toLowerCase().endsWith(".pdf")
libraryFiles.add(new LibraryFile(libraryEntity, libraryPathEntity, file.toFile().getName(), fileType)); ? BookFileType.PDF
: BookFileType.EPUB;
String relativePath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), fullFilePath);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(relativePath)
.fileName(fullFilePath.getFileName().toString())
.bookFileType(fileType)
.build();
libraryFiles.add(libraryFile);
}); });
} }
return libraryFiles; return libraryFiles;
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService; import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.util.FileUtils;
import io.documentnode.epub4j.domain.Identifier; import io.documentnode.epub4j.domain.Identifier;
import io.documentnode.epub4j.domain.Metadata; import io.documentnode.epub4j.domain.Metadata;
import io.documentnode.epub4j.domain.Resource; import io.documentnode.epub4j.domain.Resource;
@@ -61,7 +62,7 @@ public class EpubProcessor implements FileProcessor {
protected Book processNewFile(LibraryFile libraryFile) { protected Book processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB); BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
try { try {
io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(libraryFile.getLibraryPathEntity().getPath() + "/" + libraryFile.getFileName())); io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
setBookMetadata(epub, bookEntity); setBookMetadata(epub, bookEntity);
processCover(epub, bookEntity); processCover(epub, bookEntity);
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService; import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader; import org.apache.pdfbox.Loader;
@@ -54,7 +55,7 @@ public class PdfProcessor implements FileProcessor {
@Transactional(propagation = Propagation.REQUIRES_NEW) @Transactional(propagation = Propagation.REQUIRES_NEW)
protected Book processNewFile(LibraryFile libraryFile) { protected Book processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF); BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
try (PDDocument pdf = Loader.loadPDF(new File(libraryFile.getLibraryPathEntity().getPath() + "/" + libraryFile.getFileName()))) { try (PDDocument pdf = Loader.loadPDF(new File(FileUtils.getBookFullPath(bookEntity)))) {
setMetadata(pdf, bookEntity); setMetadata(pdf, bookEntity);
processCover(pdf, bookEntity); processCover(pdf, bookEntity);
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.BookEntity;
import java.nio.file.Path;
import java.util.Optional;
public class FileUtils {
public static String getBookFullPath(BookEntity bookEntity) {
return bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileSubPath() + "/" + bookEntity.getFileName();
}
public static String getRelativeSubPath(String basePath, Path fullFilePath) {
return Optional.ofNullable(Path.of(basePath)
.relativize(fullFilePath)
.getParent())
.map(Path::toString)
.map(path -> path.replace("\\", "/"))
.orElse("");
}
}
@@ -18,6 +18,7 @@ CREATE TABLE IF NOT EXISTS book
( (
id BIGINT AUTO_INCREMENT PRIMARY KEY, id BIGINT AUTO_INCREMENT PRIMARY KEY,
file_name VARCHAR(255) NOT NULL, file_name VARCHAR(255) NOT NULL,
file_sub_path VARCHAR(512) NOT NULL,
book_type VARCHAR(6) NOT NULL, book_type VARCHAR(6) NOT NULL,
library_id BIGINT NOT NULL, library_id BIGINT NOT NULL,
library_path_id BIGINT NOT NULL, library_path_id BIGINT NOT NULL,
@@ -4,7 +4,7 @@ import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewe
import {BookService} from '../../service/book.service'; import {BookService} from '../../service/book.service';
import {AppSettingsService} from '../../../core/service/app-settings.service'; import {AppSettingsService} from '../../../core/service/app-settings.service';
import {filter, forkJoin, Subscription, take} from 'rxjs'; import {filter, forkJoin, Subscription, take} from 'rxjs';
import {BookSetting, PdfViewerSetting} from '../../model/book.model'; import {BookSetting} from '../../model/book.model';
@Component({ @Component({
selector: 'app-pdf-viewer', selector: 'app-pdf-viewer',
@@ -65,21 +65,17 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
} }
this.isInitialLoad = false; this.isInitialLoad = false;
this.bookData = pdfData; this.bookData = pdfData;
this.updateLastReadTime(); this.updateProgress();
}); });
}); });
}); });
} }
private updateLastReadTime(): void {
this.bookService.updateLastReadTime(this.bookId).subscribe();
}
onPageChange(page: number): void { onPageChange(page: number): void {
if (page !== this.page) { if (page !== this.page) {
this.page = page; this.page = page;
this.updateViewerSetting();
} }
this.updateProgress();
} }
onZoomChange(zoom: string | number): void { onZoomChange(zoom: string | number): void {
@@ -115,10 +111,14 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe(); this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
} }
updateProgress() {
this.bookService.savePdfProgress(this.bookId, this.page).subscribe();
}
ngOnDestroy(): void { ngOnDestroy(): void {
this.updateLastReadTime();
if (this.appSettingsSubscription) { if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe(); this.appSettingsSubscription.unsubscribe();
} }
this.updateProgress();
} }
} }
@@ -98,15 +98,15 @@ export class BookService {
return this.http.put<void>(`${this.url}/${bookId}/book-viewer-setting`, bookSetting); return this.http.put<void>(`${this.url}/${bookId}/book-viewer-setting`, bookSetting);
} }
updateLastReadTime(bookId: number): Observable<Book> { updateLastReadTime(bookId: number): Observable<void> {
return this.http.put<Book>(`${this.url}/${bookId}/update-last-read`, {}).pipe( const timestamp = Math.floor(Date.now() / 1000).toString();
switchMap(updatedBook => { return this.http.put<void>(`${this.url}/${bookId}/update-last-read/${timestamp}`, {}).pipe(
tap(() => {
const currentState = this.bookStateSubject.value; const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => const updatedBooks = (currentState.books || []).map(book =>
book.id === updatedBook.id ? {...book, lastReadTime: updatedBook.lastReadTime} : book book.id === bookId ? {...book, lastReadTime: timestamp} : book
); );
this.bookStateSubject.next({...currentState, books: updatedBooks}); this.bookStateSubject.next({...currentState, books: updatedBooks});
return [updatedBook];
}) })
); );
} }
@@ -164,6 +164,10 @@ export class BookService {
}); });
} }
savePdfProgress(bookId: number, progress: number): Observable<void> {
return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, pdfProgress: progress});
}
saveEpubProgress(bookId: number, progress: string): Observable<void> { saveEpubProgress(bookId: number, progress: string): Observable<void> {
return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, epubProgress: progress}); return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, epubProgress: progress});
} }
@@ -35,6 +35,7 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
isSettingsDrawerVisible = false; isSettingsDrawerVisible = false;
private book: any; private book: any;
private rendition: any; private rendition: any;
location: any;
private keyListener: (e: KeyboardEvent) => void = () => { private keyListener: (e: KeyboardEvent) => void = () => {
}; };
@@ -127,7 +128,6 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.setupKeyListener(); this.setupKeyListener();
this.trackProgress(); this.trackProgress();
this.updateLastReadTime();
}; };
fileReader.readAsArrayBuffer(epubData); fileReader.readAsArrayBuffer(epubData);
@@ -136,13 +136,8 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
}); });
} }
private updateLastReadTime(): void {
this.bookService.updateLastReadTime(this.epub.id).subscribe();
}
changeThemes(): void { changeThemes(): void {
if (this.rendition) { if (this.rendition) {
console.log(this.selectedTheme)
this.rendition.themes.select(this.selectedTheme); this.rendition.themes.select(this.selectedTheme);
this.rendition.clear(); this.rendition.clear();
this.rendition.start(); this.rendition.start();
@@ -204,14 +199,6 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
document.addEventListener('keyup', this.keyListener); document.addEventListener('keyup', this.keyListener);
} }
private trackProgress(): void {
if (this.rendition) {
this.rendition.on('relocated', (location: any) => {
this.bookService.saveEpubProgress(this.epub.id, location.start.cfi).subscribe();
});
}
}
prevPage(): void { prevPage(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.prev(); this.rendition.prev();
@@ -227,6 +214,7 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
navigateToChapter(chapter: { label: string; href: string }): void { navigateToChapter(chapter: { label: string; href: string }): void {
if (this.book && chapter.href) { if (this.book && chapter.href) {
this.book.rendition.display(chapter.href); this.book.rendition.display(chapter.href);
this.trackProgress();
} }
} }
@@ -238,12 +226,20 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible; this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible;
} }
private trackProgress(): void {
if (this.rendition) {
this.rendition.on('relocated', (location: any) => {
this.bookService.saveEpubProgress(this.epub.id, location.start.cfi).subscribe();
});
}
}
ngOnDestroy(): void { ngOnDestroy(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.off('keyup', this.keyListener); this.rendition.off('keyup', this.keyListener);
} }
this.updateLastReadTime();
document.removeEventListener('keyup', this.keyListener); document.removeEventListener('keyup', this.keyListener);
this.trackProgress();
} }
themesMap = new Map<string, any>([ themesMap = new Map<string, any>([
@@ -101,10 +101,6 @@ export class MetadataPickerComponent implements OnInit {
return this.fetchedMetadata.categories ? this.fetchedMetadata.categories.map(category => category).join(', ') : ''; return this.fetchedMetadata.categories ? this.fetchedMetadata.categories.map(category => category).join(', ') : '';
} }
coverImageSrc(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
}
onSave(): void { onSave(): void {
const updatedBookMetadata: BookMetadata = { const updatedBookMetadata: BookMetadata = {
bookId: this.currentBookId, bookId: this.currentBookId,