Add user specific book progress tracking and improve epub progress tracking

This commit is contained in:
adityachandelgit
2025-05-18 11:16:45 -06:00
committed by Aditya Chandel
parent 8d8379e689
commit c2960ad830
20 changed files with 287 additions and 74 deletions
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@@ -20,7 +21,7 @@ public class Book {
private Instant lastReadTime;
private Instant addedOn;
private BookMetadata metadata;
private Integer pdfProgress;
private String epubProgress;
private PdfProgress pdfProgress;
private EpubProgress epubProgress;
private List<Shelf> shelves;
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class EpubProgress {
@NotNull
String cfi;
@NotNull
Float percentage;
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class PdfProgress {
@NotNull
Integer page;
@NotNull
Float percentage;
}
@@ -1,5 +1,7 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.dto.EpubProgress;
import com.adityachandel.booklore.model.dto.PdfProgress;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@@ -8,8 +10,8 @@ import lombok.Data;
public class ReadProgressRequest {
@NotNull
private Long bookId;
private String epubProgress;
private Integer pdfProgress;
private EpubProgress epubProgress;
private PdfProgress pdfProgress;
@AssertTrue(message = "Either epubProgress or pdfProgress must be provided")
public boolean isProgressValid() {
@@ -32,6 +32,12 @@ public class UserBookProgressEntity {
@Column(name = "pdf_progress")
private Integer pdfProgress;
@Column(name = "pdf_progress_percent")
private Float pdfProgressPercent;
@Column(name = "epub_progress", length = 1000)
private String epubProgress;
@Column(name = "epub_progress_percent")
private Float epubProgressPercent;
}
@@ -124,8 +124,19 @@ public class BooksService {
Book book = bookMapper.toBook(bookEntity);
book.setLastReadTime(userProgress.getLastReadTime());
book.setPdfProgress(userProgress.getPdfProgress());
book.setEpubProgress(userProgress.getEpubProgress());
if (bookEntity.getBookType() == BookFileType.PDF) {
book.setPdfProgress(PdfProgress.builder()
.page(userProgress.getPdfProgress())
.percentage(userProgress.getPdfProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.EPUB) {
book.setEpubProgress(EpubProgress.builder()
.cfi(userProgress.getEpubProgress())
.percentage(userProgress.getEpubProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
if (!withDescription) {
@@ -157,8 +168,18 @@ public class BooksService {
.orElse(new UserBookProgressEntity());
Book book = bookMapper.toBookWithDescription(bookEntity, withDescription);
book.setLastReadTime(userProgress.getLastReadTime());
book.setPdfProgress(userProgress.getPdfProgress());
book.setEpubProgress(userProgress.getEpubProgress());
if (bookEntity.getBookType() == BookFileType.EPUB) {
book.setEpubProgress(EpubProgress.builder()
.cfi(userProgress.getEpubProgress())
.percentage(userProgress.getEpubProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.PDF) {
book.setPdfProgress(PdfProgress.builder()
.page(userProgress.getPdfProgress())
.percentage(userProgress.getPdfProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
return book;
})
@@ -210,9 +231,11 @@ public class BooksService {
userBookProgress.setBook(book);
userBookProgress.setLastReadTime(Instant.now());
if (book.getBookType() == BookFileType.EPUB && request.getEpubProgress() != null) {
userBookProgress.setEpubProgress(request.getEpubProgress());
userBookProgress.setEpubProgress(request.getEpubProgress().getCfi());
userBookProgress.setEpubProgressPercent(request.getEpubProgress().getPercentage());
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
userBookProgress.setPdfProgress(request.getPdfProgress());
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
}
userBookProgressRepository.save(userBookProgress);
}
@@ -0,0 +1,3 @@
ALTER TABLE user_book_progress
ADD COLUMN pdf_progress_percent FLOAT NULL,
ADD COLUMN epub_progress_percent FLOAT NULL;
@@ -23,6 +23,14 @@
class="select-checkbox"
(ngModelChange)="toggleSelection(isSelected || false)">
</p-checkbox>
<p-progressBar
*ngIf="progressPercentage !== null"
[value]="progressPercentage"
[showValue]="false"
class="cover-progress-bar"
[ngClass]="{ 'progress-complete': progressPercentage === 100, 'progress-incomplete': progressPercentage < 100 }">
</p-progressBar>
</div>
<div [hidden]="bottomBarHidden">
@@ -1,6 +1,6 @@
.book-card {
background-color: var(--card-background);
border-radius: 8px;
border-radius: 0 0 8px 8px;
position: relative;
overflow: hidden;
transition: border 0.2s;
@@ -13,7 +13,6 @@
.cover-container {
position: relative;
width: 100%;
border-radius: 8px;
overflow: hidden;
display: flex;
align-items: center;
@@ -39,7 +38,7 @@
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 8px;
border-radius: 8px 8px 0 0;
transition: opacity 0.3s ease-in;
opacity: 0;
}
@@ -126,3 +125,25 @@
opacity: 1;
visibility: visible;
}
.cover-progress-bar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 2px;
z-index: 1;
opacity: 0.8;
}
::ng-deep .progress-incomplete .p-progressbar-value {
background-color: #3b82f6;
}
::ng-deep .progress-complete .p-progressbar-value {
background-color: #22c55e;
}
::ng-deep p-progressbar {
--p-progressbar-border-radius: 0 !important;
}
@@ -19,12 +19,13 @@ import {EmailService} from '../../../../settings/email/email.service';
import {TieredMenu} from 'primeng/tieredmenu';
import {BookSenderComponent} from '../../book-sender/book-sender.component';
import {Router} from '@angular/router';
import {ProgressBar} from 'primeng/progressbar';
@Component({
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, NgClass, TieredMenu],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, NgClass, TieredMenu, ProgressBar],
standalone: true
})
export class BookCardComponent implements OnInit {
@@ -59,6 +60,16 @@ export class BookCardComponent implements OnInit {
});
}
get progressPercentage(): number | null {
if (this.book.epubProgress?.percentage != null) {
return this.book.epubProgress.percentage;
}
if (this.book.pdfProgress?.percentage != null) {
return this.book.pdfProgress.percentage;
}
return null;
}
onImageLoad(): void {
this.isImageLoaded = true;
}
@@ -18,29 +18,35 @@
<p>{{ currentChapter }}</p>
<div>
<p-button size="small" class="settings-toggle-button" (click)="toggleSettingsDrawer()" icon="pi pi-cog" severity="secondary"></p-button>
<p-drawer [(visible)]="isSettingsDrawerVisible" [modal]="false" [position]="'right'" header="Settings">
<div class="flex flex-col">
<div class="settings-content">
<p>Font Size: {{ fontSize }}%</p>
<div class="flex flex-row gap-4">
<p-button icon="pi pi-minus" (click)="decreaseFontSize()" severity="info"></p-button>
<p-button icon="pi pi-plus" (click)="increaseFontSize()" severity="info"></p-button>
</div>
<p-divider></p-divider>
<label for="font-type">Font Type:</label>
<p-select id="font-type" [options]="fontTypes" [(ngModel)]="selectedFontType" (onChange)="changeFontType()"></p-select>
<p-divider></p-divider>
<label for="theme">Theme:</label>
<p-select id="theme" [options]="themes" [(ngModel)]="selectedTheme" (onChange)="changeThemes()"></p-select>
<p-divider></p-divider>
<label for="flow">Flow:</label>
<p-select id="flow" [options]="flows" [(ngModel)]="selectedFlow" (onChange)="changeScrollMode()"></p-select>
</div>
<div class="flex gap-4">
<div *ngIf="!locationsReady" class="location-indicator" pTooltip="Saving progress not ready yet">
<span class="dot"></span>
</div>
</p-drawer>
<div>
<p-button size="small" class="settings-toggle-button" (click)="toggleSettingsDrawer()" icon="pi pi-cog" severity="secondary"></p-button>
<p-drawer [(visible)]="isSettingsDrawerVisible" [modal]="false" [position]="'right'" header="Settings">
<div class="flex flex-col">
<div class="settings-content">
<p>Font Size: {{ fontSize }}%</p>
<div class="flex flex-row gap-4">
<p-button icon="pi pi-minus" (click)="decreaseFontSize()" severity="info"></p-button>
<p-button icon="pi pi-plus" (click)="increaseFontSize()" severity="info"></p-button>
</div>
<p-divider></p-divider>
<label for="font-type">Font Type:</label>
<p-select id="font-type" [options]="fontTypes" [(ngModel)]="selectedFontType" (onChange)="changeFontType()"></p-select>
<p-divider></p-divider>
<label for="theme">Theme:</label>
<p-select id="theme" [options]="themes" [(ngModel)]="selectedTheme" (onChange)="changeThemes()"></p-select>
<p-divider></p-divider>
<label for="flow">Flow:</label>
<p-select id="flow" [options]="flows" [(ngModel)]="selectedFlow" (onChange)="changeScrollMode()"></p-select>
</div>
</div>
</p-drawer>
</div>
</div>
</div>
</div>
<div id="epubContainer" #epubContainer></div>
@@ -110,3 +110,17 @@
width: 100%;
margin-top: 5px;
}
.location-indicator {
display: flex;
align-items: center;
margin-left: 0.5rem;
.dot {
height: 10px;
width: 10px;
background-color: red;
border-radius: 50%;
display: inline-block;
box-shadow: 0 0 4px #bbb;
}
}
@@ -13,6 +13,7 @@ import {Select} from 'primeng/select';
import {UserService} from '../../../../settings/user-management/user.service';
import {ProgressSpinner} from 'primeng/progressspinner';
import {MessageService} from 'primeng/api';
import {Tooltip} from 'primeng/tooltip';
const FALLBACK_EPUB_SETTINGS = {
fontSize: 150,
@@ -27,10 +28,21 @@ function flatten(chapters: any) {
return [].concat.apply([], chapters.map((chapter: any) => [].concat.apply([chapter], flatten(chapter.subitems))));
}
export function getCfiFromHref(book: any, href: string): string {
export function getCfiFromHref(book: any, href: string): string | null {
const [_, id] = href.split('#');
const section = book.spine.get(href);
const el = (id ? section.document.getElementById(id) : section.document.body) as Element;
if (!section || !section.document) {
console.warn('Section or section.document is undefined for href:', href);
return null;
}
const el = id ? section.document.getElementById(id) : section.document.body;
if (!el) {
console.warn('Element not found in section.document for href:', href);
return null;
}
return section.cfiFromElement(el);
}
@@ -41,7 +53,11 @@ export function getChapter(book: any, location: any) {
return book.canonical(chapter.href).includes(book.canonical(locationHref));
})
.reduce((result: any | null, chapter: any) => {
const locationAfterChapter = EpubCFI.prototype.compare(location.start.cfi, getCfiFromHref(book, chapter.href)) > 0;
const chapterCfi = getCfiFromHref(book, chapter.href);
if (!chapterCfi) {
return result;
}
const locationAfterChapter = EpubCFI.prototype.compare(location.start.cfi, chapterCfi) > 0;
return locationAfterChapter ? chapter : result;
}, null);
}
@@ -50,7 +66,7 @@ export function getChapter(book: any, location: any) {
selector: 'app-epub-viewer',
templateUrl: './epub-viewer.component.html',
styleUrls: ['./epub-viewer.component.scss'],
imports: [Drawer, Button, NgForOf, FormsModule, Divider, Select, ProgressSpinner, NgIf],
imports: [Drawer, Button, NgForOf, FormsModule, Divider, Select, ProgressSpinner, NgIf, Tooltip],
standalone: true
})
export class EpubViewerComponent implements OnInit, OnDestroy {
@@ -62,6 +78,10 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
isDrawerVisible = false;
isSettingsDrawerVisible = false;
public locationsReady = false;
public approxProgress = 0;
public exactProgress = 0;
private book: any;
private rendition: any;
private keyListener: (e: KeyboardEvent) => void = () => {
@@ -143,11 +163,9 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
allowScriptedContent: true,
});
if (this.epub?.epubProgress) {
this.rendition.display(this.epub.epubProgress);
} else {
this.rendition.display();
}
const displayPromise = this.epub?.epubProgress?.cfi
? this.rendition.display(this.epub.epubProgress.cfi)
: this.rendition.display();
this.themesMap.forEach((theme, name) => {
this.rendition.themes.register(name, theme);
@@ -169,9 +187,11 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.rendition.themes.fontSize(`${this.fontSize}%`);
this.rendition.themes.font(this.selectedFontType);
this.setupKeyListener();
this.trackProgress();
this.isLoading = false;
displayPromise.then(() => {
this.setupKeyListener();
this.trackProgress();
this.isLoading = false;
});
};
fileReader.readAsArrayBuffer(epubData);
@@ -204,7 +224,6 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
this.rendition.themes.fontSize(`${this.fontSize}%`);
this.setupKeyListener();
this.trackProgress();
this.rendition.display(cfi || undefined);
this.updateViewerSetting();
}
@@ -300,22 +319,36 @@ export class EpubViewerComponent implements OnInit, OnDestroy {
}
private trackProgress(): void {
if (this.rendition) {
this.rendition.on('relocated', (location: any) => {
const currentChapter = getChapter(this.book, location);
this.currentChapter = currentChapter?.label;
this.bookService.saveEpubProgress(this.epub.id, location.start.cfi).subscribe();
});
}
if (!this.book || !this.rendition) return;
this.rendition.on('relocated', (location: any) => {
const cfi = location.start.cfi;
const currentIndex = location.start.index;
const totalSpineItems = this.book.spine.items.length;
let percentage: number;
if (this.locationsReady) {
percentage = this.book.locations.percentageFromCfi(cfi);
this.exactProgress = Math.round(percentage * 1000) / 10;
} else {
if (totalSpineItems > 0) {
percentage = currentIndex / totalSpineItems;
} else {
percentage = 0;
}
this.approxProgress = Math.round(percentage * 1000) / 10;
}
this.currentChapter = getChapter(this.book, location)?.label;
this.bookService.saveEpubProgress(this.epub.id, cfi, Math.round(percentage * 1000) / 10).subscribe();
});
this.book.ready.then(() => this.book.locations.generate(10000)).then(() => {
this.locationsReady = true;
});
}
ngOnDestroy(): void {
if (this.rendition) {
this.rendition.off('keyup', this.keyListener);
}
document.removeEventListener('keyup', this.keyListener);
this.trackProgress();
}
themesMap = new Map<string, any>([
@@ -13,6 +13,7 @@
[zoom]="zoom"
[spread]="spread"
[showBookModeButton]="false"
(pagesLoaded)="onPdfPagesLoaded($event)"
(pageChange)="onPageChange($event)"
(zoomChange)="onZoomChange($event)"
(spreadChange)="onSpreadChange($event)">
@@ -17,6 +17,7 @@ import {MessageService} from 'primeng/api';
})
export class PdfViewerComponent implements OnInit, OnDestroy {
isLoading = true;
totalPages: number = 0;
handTool = true;
rotation: 0 | 90 | 180 | 270 = 0;
@@ -59,7 +60,7 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
this.zoom = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'odd';
}
this.page = pdfMeta.pdfProgress || 1;
this.page = pdfMeta.pdfProgress?.page || 1;
this.bookData = pdfData;
this.isLoading = false;
},
@@ -102,8 +103,17 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
updateProgress() {
this.bookService.savePdfProgress(this.bookId, this.page).subscribe();
updateProgress(): void {
const percentage = this.totalPages > 0
? Math.round((this.page / this.totalPages) * 1000) / 10
: 0;
this.bookService.savePdfProgress(this.bookId, this.page, percentage).subscribe();
}
onPdfPagesLoaded(event: any): void {
this.totalPages = event.pagesCount;
console.log('Total pages loaded:', this.totalPages);
}
ngOnDestroy(): void {
@@ -1,11 +1,22 @@
<div class="pt-2 flex flex-col h-full overflow-hidden">
<div *ngIf="metadata$ | async as metadata">
<div class="flex flex-row">
<img [attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)"
class="book-cover placeholder"
alt="Cover of {{ metadata.title }}"
loading="lazy"
width="225"/>
<div class="cover-wrapper relative">
<img
[attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)"
class="book-cover placeholder"
alt="Cover of {{ metadata.title }}"
loading="lazy"
width="225"/>
<p-progressBar
*ngIf="getProgressPercent() !== null"
[value]="getProgressPercent()"
[showValue]="true"
[ngClass]="{ 'progress-complete': getProgressPercent() === 100, 'progress-incomplete': getProgressPercent()! < 100 }"
[style]="{ height: '10px' }">
</p-progressBar>
</div>
<div class="flex flex-col justify-between">
<div class="pl-6 flex flex-col w-full">
@@ -75,6 +86,7 @@
<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>
<p class="whitespace-nowrap"><span class="font-bold">Progress:</span> {{ getProgressPercent() !== null ? getProgressPercent() + '%' : '-' }}</p>
</div>
<p class="pt-2"><span class="font-bold">File Path:</span> {{ book?.filePath }}</p>
@@ -95,7 +107,7 @@
<div *ngIf="metadata$ | async as metadata" class="flex-1 overflow-auto space-y-2 px-2">
<div [ngClass]="{ 'line-clamp-5': !isExpanded, 'line-clamp-none': isExpanded }" class="transition-all duration-300 overflow-hidden description-container">
<div class="readonly-editor px-2">
<p-editor #quillEditor [readonly]="true" [style]="{height: '260px'}" [(ngModel)]="metadata.description">
<p-editor #quillEditor [readonly]="true" [style]="{height: '250px'}" [(ngModel)]="metadata.description">
<ng-template #header>
</ng-template>
</p-editor>
@@ -62,3 +62,4 @@
max-height: none;
overflow: visible;
}
@@ -22,13 +22,14 @@ import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {BookCardComponent} from '../../../components/book-browser/book-card/book-card.component';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Editor} from 'primeng/editor';
import {ProgressBar} from 'primeng/progressbar';
@Component({
selector: 'app-metadata-viewer',
standalone: true,
templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss',
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective, Editor]
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SplitButton, NgClass, Tooltip, DecimalPipe, InfiniteScrollDirective, BookCardComponent, ButtonDirective, Editor, ProgressBar]
})
export class MetadataViewerComponent implements OnInit {
@@ -164,6 +165,14 @@ export class MetadataViewerComponent implements OnInit {
return '-';
}
getProgressPercent(): number | undefined {
if (this.book?.bookType === 'PDF') {
return this.book.pdfProgress?.percentage;
} else {
return this.book?.epubProgress?.percentage;
}
}
getStarColor(rating?: number | null): string {
if (rating == null) {
return 'rgb(203, 213, 225)';
+12 -2
View File
@@ -10,12 +10,22 @@ export interface Book {
shelves?: Shelf[];
lastReadTime?: string;
addedOn?: string;
epubProgress?: string;
pdfProgress?: number;
epubProgress?: EpubProgress;
pdfProgress?: PdfProgress;
filePath?: string;
fileSizeKb?: number;
}
export interface EpubProgress {
cfi: string;
percentage: number;
}
export interface PdfProgress {
page: number;
percentage: number;
}
export interface BookMetadata {
bookId: number;
title: string;
@@ -185,12 +185,26 @@ export class BookService {
window.URL.revokeObjectURL(url);
}
savePdfProgress(bookId: number, progress: number): Observable<void> {
return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, pdfProgress: progress});
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
}
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, progress: string): Observable<void> {
return this.http.post<void>(`${this.url}/progress`, {bookId: bookId, epubProgress: progress});
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
const body = {
bookId: bookId,
epubProgress: {
cfi: cfi,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
regenerateCovers(): Observable<void> {
@@ -276,7 +290,7 @@ export class BookService {
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: { limit: limit.toString() }
params: {limit: limit.toString()}
});
}