import React from "react"; import {API_URI} from "../components/Vars"; /* * How far the user is through a file, and where to resume it (see wrolpi/files/progress.py). * * The server is the source of truth; its FileGroup JSON carries `progress` and `position`. Every save is * also written to sessionStorage, because the final save sent while leaving a page can still be in flight * when the user comes straight back, and the server would then answer with an older position. Whichever * of the two is newer wins. */ const HEARTBEAT_MS = 15_000; const CACHE_PREFIX = 'wrolpi-progress:'; // Mirrors wrolpi/files/progress.py, so a position the server would discard is not resumed from the cache. const FINISHED_PROGRESS = 0.95; const MINIMUM_PROGRESS = 0.01; const MINIMUM_SECONDS = 10; function readCache(path) { try { const raw = window.sessionStorage.getItem(CACHE_PREFIX + path); return raw ? JSON.parse(raw) : null; } catch (e) { return null; } } function writeCache(path, entry) { try { window.sessionStorage.setItem(CACHE_PREFIX + path, JSON.stringify(entry)); } catch (e) { // Storage is unavailable (private mode, quota); the server still has the position. } } /** Send progress to the server. A final save uses a beacon, which survives the page closing. */ export function sendProgress(path, progress, position, final = false) { const url = `${API_URI}/files/progress`; const body = JSON.stringify({file: path, progress, position, final}); if (final && navigator.sendBeacon) { if (navigator.sendBeacon(url, new Blob([body], {type: 'application/json'}))) { return; } } fetch(url, {method: 'POST', body, keepalive: true}) .catch(e => console.error('Failed to save progress', e)); } export function isResumable(progress, position) { if (!position || progress === null || progress === undefined) { return false; } if (progress >= FINISHED_PROGRESS || progress < MINIMUM_PROGRESS) { return false; } if (position.kind === 'time') { return position.seconds >= MINIMUM_SECONDS; } if (position.kind === 'page') { return position.page > 0; } return true; } /** * Where to resume `path`: the newer of the server's position (from `fileGroup`) and this tab's own. * * @returns {object|null} A position, or null to start from the beginning. */ export function getResumePosition(path, fileGroup) { if (!path) { return null; } let best = null; let bestTime = -1; if (fileGroup && fileGroup.progress !== null && fileGroup.progress !== undefined) { // A finished file has no position; when it was finished is when it was viewed. bestTime = fileGroup.position?.updated_at ?? (Date.parse(fileGroup.viewed) || 0); best = {progress: fileGroup.progress, position: fileGroup.position}; } const cached = readCache(path); if (cached && cached.updated_at > bestTime) { best = cached; } return best && isResumable(best.progress, best.position) ? best.position : null; } /** * Save how far the user is through `path`. * * The viewer calls `report({progress, position})` as the user moves through the file; that is only * remembered. It is sent every 15 seconds if it changed, and as a final save when `save(true)` is called * (pause, end), when the page is hidden or closed, and when `path` changes or the viewer unmounts. * * The last report is kept rather than read from the viewer at unmount, because by then React has detached * the viewer's elements. */ export function useFileProgress(path, {enabled = true} = {}) { const snapshotRef = React.useRef(null); const sentRef = React.useRef(null); const report = React.useCallback((snapshot) => { snapshotRef.current = snapshot; }, []); const save = React.useCallback((final = false) => { const snapshot = snapshotRef.current; if (!path || !enabled || !snapshot) { return; } const key = JSON.stringify(snapshot); if (!final && key === sentRef.current) { return; } sentRef.current = key; const updated_at = Date.now(); const position = snapshot.position ? {...snapshot.position, updated_at} : null; writeCache(path, {progress: snapshot.progress, position, updated_at}); sendProgress(path, snapshot.progress, position, final); }, [path, enabled]); React.useEffect(() => { if (!path || !enabled) { return; } // A new file starts with nothing to save. snapshotRef.current = null; sentRef.current = null; const interval = setInterval(() => save(false), HEARTBEAT_MS); const onVisibilityChange = () => { if (document.visibilityState === 'hidden') { save(true); } }; const onPageHide = () => save(true); document.addEventListener('visibilitychange', onVisibilityChange); window.addEventListener('pagehide', onPageHide); return () => { clearInterval(interval); document.removeEventListener('visibilitychange', onVisibilityChange); window.removeEventListener('pagehide', onPageHide); save(true); }; }, [path, enabled, save]); return {report, save}; } /** * Track and resume a