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();
}
@PutMapping("/{bookId}/update-last-read")
public ResponseEntity<Book> updateBookViewerSettings(@PathVariable long bookId) {
return ResponseEntity.ok(booksService.updateLastReadTime(bookId));
}
@PostMapping("/assign-shelves")
public ResponseEntity<List<Book>> addBookToShelf(@RequestBody @Valid ShelvesAssignmentRequest request) {
return ResponseEntity.ok(booksService.assignShelvesToBooks(request.getBookIds(), request.getShelvesToAssign(), request.getShelvesToUnassign()));
@@ -13,6 +13,7 @@ import lombok.Data;
public class LibraryFile {
private LibraryEntity libraryEntity;
private LibraryPathEntity libraryPathEntity;
private String fileSubPath;
private String fileName;
private BookFileType bookFileType;
}
@@ -23,6 +23,9 @@ public class BookEntity {
@Column(name = "file_name", length = 1000)
private String fileName;
@Column(name = "file_sub_path")
private String fileSubPath;
@Column(name = "book_type")
private BookFileType bookType;
@@ -24,11 +24,11 @@ public class BookCreatorService {
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
File bookFile = new File(libraryFile.getLibraryPathEntity().getPath() + "/" + libraryFile.getFileName());
BookEntity bookEntity = BookEntity.builder()
.library(libraryFile.getLibraryEntity())
.libraryPath(libraryFile.getLibraryPathEntity())
.fileName(bookFile.getName())
.fileName(libraryFile.getFileName())
.fileSubPath(libraryFile.getFileSubPath())
.bookType(bookFileType)
.addedOn(Instant.now())
.build();
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
@@ -99,7 +100,7 @@ public class BooksService {
public ResponseEntity<byte[]> getBookData(long bookId) throws IOException {
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()
.header(HttpHeaders.CONTENT_TYPE, "application/pdf")
.body(pdfBytes);
@@ -110,12 +111,6 @@ public class BooksService {
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
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
List<BookEntity> bookEntities = bookRepository.findAllById(bookIds);
@@ -158,8 +153,7 @@ public class BooksService {
public ResponseEntity<Resource> prepareFileForDownload(Long bookId) {
try {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
String filePath = bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileName();
Path file = Paths.get(filePath).toAbsolutePath().normalize();
Path file = Paths.get(FileUtils.getBookFullPath(bookEntity)).toAbsolutePath().normalize();
Resource resource = new UrlResource(file.toUri());
String contentType = Files.probeContentType(file);
if (contentType == null) {
@@ -3,6 +3,7 @@ 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.FileUtils;
import lombok.AllArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Service;
@@ -18,7 +19,7 @@ public class EpubService {
public ByteArrayResource getEpubFile(Long bookId) throws IOException {
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();
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.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@@ -20,6 +22,7 @@ import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.Optional;
@RequiredArgsConstructor
@Service
@@ -36,18 +39,19 @@ public class FileUploadService {
private final EpubProcessor epubProcessor;
private final NotificationService notificationService;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) {
validateFile(file);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
LibraryPathEntity libraryPath = libraryEntity.getLibraryPaths()
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
.stream()
.filter(p -> p.getId() == pathId)
.findFirst()
.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();
if (storageFile.exists()) {
@@ -57,7 +61,7 @@ public class FileUploadService {
try {
file.transferTo(storageFile);
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);
log.info("Book processed successfully: {}", book.getMetadata().getTitle());
return book;
@@ -77,16 +81,20 @@ public class FileUploadService {
}
}
private Book processFile(MultipartFile file, LibraryEntity libraryEntity, File storageFile) {
BookFileType fileType = determineFileType(file.getContentType());
private Book processFile(MultipartFile file, LibraryEntity libraryEntity, LibraryPathEntity libraryPathEntity, File storageFile) {
BookFileType fileType = determineFileType(Objects.requireNonNull(file.getContentType()));
if (fileType == null) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
String subPath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), storageFile.toPath());
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
.libraryPathEntity(libraryPathEntity)
.fileSubPath(subPath)
.bookFileType(fileType)
.fileName(storageFile.getAbsolutePath())
.fileName(file.getOriginalFilename())
.build();
switch (fileType) {
@@ -12,6 +12,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -124,15 +125,26 @@ public class LibraryProcessingService {
private List<LibraryFile> findLibraryFiles(LibraryPathEntity libraryPathEntity, LibraryEntity libraryEntity) throws IOException {
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)
.filter(file -> {
String fileName = file.getFileName().toString().toLowerCase();
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
})
.forEach(file -> {
BookFileType fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? BookFileType.PDF : BookFileType.EPUB;
libraryFiles.add(new LibraryFile(libraryEntity, libraryPathEntity, file.toFile().getName(), fileType));
.forEach(fullFilePath -> {
BookFileType fileType = fullFilePath.getFileName().toString().toLowerCase().endsWith(".pdf")
? 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;
@@ -8,6 +8,7 @@ import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
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;
@@ -61,7 +62,7 @@ public class EpubProcessor implements FileProcessor {
protected Book processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
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);
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.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
@@ -54,7 +55,7 @@ public class PdfProcessor implements FileProcessor {
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected Book processNewFile(LibraryFile libraryFile) {
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);
processCover(pdf, bookEntity);
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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,
file_name VARCHAR(255) NOT NULL,
file_sub_path VARCHAR(512) NOT NULL,
book_type VARCHAR(6) NOT NULL,
library_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 {AppSettingsService} from '../../../core/service/app-settings.service';
import {filter, forkJoin, Subscription, take} from 'rxjs';
import {BookSetting, PdfViewerSetting} from '../../model/book.model';
import {BookSetting} from '../../model/book.model';
@Component({
selector: 'app-pdf-viewer',
@@ -65,21 +65,17 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
}
this.isInitialLoad = false;
this.bookData = pdfData;
this.updateLastReadTime();
this.updateProgress();
});
});
});
}
private updateLastReadTime(): void {
this.bookService.updateLastReadTime(this.bookId).subscribe();
}
onPageChange(page: number): void {
if (page !== this.page) {
this.page = page;
this.updateViewerSetting();
}
this.updateProgress();
}
onZoomChange(zoom: string | number): void {
@@ -115,10 +111,14 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
updateProgress() {
this.bookService.savePdfProgress(this.bookId, this.page).subscribe();
}
ngOnDestroy(): void {
this.updateLastReadTime();
if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe();
}
this.updateProgress();
}
}
@@ -98,15 +98,15 @@ export class BookService {
return this.http.put<void>(`${this.url}/${bookId}/book-viewer-setting`, bookSetting);
}
updateLastReadTime(bookId: number): Observable<Book> {
return this.http.put<Book>(`${this.url}/${bookId}/update-last-read`, {}).pipe(
switchMap(updatedBook => {
updateLastReadTime(bookId: number): Observable<void> {
const timestamp = Math.floor(Date.now() / 1000).toString();
return this.http.put<void>(`${this.url}/${bookId}/update-last-read/${timestamp}`, {}).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
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});
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> {
return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, epubProgress: progress});
}
@@ -185,7 +189,7 @@ export class BookService {
handleRemovedBookIds(removedBookIds: number[]): void {
const currentState = this.bookStateSubject.value;
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id)); // Check using includes() method
this.bookStateSubject.next({ ...currentState, books: filteredBooks });
this.bookStateSubject.next({...currentState, books: filteredBooks});
}
handleBookUpdate(updatedBook: Book) {
@@ -35,6 +35,7 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
isSettingsDrawerVisible = false;
private book: any;
private rendition: any;
location: any;
private keyListener: (e: KeyboardEvent) => void = () => {
};
@@ -127,7 +128,6 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.setupKeyListener();
this.trackProgress();
this.updateLastReadTime();
};
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 {
if (this.rendition) {
console.log(this.selectedTheme)
this.rendition.themes.select(this.selectedTheme);
this.rendition.clear();
this.rendition.start();
@@ -204,14 +199,6 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
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 {
if (this.rendition) {
this.rendition.prev();
@@ -227,6 +214,7 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
navigateToChapter(chapter: { label: string; href: string }): void {
if (this.book && chapter.href) {
this.book.rendition.display(chapter.href);
this.trackProgress();
}
}
@@ -238,12 +226,20 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
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 {
if (this.rendition) {
this.rendition.off('keyup', this.keyListener);
}
this.updateLastReadTime();
document.removeEventListener('keyup', this.keyListener);
this.trackProgress();
}
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(', ') : '';
}
coverImageSrc(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
}
onSave(): void {
const updatedBookMetadata: BookMetadata = {
bookId: this.currentBookId,