/** * Reading analytics (Pro). One session per opened viewer: reports start, * periodic progress (visible reading time, pages viewed, furthest page, * visible time per page), downloads/prints, and a final update when the page * is hidden or closed. * * Active only when the server exposes pdfRackSettings.analytics.endpoint. */ const PING_MS = 20_000; const uuid = (): string => { if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID(); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16); }); }; export class ReadingTracker { private readonly endpoint: string; private readonly session = uuid(); private readonly pdfId: number; private readonly pdfUrl: string; private started = false; private ended = false; private pages = new Set(); private maxPage = 0; private visibleMs = 0; private visibleSince: number | null = null; private timer: number | null = null; /** Visible milliseconds per page, cumulative for the session */ private pageMs = new Map(); private currentPage = 0; private pageSince: number | null = null; private readonly onVisibility = () => this.handleVisibility(); private readonly onPageHide = () => this.flush('end'); constructor(endpoint: string, pdfId: number, pdfUrl: string) { this.endpoint = endpoint; this.pdfId = pdfId; this.pdfUrl = pdfUrl; } /** Viewer reported a page (also used to start the session). */ page(page: number, total: number): void { if (!this.started) { if (total <= 0) return; this.start(total); } if (page > 0) { this.pages.add(page); this.maxPage = Math.max(this.maxPage, page); if (page !== this.currentPage) { this.bankPage(); this.currentPage = page; this.pageSince = document.visibilityState === 'visible' ? performance.now() : null; } } } action(action: 'download' | 'print'): void { if (!this.started) return; this.send({ event: action }, false); } /** Viewer destroyed (e.g. lightbox closed). */ stop(): void { if (this.started && !this.ended) this.flush('end'); this.ended = true; this.detach(); } private start(total: number): void { this.started = true; this.send({ event: 'start', pdfId: this.pdfId, pdfUrl: this.pdfId ? undefined : this.pdfUrl, totalPages: total, pageUrl: window.location.href.split('#')[0], }, false); if (document.visibilityState === 'visible') this.visibleSince = performance.now(); document.addEventListener('visibilitychange', this.onVisibility); window.addEventListener('pagehide', this.onPageHide); this.timer = window.setInterval(() => { if (document.visibilityState === 'visible') this.flush('ping'); }, PING_MS); } /** Add the time spent on the current page so far. */ private bankPage(): void { if (this.currentPage && this.pageSince !== null) { const ms = performance.now() - this.pageSince; this.pageMs.set(this.currentPage, (this.pageMs.get(this.currentPage) ?? 0) + ms); } this.pageSince = null; } private pageTimes(): Record { const out: Record = {}; this.pageMs.forEach((ms, page) => { const seconds = Math.round(ms / 1000); if (seconds > 0) out[page] = seconds; }); return out; } private handleVisibility(): void { if (document.visibilityState === 'visible') { this.visibleSince = performance.now(); if (this.currentPage) this.pageSince = performance.now(); } else { this.flush('end'); } } private duration(): number { let ms = this.visibleMs; if (this.visibleSince !== null) ms += performance.now() - this.visibleSince; return Math.round(ms / 1000); } private flush(event: 'ping' | 'end'): void { if (!this.started) return; // Bank the visible time so far if (this.visibleSince !== null) { this.visibleMs += performance.now() - this.visibleSince; this.visibleSince = document.visibilityState === 'visible' ? performance.now() : null; } this.bankPage(); if (document.visibilityState === 'visible' && this.currentPage) this.pageSince = performance.now(); this.send({ event, duration: this.duration(), pagesViewed: this.pages.size, maxPage: this.maxPage, pageTimes: this.pageTimes(), }, event === 'end'); } private send(payload: Record, beacon: boolean): void { const body = JSON.stringify({ session: this.session, ...payload }); try { if (beacon && navigator.sendBeacon) { navigator.sendBeacon(this.endpoint, new Blob([body], { type: 'application/json' })); return; } void fetch(this.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, keepalive: true, credentials: 'same-origin', }).catch(() => undefined); } catch { /* analytics must never break the viewer */ } } private detach(): void { if (this.timer) { clearInterval(this.timer); this.timer = null; } document.removeEventListener('visibilitychange', this.onVisibility); window.removeEventListener('pagehide', this.onPageHide); } }