Display the file size in the book metadata details section

* Display the file size in the Book Metadata details section

- Implement AppMigration feature
- Populate missing file sizes for books with null file size in 'populateFileSizes' migration

---------

Co-authored-by: adityachandelgit
This commit is contained in:
Aditya Chandel
2025-04-25 13:55:15 -06:00
committed by GitHub
co-authored by adityachandelgit
parent 285bc83a98
commit 2df8e193cc
16 changed files with 176 additions and 20 deletions
@@ -15,6 +15,7 @@ public class Book {
private Long libraryId;
private String fileName;
private String filePath;
private Long fileSizeKb;
private String title;
private Instant lastReadTime;
private Instant addedOn;
@@ -7,6 +7,9 @@ import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.nio.file.Path;
import java.nio.file.Paths;
@Builder
@Data
@AllArgsConstructor
@@ -16,4 +19,8 @@ public class LibraryFile {
private String fileSubPath;
private String fileName;
private BookFileType bookFileType;
public Path getFullPath() {
return Paths.get(libraryPathEntity.getPath(), fileSubPath, fileName);
}
}
@@ -0,0 +1,27 @@
package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "app_migration")
public class AppMigrationEntity {
@Id
@Column(name = "migration_key", nullable = false, unique = true)
private String key;
@Column(name = "executed_at", nullable = false)
private LocalDateTime executedAt;
@Column(name = "description")
private String description;
}
@@ -31,6 +31,9 @@ public class BookEntity {
@Column(name = "book_type")
private BookFileType bookType;
@Column(name = "file_size_kb")
private Long fileSizeKb;
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private BookMetadataEntity metadata;
@@ -0,0 +1,7 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AppMigrationRepository extends JpaRepository<AppMigrationEntity, String> {
}
@@ -38,9 +38,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
@Query("DELETE FROM BookEntity b WHERE b.id IN (:ids)")
void deleteByIdIn(Collection<Long> ids);
@Query("SELECT b FROM BookEntity b WHERE b.library IN (SELECT l FROM LibraryEntity l WHERE l IN :userLibraries)")
List<BookEntity> findBooksByUserLibraries(@Param("userLibraries") List<LibraryEntity> userLibraries);
List<BookEntity> findByLibraryIdIn(Set<Long> userLibraryIds);
List<BookEntity> findByFileSizeKbIsNull();
}
@@ -0,0 +1,47 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.entity.AppMigrationEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.AppMigrationRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.transaction.Transactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@AllArgsConstructor
@Service
public class AppMigrationService {
private AppMigrationRepository migrationRepository;
private BookRepository bookRepository;
@Transactional
public void populateMissingFileSizesOnce() {
if (migrationRepository.existsById("populateFileSizes")) {
return;
}
List<BookEntity> books = bookRepository.findByFileSizeKbIsNull();
for (BookEntity book : books) {
Long sizeInKb = FileUtils.getFileSizeInKb(book);
if (sizeInKb != null) {
book.setFileSizeKb(sizeInKb);
}
}
bookRepository.saveAll(books);
log.info("Starting migration 'populateFileSizes' for {} books.", books.size());
AppMigrationEntity migration = new AppMigrationEntity();
migration.setKey("populateFileSizes");
migration.setExecutedAt(LocalDateTime.now());
migration.setDescription("Populate file size for existing books");
migrationRepository.save(migration);
log.info("Migration 'populateFileSizes' executed successfully.");
}
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.service;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class AppMigrationStartup {
private final AppMigrationService appMigrationService;
@EventListener(ApplicationReadyEvent.class)
public void runMigrationsOnce() {
appMigrationService.populateMissingFileSizesOnce();
}
}
@@ -4,15 +4,20 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Slf4j
@Service
@AllArgsConstructor
public class BookCreatorService {
@@ -23,19 +28,19 @@ public class BookCreatorService {
private final BookMetadataRepository bookMetadataRepository;
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
long fileSizeKb = FileUtils.getFileSizeInKb(libraryFile.getFullPath());
BookEntity bookEntity = BookEntity.builder()
.library(libraryFile.getLibraryEntity())
.libraryPath(libraryFile.getLibraryPathEntity())
.fileName(libraryFile.getFileName())
.fileSubPath(libraryFile.getFileSubPath())
.bookType(bookFileType)
.fileSizeKb(fileSizeKb)
.addedOn(Instant.now())
.build();
BookMetadataEntity bookMetadataEntity = BookMetadataEntity.builder().build();
bookEntity.setMetadata(bookMetadataEntity);
bookEntity = bookRepository.saveAndFlush(bookEntity);
return bookEntity;
return bookRepository.saveAndFlush(bookEntity);
}
public void addCategoriesToBook(List<String> categories, BookEntity bookEntity) {
@@ -7,10 +7,7 @@ import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import lombok.AllArgsConstructor;
@@ -18,7 +15,6 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -32,12 +28,9 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@Slf4j
@AllArgsConstructor
@Service
@@ -124,21 +117,26 @@ public class BooksService {
public Book getBook(long bookId, boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookId).orElse(new UserBookProgressEntity());
Book book = bookMapper.toBook(bookEntity);
book.setLastReadTime(userProgress.getLastReadTime());
book.setPdfProgress(userProgress.getPdfProgress());
book.setEpubProgress(userProgress.getEpubProgress());
book.setFilePath(bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileSubPath() + "/" + bookEntity.getFileName());
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
if (!withDescription) {
book.getMetadata().setDescription(null);
}
return book;
}
public List<Book> getBooks(boolean withDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
List<BookEntity> books;
if (userEntity.getPermissions().isPermissionAdmin()) {
@@ -152,12 +150,14 @@ public class BooksService {
return books.stream()
.map(bookEntity -> {
UserBookProgressEntity userProgress = userBookProgressRepository.findByUserIdAndBookId(user.getId(), bookEntity.getId())
UserBookProgressEntity userProgress = userBookProgressRepository
.findByUserIdAndBookId(user.getId(), bookEntity.getId())
.orElse(new UserBookProgressEntity());
Book book = bookMapper.toBookWithDescription(bookEntity, withDescription);
book.setLastReadTime(userProgress.getLastReadTime());
book.setPdfProgress(userProgress.getPdfProgress());
book.setEpubProgress(userProgress.getEpubProgress());
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
return book;
})
.collect(Collectors.toList());
@@ -1,22 +1,45 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
@Slf4j
public class FileUtils {
private static final String FILE_NOT_FOUND_MESSAGE = "File does not exist: ";
public static String getBookFullPath(BookEntity bookEntity) {
return bookEntity.getLibraryPath().getPath() + "/" + bookEntity.getFileSubPath() + "/" + bookEntity.getFileName();
return String.format("%s/%s/%s", 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("\\", "/"))
.map(path -> path.toString().replace("\\", "/"))
.orElse("");
}
public static Long getFileSizeInKb(BookEntity bookEntity) {
Path filePath = Path.of(getBookFullPath(bookEntity));
return getFileSizeInKb(filePath);
}
public static Long getFileSizeInKb(Path filePath) {
try {
if (!Files.exists(filePath)) {
log.warn(FILE_NOT_FOUND_MESSAGE + "{}", filePath.toAbsolutePath());
return null;
}
return Files.size(filePath) / 1024;
} catch (IOException e) {
log.error("Failed to get file size for path [{}]: {}", filePath, e.getMessage(), e);
return null;
}
}
}
@@ -0,0 +1,2 @@
ALTER TABLE book
ADD COLUMN file_size_kb BIGINT;
@@ -0,0 +1,6 @@
CREATE TABLE app_migration
(
migration_key VARCHAR(100) PRIMARY KEY COMMENT 'Unique identifier for the migration',
executed_at TIMESTAMP NOT NULL COMMENT 'When the migration was executed',
description TEXT COMMENT 'Optional description of what the migration did'
) COMMENT = 'Tracks one-time application-level data migrations';
@@ -13,6 +13,7 @@ export interface Book {
epubProgress?: string;
pdfProgress?: number;
filePath?: string;
fileSizeKb?: number;
}
export interface BookMetadata {
@@ -50,13 +50,14 @@
<p-tag *ngFor="let category of metadata.categories" [value]="category" class="shrink-0"></p-tag>
</div>
<div class="grid gap-x-20 gap-y-2 pt-6" style="grid-template-columns: repeat(3, max-content);">
<div class="grid gap-x-20 gap-y-2 pt-6" style="grid-template-columns: repeat(4, max-content);">
<p class="whitespace-nowrap"><span class="font-bold">Publisher:</span> {{ metadata.publisher || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Published:</span> {{ metadata.publishedDate || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Language:</span> {{ metadata.language || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 10:</span> {{ metadata.isbn10 || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">ISBN 13:</span> {{ metadata.isbn13 || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">Page Count:</span> {{ metadata.pageCount || '-' }}</p>
<p class="whitespace-nowrap"><span class="font-bold">File Size:</span> {{ getFileSizeInMB() }}</p>
</div>
<p class="pt-2"><span class="font-bold">File Path:</span> {{ book?.filePath }}</p>
@@ -154,4 +154,13 @@ export class MetadataViewerComponent implements OnInit {
}
return lockedKeys.every(key => metadata[key] === true);
}
getFileSizeInMB(): string {
const sizeKb = this.book?.fileSizeKb;
if (sizeKb != null) {
const sizeMb = sizeKb / 1024;
return `${sizeMb.toFixed(2)} MB`;
}
return '-';
}
}