59 lines
1.9 KiB
JavaScript
59 lines
1.9 KiB
JavaScript
/**
|
|
* session.js
|
|
* ----------
|
|
* Page-load session restore.
|
|
*
|
|
* On every page load — including hard browser reloads (Ctrl+Shift+R) and
|
|
* opening the app in a new tab — asks the server whether a job is active,
|
|
* fetches its full snapshot, and reconnects the live SSE stream if needed.
|
|
*
|
|
* This does NOT depend on sessionStorage surviving the reload (though
|
|
* sessionStorage is still written as a fast secondary hint).
|
|
*
|
|
* Exports
|
|
* -------
|
|
* tryRestoreSession() — call once at startup
|
|
*/
|
|
|
|
import { announce } from './state.js';
|
|
import { applySnapshot, startProgressStream } from './stream.js';
|
|
import { showResults } from './progress.js';
|
|
|
|
/**
|
|
* Query the server for active/recent jobs and restore the UI if one is found.
|
|
*
|
|
* Strategy:
|
|
* 1. GET /api/compress/active — find the most recent running job (or any job)
|
|
* 2. GET /api/compress/status/<id> — fetch the full snapshot
|
|
* 3. applySnapshot() to rebuild all progress bars
|
|
* 4. If still running: re-attach the SSE stream
|
|
* 5. If done/cancelled: show the results card
|
|
*/
|
|
export async function tryRestoreSession() {
|
|
try {
|
|
const activeResp = await fetch('/api/compress/active');
|
|
if (!activeResp.ok) return;
|
|
|
|
const { jobs } = await activeResp.json();
|
|
if (!jobs.length) return;
|
|
|
|
// Prefer the most recent running job; fall back to any job
|
|
const candidate = jobs.find(j => j.status === 'running') || jobs[0];
|
|
|
|
const snapResp = await fetch(`/api/compress/status/${candidate.job_id}`);
|
|
if (!snapResp.ok) return;
|
|
|
|
const snap = await snapResp.json();
|
|
applySnapshot(snap);
|
|
announce('Active compression job restored.');
|
|
|
|
if (snap.status === 'running') {
|
|
startProgressStream(snap.job_id, snap.files);
|
|
} else if (snap.status === 'done' || snap.status === 'cancelled') {
|
|
showResults(snap.status);
|
|
sessionStorage.removeItem('vp-job-id');
|
|
}
|
|
} catch {
|
|
// Server unreachable or no jobs — start fresh, no action needed
|
|
}
|
|
}
|