Introduce reading session tracking with visual insights (#1957)

* Introduce reading session tracking with visual insights (#1957)

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2025-12-21 21:14:42 -07:00
committed by GitHub
co-authored by acx10
parent b12fc82414
commit b5ada2fff0
39 changed files with 2526 additions and 406 deletions
@@ -53,9 +53,14 @@
</li>
}
<li>
<a class="topbar-item" (click)="navigateToStats()" pTooltip="Stats" tooltipPosition="bottom">
<button
class="topbar-item"
(click)="statsMenu.toggle($event)"
pTooltip="Stats"
tooltipPosition="bottom">
<i class="pi pi-chart-bar text-surface-100"></i>
</a>
</button>
<p-menu #statsMenu [model]="statsMenuItems" [popup]="true" appendTo="body" />
</li>
@if (userService.userState$ | async; as userState) {
<li>
@@ -192,11 +197,12 @@
<li>
<button
class="flex items-center gap-2 w-full text-left p-2 hover:bg-surface-200 dark:hover:bg-surface-700 rounded"
(click)="navigateToStats(); mobileMenu.hide()"
(click)="statsMenu.toggle($event)"
>
<i class="pi pi-chart-bar text-surface-100"></i>
Charts
</button>
<p-menu #statsMenuMobile [model]="statsMenuItems" [popup]="true" />
</li>
<li>
<button
@@ -24,6 +24,7 @@ import {BookdropFileService} from '../../../../features/bookdrop/service/bookdro
import {DialogLauncherService} from '../../../services/dialog-launcher.service';
import {UnifiedNotificationBoxComponent} from '../../../components/unified-notification-popover/unified-notification-popover-component';
import {Severity, LogNotification} from '../../../websocket/model/log-notification.model';
import {Menu} from 'primeng/menu';
@Component({
selector: 'app-topbar',
@@ -45,11 +46,13 @@ import {Severity, LogNotification} from '../../../websocket/model/log-notificati
Popover,
UnifiedNotificationBoxComponent,
NgStyle,
Menu,
],
})
export class AppTopBarComponent implements OnDestroy {
items!: MenuItem[];
ref?: DynamicDialogRef;
statsMenuItems: MenuItem[] = [];
@ViewChild('menubutton') menuButton!: ElementRef;
@ViewChild('topbarmenubutton') topbarMenuButton!: ElementRef;
@@ -80,6 +83,7 @@ export class AppTopBarComponent implements OnDestroy {
private bookdropFileService: BookdropFileService,
private dialogLauncher: DialogLauncherService
) {
this.initializeStatsMenu();
this.subscribeToMetadataProgress();
this.subscribeToNotifications();
@@ -143,7 +147,11 @@ export class AppTopBarComponent implements OnDestroy {
}
navigateToStats() {
this.router.navigate(['/stats']);
this.router.navigate(['/library-stats']);
}
navigateToUserStats() {
this.router.navigate(['/reading-stats']);
}
logout() {
@@ -191,6 +199,21 @@ export class AppTopBarComponent implements OnDestroy {
this.hasActiveOrCompletedTasks = this.hasActiveOrCompletedTasks || this.hasPendingBookdropFiles;
}
private initializeStatsMenu() {
this.statsMenuItems = [
{
label: 'Library Stats',
icon: 'pi pi-chart-line',
command: () => this.navigateToStats()
},
{
label: 'Reading Stats',
icon: 'pi pi-users',
command: () => this.navigateToUserStats()
}
];
}
get iconClass(): string {
if (this.progressHighlight) return 'pi-spinner spin';
if (this.iconPulsating) return 'pi-wave-pulse';
@@ -0,0 +1,288 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { fromEvent, merge, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { API_CONFIG } from '../../core/config/api-config';
import {BookType} from '../../features/book/model/book.model';
export interface ReadingSession {
bookId: number;
bookType: BookType;
startTime: Date;
endTime?: Date;
durationSeconds?: number;
startLocation?: string;
endLocation?: string;
startProgress?: number;
endProgress?: number;
progressDelta?: number;
}
@Injectable({
providedIn: 'root'
})
export class ReadingSessionService {
private readonly http = inject(HttpClient);
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/reading-sessions`;
private currentSession: ReadingSession | null = null;
private idleTimer: ReturnType<typeof setTimeout> | null = null;
private activitySubscription: Subscription | null = null;
private readonly IDLE_TIMEOUT_MS = 5 * 60 * 1000;
private readonly MIN_SESSION_DURATION_SECONDS = 30;
private readonly ACTIVITY_DEBOUNCE_MS = 1000;
constructor() {
this.setupBrowserLifecycleListeners();
}
private setupBrowserLifecycleListeners(): void {
window.addEventListener('beforeunload', () => {
if (this.currentSession) {
this.endSessionSync();
}
});
document.addEventListener('visibilitychange', () => {
if (document.hidden && this.currentSession) {
this.log('Tab hidden, pausing session');
this.pauseIdleDetection();
} else if (!document.hidden && this.currentSession) {
this.log('Tab visible, resuming session');
this.resumeIdleDetection();
}
});
}
startSession(bookId: number, bookType: BookType, startLocation?: string, startProgress?: number): void {
if (this.currentSession) {
this.endSession();
}
this.currentSession = {
bookId,
bookType,
startTime: new Date(),
startLocation,
startProgress
};
this.log('Reading session started', {
bookId,
startTime: this.currentSession.startTime.toISOString(),
startLocation,
startProgress: startProgress != null ? `${startProgress.toFixed(1)}%` : 'N/A'
});
this.startIdleDetection();
}
updateProgress(currentLocation?: string, currentProgress?: number): void {
if (!this.currentSession) {
return;
}
this.currentSession.endLocation = currentLocation;
this.currentSession.endProgress = currentProgress;
this.resetIdleTimer();
}
endSession(endLocation?: string, endProgress?: number): void {
if (!this.currentSession) {
return;
}
this.stopIdleDetection();
this.currentSession.endTime = new Date();
this.currentSession.endLocation = endLocation ?? this.currentSession.endLocation;
this.currentSession.endProgress = endProgress ?? this.currentSession.endProgress;
const durationMs = this.currentSession.endTime.getTime() - this.currentSession.startTime.getTime();
this.currentSession.durationSeconds = Math.floor(durationMs / 1000);
if (this.currentSession.startProgress != null && this.currentSession.endProgress != null) {
this.currentSession.progressDelta = this.currentSession.endProgress - this.currentSession.startProgress;
}
if (this.currentSession.durationSeconds >= this.MIN_SESSION_DURATION_SECONDS) {
this.sendSessionToBackend(this.currentSession);
} else {
this.log('Session too short, discarding', {
durationSeconds: this.currentSession.durationSeconds
});
}
this.currentSession = null;
}
private endSessionSync(): void {
if (!this.currentSession) {
return;
}
const endTime = new Date();
const durationMs = endTime.getTime() - this.currentSession.startTime.getTime();
const durationSeconds = Math.floor(durationMs / 1000);
if (durationSeconds < this.MIN_SESSION_DURATION_SECONDS) {
this.cleanup();
return;
}
const sessionData = this.buildSessionData(
this.currentSession,
endTime,
durationSeconds
);
this.log('Reading session ended (sync)', sessionData);
try {
const blob = new Blob([JSON.stringify(sessionData)], { type: 'application/json' });
const success = navigator.sendBeacon(this.url, blob);
if (!success) {
this.logError('sendBeacon failed, request may not have been queued');
}
} catch (error) {
this.logError('Failed to send session data', error);
}
this.cleanup();
}
private sendSessionToBackend(session: ReadingSession): void {
if (!session.endTime || session.durationSeconds == null) {
this.logError('Invalid session data, missing endTime or duration');
return;
}
const sessionData = this.buildSessionData(
session,
session.endTime,
session.durationSeconds
);
this.log('Reading session completed', sessionData);
this.http.post<void>(this.url, sessionData).subscribe({
next: () => this.log('Session saved to backend'),
error: (err: HttpErrorResponse) => this.logError('Failed to save session', err)
});
}
private buildSessionData(session: ReadingSession, endTime: Date, durationSeconds: number) {
return {
bookId: session.bookId,
bookType: session.bookType,
startTime: session.startTime.toISOString(),
endTime: endTime.toISOString(),
durationSeconds,
durationFormatted: this.formatDuration(durationSeconds),
startProgress: session.startProgress,
endProgress: session.endProgress,
progressDelta: session.progressDelta,
startLocation: session.startLocation,
endLocation: session.endLocation
};
}
private formatDuration(seconds: number): string {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}h ${minutes}m ${secs}s`;
} else if (minutes > 0) {
return `${minutes}m ${secs}s`;
}
return `${secs}s`;
}
private startIdleDetection(): void {
this.stopIdleDetection();
const activity$ = merge(
fromEvent(document, 'mousemove'),
fromEvent(document, 'mousedown'),
fromEvent(document, 'keypress'),
fromEvent(document, 'scroll'),
fromEvent(document, 'touchstart')
).pipe(
debounceTime(this.ACTIVITY_DEBOUNCE_MS)
);
this.activitySubscription = activity$.subscribe(() => {
this.resetIdleTimer();
});
this.resetIdleTimer();
}
private pauseIdleDetection(): void {
if (this.idleTimer) {
clearTimeout(this.idleTimer);
this.idleTimer = null;
}
if (this.activitySubscription) {
this.activitySubscription.unsubscribe();
this.activitySubscription = null;
}
}
private resumeIdleDetection(): void {
if (this.currentSession) {
this.startIdleDetection();
}
}
private resetIdleTimer(): void {
if (this.idleTimer) {
clearTimeout(this.idleTimer);
}
this.idleTimer = setTimeout(() => {
this.log('User idle detected, ending session');
this.endSession();
}, this.IDLE_TIMEOUT_MS);
}
private stopIdleDetection(): void {
if (this.idleTimer) {
clearTimeout(this.idleTimer);
this.idleTimer = null;
}
if (this.activitySubscription) {
this.activitySubscription.unsubscribe();
this.activitySubscription = null;
}
}
private cleanup(): void {
this.stopIdleDetection();
this.currentSession = null;
}
isSessionActive(): boolean {
return this.currentSession !== null;
}
private log(message: string, data?: any): void {
if (data) {
console.log(`[ReadingSession] ${message}`, data);
} else {
console.log(`[ReadingSession] ${message}`);
}
}
private logError(message: string, error?: any): void {
if (error) {
console.error(`[ReadingSession] ${message}`, error);
} else {
console.error(`[ReadingSession] ${message}`);
}
}
}
@@ -3,8 +3,8 @@ import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
import {BookService} from '../../features/book/service/book.service';
import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component';
import { Router } from '@angular/router';
import { Book } from '../../features/book/model/book.model';
import {Router} from '@angular/router';
import {Book} from '../../features/book/model/book.model';
@Injectable({
providedIn: 'root'
@@ -33,11 +33,20 @@ export class UrlHelperService {
coverGenerator.title = book.metadata.title || '';
coverGenerator.author = (book.metadata.authors || []).join(', ');
return coverGenerator.generateCover();
} else {
return 'assets/images/missing-cover.jpg';
}
}
const url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail?${coverUpdatedOn}`;
let url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail`;
if (coverUpdatedOn) {
url += `?${coverUpdatedOn}`;
}
return this.appendToken(url);
}
getThumbnailUrl1(bookId: number, coverUpdatedOn?: string): string {
let url = `${this.mediaBaseUrl}/book/${bookId}/thumbnail`;
if (coverUpdatedOn) {
url += `?${coverUpdatedOn}`;
}
return this.appendToken(url);
}
@@ -49,11 +58,12 @@ export class UrlHelperService {
coverGenerator.title = book.metadata.title || '';
coverGenerator.author = (book.metadata.authors || []).join(', ');
return coverGenerator.generateCover();
} else {
return 'assets/images/missing-cover.jpg';
}
}
const url = `${this.mediaBaseUrl}/book/${bookId}/cover?${coverUpdatedOn}`;
let url = `${this.mediaBaseUrl}/book/${bookId}/cover`;
if (coverUpdatedOn) {
url += `?${coverUpdatedOn}`;
}
return this.appendToken(url);
}
@@ -67,25 +77,13 @@ export class UrlHelperService {
return this.appendToken(url);
}
getBackgroundImageUrl(lastUpdated?: number): string {
let url = `${this.mediaBaseUrl}/background`;
if (lastUpdated) {
url += `?t=${lastUpdated}`;
}
const token = this.getToken();
if (token) {
url += `${url.includes('?') ? '&' : '?'}token=${token}`;
}
return url;
}
getBookUrl(book: Book) {
return this.router.createUrlTree(['/book', book.id], {
queryParams: {tab: 'view'}
});
}
filterBooksBy(filterKey: string, filterValue: string){
filterBooksBy(filterKey: string, filterValue: string) {
if (filterKey === 'series') {
return this.router.createUrlTree(['/series', encodeURIComponent(filterValue)])
}
@@ -100,9 +98,4 @@ export class UrlHelperService {
}
});
}
getIconUrl(iconName: string): string {
const url = `${this.mediaBaseUrl}/icon/${iconName}`;
return this.appendToken(url);
}
}