WIP: Checkpoint for global and individual book settings

This commit is contained in:
aditya.chandel
2025-01-17 16:03:40 -07:00
parent f75f005347
commit 5937574eb8
25 changed files with 384 additions and 299 deletions
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookViewerSetting; import com.adityachandel.booklore.model.dto.BookViewerSetting;
import com.adityachandel.booklore.model.dto.BookViewerSettings;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest; import com.adityachandel.booklore.model.dto.request.ShelvesAssignmentRequest;
import com.adityachandel.booklore.service.BooksService; import com.adityachandel.booklore.service.BooksService;
@@ -47,14 +48,14 @@ public class BookController {
return booksService.getBookData(bookId); return booksService.getBookData(bookId);
} }
@GetMapping("/{bookId}/viewer-setting") @GetMapping("/{bookId}/book-viewer-setting")
public ResponseEntity<BookViewerSetting> getBookViewerSettings(@PathVariable long bookId) { public ResponseEntity<BookViewerSettings> getBookViewerSettings(@PathVariable long bookId) {
return ResponseEntity.ok(booksService.getBookViewerSetting(bookId)); return ResponseEntity.ok(booksService.getBookViewerSetting(bookId));
} }
@PutMapping("/{bookId}/viewer-setting") @PutMapping("/{bookId}/book-viewer-setting")
public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSetting bookViewerSetting, @PathVariable long bookId) { public ResponseEntity<Void> updateBookViewerSettings(@RequestBody BookViewerSettings bookViewerSettings, @PathVariable long bookId) {
booksService.saveBookViewerSetting(bookId, bookViewerSetting); booksService.updateBookViewerSetting(bookId, bookViewerSettings);
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@@ -8,6 +8,8 @@ import org.springframework.http.HttpStatus;
public enum ApiError { public enum ApiError {
AUTHOR_NOT_FOUND(HttpStatus.NOT_FOUND, "Author not found with ID: %d"), AUTHOR_NOT_FOUND(HttpStatus.NOT_FOUND, "Author not found with ID: %d"),
BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, "Book not found with ID: %d"), BOOK_NOT_FOUND(HttpStatus.NOT_FOUND, "Book not found with ID: %d"),
UNSUPPORTED_BOOK_TYPE(HttpStatus.BAD_REQUEST, "Unsupported book type for viewer settings"),
INVALID_VIEWER_SETTING(HttpStatus.BAD_REQUEST, "Invalid viewer setting for the book"),
FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"), FILE_READ_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "Error reading files from path"),
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"), IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"), INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"),
@@ -1,12 +1,12 @@
package com.adityachandel.booklore.mapper; package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.BookViewerSetting; import com.adityachandel.booklore.model.dto.BookViewerSetting;
import com.adityachandel.booklore.model.entity.BookViewerSettingEntity; import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
@Mapper(componentModel = "spring") @Mapper(componentModel = "spring")
public interface BookViewerSettingMapper { public interface BookViewerSettingMapper {
BookViewerSetting toBookViewerSetting(BookViewerSettingEntity entity); BookViewerSetting toBookViewerSetting(PdfViewerPreferencesEntity entity);
} }
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.EpubViewerPreferences;
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
public interface EpubViewerPreferencesMapper {
EpubViewerPreferences toModel(EpubViewerPreferencesEntity entity);
EpubViewerPreferencesEntity toEntity(EpubViewerPreferences entity);
}
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.mapper;
import com.adityachandel.booklore.model.dto.PdfViewerPreferences;
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import org.mapstruct.Mapper;
@Mapper(componentModel = "spring")
public interface PdfViewerPreferencesMapper {
PdfViewerPreferences toModel(PdfViewerPreferencesEntity entity);
PdfViewerPreferencesEntity toEntity(PdfViewerPreferences model);
}
@@ -8,6 +8,6 @@ import lombok.Data;
public class BookViewerSetting { public class BookViewerSetting {
private int pageNumber; private int pageNumber;
private String zoom; private String zoom;
private Boolean sidebar_visible; private Boolean sidebarVisible;
private String spread; private String spread;
} }
@@ -0,0 +1,11 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class BookViewerSettings {
private PdfViewerPreferences pdfSettings;
private EpubViewerPreferences epubSettings;
}
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class EpubViewerPreferences {
private Long bookId;
private String theme;
private String font;
private Integer fontSize;
}
@@ -0,0 +1,13 @@
package com.adityachandel.booklore.model.dto;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class PdfViewerPreferences {
private Long bookId;
private String zoom;
private Boolean sidebarVisible;
private String spread;
}
@@ -37,7 +37,10 @@ public class BookEntity {
private LibraryEntity library; private LibraryEntity library;
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true) @OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private BookViewerSettingEntity viewerSetting; private PdfViewerPreferencesEntity pdfViewerPrefs;
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private EpubViewerPreferencesEntity epubViewerPrefs;
@Column(name = "last_read_time") @Column(name = "last_read_time")
private Instant lastReadTime; private Instant lastReadTime;
@@ -0,0 +1,32 @@
package com.adityachandel.booklore.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "epub_viewer_preference")
public class EpubViewerPreferencesEntity {
@Id
private Long bookId;
@OneToOne
@MapsId
@JoinColumn(name = "book_id")
@JsonIgnore
private BookEntity book;
@Column(name = "theme")
private String theme;
@Column(name = "font")
private String font;
@Column(name = "font_size")
private Integer fontSize;
}
@@ -10,8 +10,8 @@ import lombok.*;
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Table(name = "book_viewer_setting") @Table(name = "pdf_viewer_preference")
public class BookViewerSettingEntity { public class PdfViewerPreferencesEntity {
@Id @Id
private Long bookId; private Long bookId;
@@ -21,14 +21,11 @@ public class BookViewerSettingEntity {
@JsonIgnore @JsonIgnore
private BookEntity book; private BookEntity book;
@Column(name = "page_number")
private int pageNumber;
@Column(name = "zoom") @Column(name = "zoom")
private String zoom; private String zoom;
@Column(name = "sidebar_visible") @Column(name = "sidebar_visible")
private Boolean sidebar_visible; private Boolean sidebarVisible;
@Column(name = "spread") @Column(name = "spread")
private String spread; private String spread;
@@ -1,10 +0,0 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.BookViewerSettingEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookViewerSettingRepository extends JpaRepository<BookViewerSettingEntity, Long> {
}
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EpubViewerPreferencesRepository extends JpaRepository<EpubViewerPreferencesEntity, Long> {
}
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PdfViewerPreferencesRepository extends JpaRepository<PdfViewerPreferencesEntity, Long> {
}
@@ -1,15 +1,9 @@
package com.adityachandel.booklore.service; package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.LibraryFile; import com.adityachandel.booklore.model.LibraryFile;
import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.BookViewerSettingEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.AuthorRepository; import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.BookViewerSettingRepository;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -26,7 +20,8 @@ public class BookCreatorService {
private AuthorRepository authorRepository; private AuthorRepository authorRepository;
private BookRepository bookRepository; private BookRepository bookRepository;
private BookMetadataRepository bookMetadataRepository; private BookMetadataRepository bookMetadataRepository;
private BookViewerSettingRepository bookViewerSettingRepository; private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) { public BookEntity createShellBook(LibraryFile libraryFile, BookFileType bookFileType) {
File bookFile = new File(libraryFile.getFilePath()); File bookFile = new File(libraryFile.getFilePath());
@@ -35,16 +30,25 @@ public class BookCreatorService {
.path(bookFile.getPath()) .path(bookFile.getPath())
.fileName(bookFile.getName()) .fileName(bookFile.getName())
.bookType(bookFileType) .bookType(bookFileType)
.addedOn(Instant.now())
.build(); .build();
BookMetadataEntity bookMetadataEntity = BookMetadataEntity.builder().build(); BookMetadataEntity bookMetadataEntity = BookMetadataEntity.builder().build();
BookViewerSettingEntity bookViewerSetting = BookViewerSettingEntity.builder() if (bookFileType == BookFileType.PDF) {
.book(bookEntity) PdfViewerPreferencesEntity pdfViewerPreferencesEntity = PdfViewerPreferencesEntity.builder()
.bookId(bookEntity.getId()) .book(bookEntity)
.build(); .bookId(bookEntity.getId())
.build();
bookEntity.setPdfViewerPrefs(pdfViewerPreferencesEntity);
} else if (bookFileType == BookFileType.EPUB) {
EpubViewerPreferencesEntity epubViewerPreferencesEntity = EpubViewerPreferencesEntity.builder()
.book(bookEntity)
.bookId(bookEntity.getId())
.build();
bookEntity.setEpubViewerPrefs(epubViewerPreferencesEntity);
}
bookEntity.setMetadata(bookMetadataEntity); bookEntity.setMetadata(bookMetadataEntity);
bookEntity.setViewerSetting(bookViewerSetting);
bookEntity.setAddedOn(Instant.now());
bookEntity = bookRepository.saveAndFlush(bookEntity); bookEntity = bookRepository.saveAndFlush(bookEntity);
return bookEntity; return bookEntity;
} }
@@ -73,6 +77,10 @@ public class BookCreatorService {
} }
bookRepository.save(bookEntity); bookRepository.save(bookEntity);
bookMetadataRepository.save(bookEntity.getMetadata()); bookMetadataRepository.save(bookEntity.getMetadata());
bookViewerSettingRepository.save(bookEntity.getViewerSetting()); if (bookEntity.getBookType() == BookFileType.EPUB) {
epubViewerPreferencesRepository.save(bookEntity.getEpubViewerPrefs());
} else if (bookEntity.getBookType() == BookFileType.PDF) {
pdfViewerPreferencesRepository.save(bookEntity.getPdfViewerPrefs());
}
} }
} }
@@ -2,21 +2,20 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.mapper.BookViewerSettingMapper; import com.adityachandel.booklore.mapper.EpubViewerPreferencesMapper;
import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.mapper.PdfViewerPreferencesMapper;
import com.adityachandel.booklore.model.dto.BookViewerSetting; import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.BookWithNeighbors;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest; import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookViewerSettingEntity; import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity; import com.adityachandel.booklore.model.entity.ShelfEntity;
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.repository.BookViewerSettingRepository; import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
import com.adityachandel.booklore.repository.LibraryRepository; 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 jakarta.validation.Valid;
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;
@@ -29,7 +28,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@@ -44,13 +42,45 @@ import java.util.stream.Collectors;
public class BooksService { public class BooksService {
private final BookRepository bookRepository; private final BookRepository bookRepository;
private final BookViewerSettingRepository bookViewerSettingRepository; private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
private final LibraryRepository libraryRepository; private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
private final ShelfRepository shelfRepository; private final ShelfRepository shelfRepository;
private final FileService fileService; private final FileService fileService;
private final BookMapper bookMapper; private final BookMapper bookMapper;
private final BookViewerSettingMapper bookViewerSettingMapper; private final PdfViewerPreferencesMapper pdfViewerPreferencesMapper;
private final EpubViewerPreferencesMapper epubViewerPreferencesMapper;
public BookViewerSettings getBookViewerSetting(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookEntity.getBookType() == BookFileType.PDF) {
return BookViewerSettings.builder().pdfSettings(pdfViewerPreferencesMapper.toModel(bookEntity.getPdfViewerPrefs())).build();
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
return BookViewerSettings.builder().epubSettings(epubViewerPreferencesMapper.toModel(bookEntity.getEpubViewerPrefs())).build();
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
}
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookEntity.getBookType() == BookFileType.PDF) {
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
PdfViewerPreferencesEntity viewerPrefs = bookEntity.getPdfViewerPrefs();
viewerPrefs.setZoom(pdfSettings.getZoom());
viewerPrefs.setSpread(pdfSettings.getSpread());
viewerPrefs.setSidebarVisible(pdfSettings.getSidebarVisible());
pdfViewerPreferencesRepository.save(viewerPrefs);
} else if (bookEntity.getBookType() == BookFileType.EPUB) {
EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings();
EpubViewerPreferencesEntity viewerPrefs = bookEntity.getEpubViewerPrefs();
viewerPrefs.setFont(epubSettings.getFont());
viewerPrefs.setFontSize(epubSettings.getFontSize());
viewerPrefs.setTheme(epubSettings.getTheme());
epubViewerPreferencesRepository.save(viewerPrefs);
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
}
public Book getBook(long bookId, boolean withDescription) { public Book getBook(long bookId, boolean withDescription) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
@@ -67,15 +97,6 @@ public class BooksService {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public void saveBookViewerSetting(long bookId, BookViewerSetting bookViewerSettingDTO) {
BookViewerSettingEntity bookViewerSetting = bookViewerSettingRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookViewerSetting.setPageNumber(bookViewerSettingDTO.getPageNumber());
bookViewerSetting.setZoom(bookViewerSettingDTO.getZoom());
bookViewerSetting.setSpread(bookViewerSettingDTO.getSpread());
bookViewerSetting.setSidebar_visible(bookViewerSettingDTO.getSidebar_visible());
bookViewerSettingRepository.save(bookViewerSetting);
}
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.getPath()).toPath()); byte[] pdfBytes = Files.readAllBytes(new File(bookEntity.getPath()).toPath());
@@ -89,29 +110,12 @@ public class BooksService {
return bookEntities.stream().map(bookMapper::toBook).toList(); return bookEntities.stream().map(bookMapper::toBook).toList();
} }
public BookViewerSetting getBookViewerSetting(long bookId) {
BookViewerSettingEntity bookViewerSetting = bookViewerSettingRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
return bookViewerSettingMapper.toBookViewerSetting(bookViewerSetting);
}
public Book updateLastReadTime(long bookId) { public Book updateLastReadTime(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookEntity.setLastReadTime(Instant.now()); bookEntity.setLastReadTime(Instant.now());
return bookMapper.toBook(bookRepository.save(bookEntity)); return bookMapper.toBook(bookRepository.save(bookEntity));
} }
public BookWithNeighbors getBookWithNeighbours(long libraryId, long bookId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
BookEntity previousBookEntity = bookRepository.findFirstByLibraryIdAndIdLessThanOrderByIdDesc(libraryId, bookId).orElse(null);
BookEntity nextBookEntity = bookRepository.findFirstByLibraryIdAndIdGreaterThanOrderByIdAsc(libraryId, bookId).orElse(null);
return BookWithNeighbors.builder()
.currentBook(bookMapper.toBook(bookEntity))
.previousBookId(previousBookEntity != null ? previousBookEntity.getId() : null)
.nextBookId(nextBookEntity != null ? nextBookEntity.getId() : null)
.build();
}
@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);
@@ -72,14 +72,22 @@ CREATE TABLE IF NOT EXISTS category
); );
-- Create the book_viewer_setting table -- Create the book_viewer_setting table
CREATE TABLE IF NOT EXISTS book_viewer_setting CREATE TABLE IF NOT EXISTS pdf_viewer_preference
( (
book_id BIGINT PRIMARY KEY, book_id BIGINT PRIMARY KEY,
page_number INT NULL,
zoom VARCHAR(16) NULL, zoom VARCHAR(16) NULL,
sidebar_visible BOOLEAN NULL, sidebar_visible BOOLEAN NULL,
spread VARCHAR(16) NULL, spread VARCHAR(16) NULL,
CONSTRAINT fk_book_viewer_setting FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE CONSTRAINT fk_pdf_viewer_setting FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS epub_viewer_preference
(
book_id BIGINT PRIMARY KEY,
theme VARCHAR(128) NULL,
font VARCHAR(128) NULL,
font_size TINYINT NULL,
CONSTRAINT fk_epub_viewer_setting FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
); );
-- Create the book_metadata_category_mapping table -- Create the book_metadata_category_mapping table
@@ -131,6 +139,6 @@ CREATE TABLE app_settings
id BIGINT AUTO_INCREMENT PRIMARY KEY, id BIGINT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(255) NOT NULL, category VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL,
val TEXT NOT NULL, val TEXT NOT NULL,
UNIQUE (category, name) UNIQUE (category, name)
); );
@@ -3,7 +3,8 @@ import {ActivatedRoute} from '@angular/router';
import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewer'; import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewer';
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 {Subscription} from 'rxjs'; import {filter, forkJoin, Subscription, take} from 'rxjs';
import {PdfViewerSetting} from '../../model/book.model';
@Component({ @Component({
selector: 'app-pdf-viewer', selector: 'app-pdf-viewer',
@@ -33,36 +34,34 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
ngOnInit(): void { ngOnInit(): void {
this.route.paramMap.subscribe((params) => { this.route.paramMap.subscribe((params) => {
this.bookId = +params.get('bookId')!; this.bookId = +params.get('bookId')!;
this.loadBook(this.bookId); this.appSettingsService.appSettings$
this.updateLastReadTime(); .pipe(
}); filter((appSettings) => appSettings !== null),
} take(1))
.subscribe((appSettings) => {
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
const pdf$ = this.bookService.getPdfData(this.bookId);
const bookSetting$ = this.bookService.getBookSetting(this.bookId);
forkJoin([book$, pdf$, bookSetting$]).subscribe((results) => {
const pdf = results[0];
const pdfData = results[1];
const individualPdfSettings = results[2]?.pdfSettings;
const globalPdfSettings = appSettings.pdf;
console.log(individualPdfSettings);
console.log(globalPdfSettings);
this.page = pdf.pdfProgress || 1;
this.zoom = individualPdfSettings?.zoom || globalPdfSettings?.zoom || 'page-fit';
this.sidebarVisible = individualPdfSettings?.sidebarVisible ?? globalPdfSettings?.sidebar ?? true;
this.spread = individualPdfSettings?.spread || globalPdfSettings?.spread || 'odd';
private loadBook(bookId: number): void {
this.appSettingsSubscription = this.appSettingsService.appSettings$.subscribe((appSettings) => {
if (appSettings) {
this.bookService.getBookSetting(bookId).subscribe({
next: (bookSetting) => {
const {pageNumber, zoom, sidebar_visible, spread} = bookSetting;
this.page = pageNumber || 1;
this.zoom = zoom || appSettings.pdf?.zoom || 'page-fit';
this.sidebarVisible = sidebar_visible ?? appSettings.pdf?.sidebar ?? true;
this.spread = spread || appSettings.pdf?.spread || 'odd';
this.isInitialLoad = false; this.isInitialLoad = false;
this.bookService.getBookData(bookId).subscribe({ this.bookData = pdfData;
next: (bookData) => { this.updateLastReadTime();
this.bookData = bookData; });
},
error: (e) => {
console.error('Error loading book data:', e);
},
});
},
error: (e) => {
console.error('Error loading book settings:', e);
},
}); });
}
}); });
} }
@@ -100,8 +99,8 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
private updateViewerSetting(): void { private updateViewerSetting(): void {
if (this.isInitialLoad) return; if (this.isInitialLoad) return;
const updatedViewerSetting = { const updatedViewerSetting: PdfViewerSetting = {
sidebar_visible: this.sidebarVisible, sidebarVisible: this.sidebarVisible,
spread: this.spread, spread: this.spread,
zoom: this.zoom, zoom: this.zoom,
}; };
@@ -10,13 +10,11 @@ import {Shelf} from '../../model/shelf.model';
import {IconPickerComponent} from '../../../utilities/component/icon-picker/icon-picker.component'; import {IconPickerComponent} from '../../../utilities/component/icon-picker/icon-picker.component';
import {ShelfState} from '../../model/state/shelf-state.model'; import {ShelfState} from '../../model/state/shelf-state.model';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {Divider} from 'primeng/divider';
import {AsyncPipe, NgForOf, NgIf} from '@angular/common'; import {AsyncPipe, NgForOf, NgIf} from '@angular/common';
import {Checkbox} from 'primeng/checkbox'; import {Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Dialog} from 'primeng/dialog'; import {Dialog} from 'primeng/dialog';
import {InputText} from 'primeng/inputtext'; import {InputText} from 'primeng/inputtext';
import {Router} from '@angular/router';
@Component({ @Component({
selector: 'app-shelf-assigner', selector: 'app-shelf-assigner',
@@ -24,7 +22,6 @@ import {Router} from '@angular/router';
templateUrl: './shelf-assigner.component.html', templateUrl: './shelf-assigner.component.html',
imports: [ imports: [
Button, Button,
Divider,
NgForOf, NgForOf,
Checkbox, Checkbox,
AsyncPipe, AsyncPipe,
+15 -4
View File
@@ -67,9 +67,20 @@ export interface Category {
name: string; name: string;
} }
export interface BookSetting { export interface PdfViewerSetting {
pageNumber: number; zoom: string | number;
zoom: number | string; sidebarVisible: boolean;
sidebar_visible: boolean | null;
spread: 'off' | 'even' | 'odd'; spread: 'off' | 'even' | 'odd';
} }
export interface EpubViewerSetting {
theme: string;
font: string;
fontSize: number;
}
export interface BookSetting {
pdfSettings?: PdfViewerSetting;
epubSettings?: EpubViewerSetting;
[key: string]: any;
}
@@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Observable, of} from 'rxjs'; import {BehaviorSubject, Observable, of} from 'rxjs';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {catchError, map, switchMap, tap} from 'rxjs/operators'; import {catchError, map, switchMap, tap} from 'rxjs/operators';
import {Book, BookMetadata, BookSetting, BookType} from '../model/book.model'; import {Book, BookMetadata, BookSetting, BookType, EpubViewerSetting, PdfViewerSetting} from '../model/book.model';
import {BookState} from '../model/state/book-state.model'; import {BookState} from '../model/state/book-state.model';
@Injectable({ @Injectable({
@@ -89,11 +89,11 @@ export class BookService {
} }
getBookSetting(bookId: number): Observable<BookSetting> { getBookSetting(bookId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`); return this.http.get<BookSetting>(`${this.url}/${bookId}/book-viewer-setting`);
} }
updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> { updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, viewerSetting); return this.http.put<void>(`${this.url}/${bookId}/book-viewer-setting`, bookSetting);
} }
updateLastReadTime(bookId: number): Observable<Book> { updateLastReadTime(bookId: number): Observable<Book> {
@@ -145,7 +145,7 @@ export class BookService {
); );
} }
getBookData(bookId: number): Observable<Blob> { getPdfData(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/data`, {responseType: 'blob' as 'json'}); return this.http.get<Blob>(`${this.url}/${bookId}/data`, {responseType: 'blob' as 'json'});
} }
@@ -80,7 +80,7 @@ export class SettingsComponent implements OnInit {
if (settings.epub) { if (settings.epub) {
const epubSettings = settings.epub; const epubSettings = settings.epub;
this.selectedTheme = this.themes.find(t => t.key === epubSettings.theme)?.key; this.selectedTheme = this.themes.find(t => t.key === epubSettings.theme)?.key;
this.fontSize = parseInt(epubSettings.fontSize, 10); this.fontSize = epubSettings.fontSize;
this.selectedFont = this.fonts.find(f => f.key === epubSettings.font)?.key; this.selectedFont = this.fonts.find(f => f.key === epubSettings.font)?.key;
} }
} }
@@ -1,13 +1,15 @@
export interface EpubSettings { export interface EpubSettings {
theme: string; theme: string;
fontSize: string; fontSize: number;
font: string; font: string;
page: string;
} }
export interface PdfSettings { export interface PdfSettings {
spread: 'off' | 'even' | 'odd'; spread: 'off' | 'even' | 'odd';
zoom: string; zoom: string;
sidebar: boolean; sidebar: boolean;
page: number;
} }
export interface AppSettings { export interface AppSettings {
@@ -7,47 +7,53 @@ import {NgForOf} from '@angular/common';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {Book} from '../../book/model/book.model'; import {Book, BookSetting, EpubViewerSetting} from '../../book/model/book.model';
import {BookService} from '../../book/service/book.service'; import {BookService} from '../../book/service/book.service';
import {forkJoin} from 'rxjs'; import {filter, forkJoin, take} from 'rxjs';
import {AppSettingsService} from '../../core/service/app-settings.service'; import {AppSettingsService} from '../../core/service/app-settings.service';
import {Select} from 'primeng/select'; import {Select} from 'primeng/select';
const FALLBACK_EPUB_SETTINGS = {
fontSize: 150,
fontType: 'serif',
theme: 'white',
maxFontSize: 300,
minFontSize: 50,
};
@Component({ @Component({
selector: 'app-epub-viewer', selector: 'app-epub-viewer',
templateUrl: './epub-viewer.component.html', templateUrl: './epub-viewer.component.html',
styleUrls: ['./epub-viewer.component.scss'], styleUrls: ['./epub-viewer.component.scss'],
imports: [Drawer, Button, NgForOf, FormsModule, Divider, Select] imports: [Drawer, Button, NgForOf, FormsModule, Divider, Select],
}) })
export class EpubViewerComponent implements OnInit, OnDestroy { export class EpubViewerComponent implements OnInit, OnDestroy {
@ViewChild('epubContainer', { static: true }) epubContainer!: ElementRef;
@ViewChild('epubContainer', {static: true}) epubContainer!: ElementRef;
chapters: { label: string; href: string }[] = []; chapters: { label: string; href: string }[] = [];
isDrawerVisible = false; isDrawerVisible = false;
isSettingsDrawerVisible: boolean = false; isSettingsDrawerVisible = false;
private book: any; private book: any;
private rendition: any; private rendition: any;
private keyListener: (e: KeyboardEvent) => void = () => { private keyListener: (e: KeyboardEvent) => void = () => {};
};
fontSize: number = 120;
epub!: Book; fontSize = FALLBACK_EPUB_SETTINGS.fontSize;
selectedFontType = FALLBACK_EPUB_SETTINGS.fontType;
selectedTheme = FALLBACK_EPUB_SETTINGS.theme;
fontTypes: any[] = [ fontTypes: any[] = [
{label: 'Serif', value: 'serif'}, { label: 'Serif', value: 'serif' },
{label: 'Sans Serif', value: 'sans-serif'}, { label: 'Sans Serif', value: 'sans-serif' },
{label: 'Roboto', value: 'roboto'}, { label: 'Roboto', value: 'roboto' },
{label: 'Cursive', value: 'cursive'}, { label: 'Cursive', value: 'cursive' },
{label: 'Monospace', value: 'monospace'} { label: 'Monospace', value: 'monospace' },
]; ];
selectedFontType: string = 'serif';
selectedTheme: string = 'white';
themes: any[] = [ themes: any[] = [
{label: 'White', value: 'white'}, { label: 'White', value: 'white' },
{label: 'Black', value: 'black'}, { label: 'Black', value: 'black' },
{label: 'Grey', value: 'grey'}, { label: 'Grey', value: 'grey' },
{label: 'Sepia', value: 'sepia'} { label: 'Sepia', value: 'sepia' },
]; ];
private epubService = inject(EpubService); private epubService = inject(EpubService);
@@ -55,119 +61,134 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
private bookService = inject(BookService); private bookService = inject(BookService);
private appSettingsService = inject(AppSettingsService); private appSettingsService = inject(AppSettingsService);
epub!: Book;
ngOnInit(): void { ngOnInit(): void {
this.route.paramMap.subscribe((params) => { this.route.paramMap.subscribe((params) => {
let book$ = this.bookService.getBookByIdFromAPI(+params.get('bookId')!, false); const bookId = +params.get('bookId')!;
let epub$ = this.epubService.downloadEpub(+params.get('bookId')!); this.appSettingsService.appSettings$
forkJoin([book$, epub$]).subscribe(results => { .pipe(filter((appSettings) => appSettings !== null), take(1))
this.epub = results[0]; .subscribe((appSettings) => {
const epub$ = this.bookService.getBookByIdFromAPI(bookId, false);
const epubData$ = this.epubService.downloadEpub(bookId);
const bookSetting$ = this.bookService.getBookSetting(bookId);
const fileReader = new FileReader(); forkJoin([epub$, epubData$, bookSetting$]).subscribe((results) => {
fileReader.onload = () => { const epub = results[0];
const epubData = fileReader.result as ArrayBuffer; const epubData = results[1];
this.book = ePub(epubData); const individualSetting = results[2]?.epubSettings;
const globalSetting = appSettings.epub;
this.book.loaded.navigation.then((nav: any) => { console.log(individualSetting)
this.chapters = nav.toc.map((chapter: any) => ({ console.log(globalSetting)
label: chapter.label,
href: chapter.href, this.epub = epub;
})); const fileReader = new FileReader();
fileReader.onload = () => {
this.book = ePub(fileReader.result as ArrayBuffer);
this.book.loaded.navigation.then((nav: any) => {
this.chapters = nav.toc.map((chapter: any) => ({
label: chapter.label,
href: chapter.href,
}));
});
this.rendition = this.book.renderTo(this.epubContainer.nativeElement, {
flow: 'paginated',
width: '100%',
height: '100%',
allowScriptedContent: true,
});
this.selectedTheme = individualSetting?.theme || globalSetting?.theme || FALLBACK_EPUB_SETTINGS.theme;
this.selectedFontType = individualSetting?.font || globalSetting?.font || FALLBACK_EPUB_SETTINGS.fontType;
this.fontSize = individualSetting?.fontSize || globalSetting?.fontSize || FALLBACK_EPUB_SETTINGS.fontSize;
this.applyViewerSettings();
this.setupKeyListener();
this.trackProgress();
};
fileReader.readAsArrayBuffer(epubData);
}); });
});
this.rendition = this.book.renderTo(this.epubContainer.nativeElement, {
flow: 'paginated',
width: '100%',
height: '100%',
allowScriptedContent: true,
});
if (this.epub?.epubProgress) {
this.rendition.display(this.epub.epubProgress);
} else {
this.rendition.display();
}
this.themesMap.forEach((theme, name) => {
this.rendition.themes.register(name, theme);
});
this.setupKeyListener();
this.trackProgress();
this.subscribeToSettings();
};
fileReader.readAsArrayBuffer(results[1]);
})
}); });
} }
private subscribeToSettings(): void { private applyViewerSettings(): void {
this.appSettingsService.appSettings$.subscribe((settings) => { this.changeFontType();
if (settings) { this.updateFontSize();
if (settings.epub) { this.changeThemes();
this.selectedTheme = settings.epub.theme || 'white';
this.selectedFontType = settings.epub.font || 'serif';
this.fontSize = parseInt(settings.epub.fontSize, 10) || 120;
this.changeFontType();
this.updateFontSize();
this.changeThemes();
}
}
});
}
private trackProgress(): void {
if (this.rendition) {
this.rendition.on('relocated', (location: any) => {
this.bookService.saveEpubProgress(this.epub.id, location.start.cfi).subscribe({
next: () => {
},
error: () => {
}
})
});
}
} }
updateFontSize(): void { updateFontSize(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.themes.fontSize(`${this.fontSize}%`); this.rendition.themes.fontSize(`${this.fontSize}%`);
this.updateViewerSetting();
} }
} }
increaseFontSize(): void { increaseFontSize(): void {
this.fontSize += 10; this.fontSize = Math.min(this.fontSize + 10, FALLBACK_EPUB_SETTINGS.maxFontSize);
if (this.fontSize > 300) {
this.fontSize = 300;
}
this.updateFontSize(); this.updateFontSize();
} }
decreaseFontSize(): void { decreaseFontSize(): void {
this.fontSize -= 10; this.fontSize = Math.max(this.fontSize - 10, FALLBACK_EPUB_SETTINGS.minFontSize);
if (this.fontSize < 50) {
this.fontSize = 50;
}
this.updateFontSize(); this.updateFontSize();
} }
changeFontType(): void { changeFontType(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.themes.font(this.selectedFontType); this.rendition.themes.font(this.selectedFontType);
this.updateViewerSetting();
} }
} }
changeThemes() { changeThemes(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.themes.select(this.selectedTheme); this.rendition.themes.select(this.selectedTheme);
this.rendition.clear(); this.rendition.clear();
this.rendition.start(); this.rendition.start();
this.updateViewerSetting();
} }
} }
navigateToChapter(chapter: { label: string; href: string }): void { private updateViewerSetting(): void {
if (this.book && chapter.href) { const bookSetting: BookSetting = {
this.book.rendition.display(chapter.href); epubSettings: {
theme: this.selectedTheme,
font: this.selectedFontType,
fontSize: this.fontSize,
}
}
this.bookService.updateViewerSetting(bookSetting, this.epub.id).subscribe();
}
private setupKeyListener(): void {
this.keyListener = (e: KeyboardEvent) => {
if (e.key === 'ArrowLeft') {
this.prevPage();
} else if (e.key === 'ArrowRight') {
this.nextPage();
}
};
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();
} }
} }
@@ -177,9 +198,9 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
} }
} }
prevPage(): void { navigateToChapter(chapter: { label: string; href: string }): void {
if (this.rendition) { if (this.book && chapter.href) {
this.rendition.prev(); this.book.rendition.display(chapter.href);
} }
} }
@@ -191,83 +212,10 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible; this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible;
} }
private setupKeyListener(): void {
this.keyListener = (e: KeyboardEvent) => {
switch (e.key) {
case 'ArrowLeft':
this.prevPage();
break;
case 'ArrowRight':
this.nextPage();
break;
default:
break;
}
};
if (this.rendition) {
this.rendition.on('keyup', this.keyListener);
}
document.addEventListener('keyup', this.keyListener);
}
ngOnDestroy(): void { ngOnDestroy(): void {
if (this.rendition) { if (this.rendition) {
this.rendition.off('keyup', this.keyListener); this.rendition.off('keyup', this.keyListener);
} }
document.removeEventListener('keyup', this.keyListener); document.removeEventListener('keyup', this.keyListener);
} }
themesMap = new Map<string, any>([
[
'black', {
"body": {"background-color": "#000000", "color": "#f9f9f9"},
"p": {"color": "#f9f9f9"},
"h1, h2, h3, h4, h5, h6": {"color": "#f9f9f9"},
"a": {"color": "#f9f9f9"},
"img": {
"-webkit-filter": "invert(1) hue-rotate(180deg)",
"filter": "invert(1) hue-rotate(180deg)"
},
"code": {"color": "#00ff00", "background-color": "black"}
}
],
[
'sepia', {
"body": {"background-color": "#f4ecd8", "color": "#6e4b3a"},
"p": {"color": "#6e4b3a"},
"h1, h2, h3, h4, h5, h6": {"color": "#6e4b3a"},
"a": {"color": "#8b4513"},
"img": {
"-webkit-filter": "sepia(1) contrast(1.5)",
"filter": "sepia(1) contrast(1.5)"
},
"code": {"color": "#8b0000", "background-color": "#f4ecd8"}
}
],
[
'white', {
"body": {"background-color": "#ffffff", "color": "#000000"},
"p": {"color": "#000000"},
"h1, h2, h3, h4, h5, h6": {"color": "#000000"},
"a": {"color": "#000000"},
"img": {
"-webkit-filter": "none",
"filter": "none"
},
"code": {"color": "#d14", "background-color": "#f5f5f5"}
}
],
[
'grey', {
"body": {"background-color": "#404040", "color": "#d3d3d3"},
"p": {"color": "#d3d3d3"},
"h1, h2, h3, h4, h5, h6": {"color": "#d3d3d3"},
"a": {"color": "#1e90ff"},
"img": {
"filter": "none"
},
"code": {"color": "#d14", "background-color": "#585858"}
}
]
]);
} }