Add hosted service-worker streaming downloads
This commit is contained in:
1 parent
a53022d717
commit
7856725c72
8 files changed
+344
-17
No files matched your search
@@ -7,6 +7,7 @@ import NetworkSettings from './NetworkSettings.vue';
|
||||
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
|
||||
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
|
||||
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
|
||||
import { createDownloadDestination, supportsStreamingDownload } from '../lib/download.ts';
|
||||
|
||||
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
|
||||
interface Session {
|
||||
@@ -40,6 +41,8 @@ const defaultStun = location.protocol === 'file:' ? '' : import.meta.env.VITE_ST
|
||||
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
|
||||
const managedCredentials = ref<IceOptions | null>(null);
|
||||
const canSaveToDisk = typeof window.showSaveFilePicker === 'function';
|
||||
const canStreamDownload = supportsStreamingDownload();
|
||||
const streamedDownload = ref(false);
|
||||
let active: Session | null = null;
|
||||
let copyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const busy = computed(() => !['idle', 'closed', 'done'].includes(step.value));
|
||||
@@ -53,7 +56,7 @@ const status = computed(() => ({
|
||||
'choose-storage': 'Choose how to receive this file.',
|
||||
sending: 'Sending…', receiving: 'Receiving…', saving: 'Saving file…',
|
||||
'awaiting-receipt': 'Waiting for the receiver to confirm the complete file…',
|
||||
done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : 'File saved to disk.'),
|
||||
done: props.sending ? 'The receiver confirmed the complete file.' : (downloadUrl.value ? 'File received. Save it below.' : streamedDownload.value ? 'File handed to your browser. Check Downloads for the final save result.' : 'File saved to disk.'),
|
||||
closed: props.sending
|
||||
? 'Create a new code, then ask the receiver for a new answer. Previous codes cannot reopen a closed connection.'
|
||||
: 'Ask the sender for a new code and paste it above. Previous codes cannot reopen a closed connection.',
|
||||
@@ -83,7 +86,7 @@ function reset(keepNetwork = false) {
|
||||
inputCode.value = outputCode.value = error.value = '';
|
||||
fps.value = incoming.value = null;
|
||||
verified.value = copied.value = choosing.value = false;
|
||||
progress.value = 0; step.value = 'idle';
|
||||
progress.value = 0; step.value = 'idle'; streamedDownload.value = false;
|
||||
}
|
||||
function fail(session: Session, err: unknown) {
|
||||
if (active !== session) return;
|
||||
@@ -216,19 +219,24 @@ function verify() {
|
||||
session.timer = setTimeout(() => { if (active === session && !session.transfer) fail(session, new Error('Connection timed out.')); }, 60000);
|
||||
session.transfer?.verify();
|
||||
}
|
||||
async function acceptFile(toDisk: boolean) {
|
||||
async function acceptFile(destination: 'disk' | 'memory' | 'download') {
|
||||
const session = active;
|
||||
if (!session?.transfer || !incoming.value || choosing.value || step.value !== 'choose-storage') return;
|
||||
choosing.value = true; error.value = '';
|
||||
let writable: FileDestination | undefined;
|
||||
try {
|
||||
if (toDisk) {
|
||||
if (destination === 'download') {
|
||||
writable = await createDownloadDestination(incoming.value, session.controller.signal);
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
} else if (destination === 'disk') {
|
||||
if (!window.showSaveFilePicker) throw new Error('Direct-to-disk saving is unavailable.');
|
||||
const handle = await window.showSaveFilePicker({ suggestedName: incoming.value.name });
|
||||
if (active !== session) return;
|
||||
writable = await handle.createWritable();
|
||||
if (active !== session) { await writable.abort(); return; }
|
||||
}
|
||||
streamedDownload.value = destination === 'download';
|
||||
session.diagnostics.record(`storage ${destination}`);
|
||||
session.transfer.accept(writable);
|
||||
} catch (err) {
|
||||
if (writable) await writable.abort().catch(() => {});
|
||||
@@ -292,9 +300,11 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
|
||||
<div v-if="incoming && step === 'choose-storage'" class="incoming">
|
||||
<p>{{ incoming.name }} — {{ formatBytes(incoming.size) }}</p>
|
||||
<p class="status">Only accept files you expect. Encryption does not make their contents safe to open.</p>
|
||||
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile(true)">Choose destination & receive to disk</button>
|
||||
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile(false)">Receive in memory (up to 64 MiB)</button>
|
||||
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
|
||||
<button v-if="canStreamDownload" class="primary" :disabled="choosing" @click="acceptFile('download')">Receive as download (up to 64 GiB)</button>
|
||||
<p v-if="canStreamDownload" class="status">Allow the browser download and keep this page open until the transfer finishes. Check Downloads for the final save result.</p>
|
||||
<button v-if="canSaveToDisk" class="primary" :disabled="choosing" @click="acceptFile('disk')">Choose destination & receive to disk</button>
|
||||
<button :disabled="choosing || incoming.size > MEMORY_LIMIT" @click="acceptFile('memory')">Receive in memory (up to 64 MiB)</button>
|
||||
<p v-if="incoming.size > MEMORY_LIMIT && !canSaveToDisk && !canStreamDownload" class="error">This browser cannot save directly to disk. Use a browser with file-system saving support or send a smaller file.</p>
|
||||
</div>
|
||||
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
|
||||
<p class="status" role="status">{{ status }}</p>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { FileDestination, FileMetadata } from './transfer.ts';
|
||||
|
||||
export function supportsStreamingDownload() {
|
||||
if (!['https:', 'http:'].includes(location.protocol) || !isSecureContext ||
|
||||
!navigator.serviceWorker || typeof TransformStream === 'undefined') return false;
|
||||
const channel = new MessageChannel();
|
||||
const stream = new ReadableStream({ start(controller) { controller.close(); } });
|
||||
try { channel.port1.postMessage(stream, [stream]); return true; }
|
||||
catch { return false; }
|
||||
finally { channel.port1.close(); channel.port2.close(); }
|
||||
}
|
||||
|
||||
export async function createDownloadDestination(meta: FileMetadata, signal: AbortSignal): Promise<FileDestination> {
|
||||
if (!supportsStreamingDownload()) throw new Error('Streaming downloads require a supported browser and HTTPS or localhost.');
|
||||
signal.throwIfAborted();
|
||||
const stream = new TransformStream<Uint8Array, Uint8Array>();
|
||||
const writer = stream.writable.getWriter();
|
||||
const channel = new MessageChannel();
|
||||
const frame = document.createElement('iframe');
|
||||
frame.hidden = true; frame.title = 'File download';
|
||||
let finished = false;
|
||||
let stopWatchingWorker = () => {};
|
||||
let resolveReady!: () => void, rejectReady!: (error: Error) => void;
|
||||
let resolveComplete!: () => void, rejectComplete!: (error: Error) => void;
|
||||
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const complete = new Promise<void>((resolve, reject) => { resolveComplete = resolve; rejectComplete = reject; });
|
||||
void ready.catch(() => {}); void complete.catch(() => {}); void writer.closed.catch(() => {});
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
stopWatchingWorker();
|
||||
signal.removeEventListener('abort', canceled);
|
||||
window.removeEventListener('pagehide', canceled);
|
||||
channel.port1.close(); frame.remove();
|
||||
};
|
||||
const fail = (error: Error) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
channel.port1.postMessage({ type: 'abort' });
|
||||
rejectReady(error); rejectComplete(error);
|
||||
void writer.abort(error).catch(() => {});
|
||||
cleanup();
|
||||
};
|
||||
const canceled = () => fail(new DOMException('Transfer canceled.', 'AbortError'));
|
||||
const timer = setTimeout(() => fail(new Error('Streaming download did not start. Check browser download permissions and try again.')), 30000);
|
||||
signal.addEventListener('abort', canceled, { once: true });
|
||||
window.addEventListener('pagehide', canceled);
|
||||
try {
|
||||
const registration = await Promise.race([
|
||||
navigator.serviceWorker.register(new URL('./download/worker.js', location.href).href),
|
||||
ready.then(() => { throw new Error('Unexpected download state.'); }),
|
||||
]);
|
||||
const worker = registration.active || registration.installing || registration.waiting;
|
||||
if (!worker) throw new Error('Download service worker is unavailable.');
|
||||
if (worker.state !== 'activated') await Promise.race([
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const changed = () => {
|
||||
if (worker.state === 'activated' || worker.state === 'redundant') {
|
||||
worker.removeEventListener('statechange', changed);
|
||||
worker.state === 'activated' ? resolve() : reject(new Error('Download service worker could not activate.'));
|
||||
}
|
||||
};
|
||||
stopWatchingWorker = () => worker.removeEventListener('statechange', changed);
|
||||
worker.addEventListener('statechange', changed); changed();
|
||||
}), ready,
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (finished) await ready;
|
||||
const id = Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
const url = new URL(`file-${id}`, registration.scope).href;
|
||||
channel.port1.onmessage = event => {
|
||||
if (event.data?.type === 'ready' && event.data.url === url) {
|
||||
frame.src = url; document.body.append(frame);
|
||||
}
|
||||
if (event.data?.type === 'started') { clearTimeout(timer); resolveReady(); }
|
||||
if (event.data?.type === 'error') fail(new Error(event.data.message || 'Download failed.'));
|
||||
if (event.data?.type === 'complete' && !finished) {
|
||||
finished = true; resolveComplete(); cleanup();
|
||||
}
|
||||
};
|
||||
worker.postMessage({ type: 'download', id, name: meta.name, size: meta.size, stream: stream.readable }, [channel.port2, stream.readable]);
|
||||
await ready;
|
||||
return {
|
||||
async write(data) { await writer.write(new Uint8Array(data)); },
|
||||
async close() { await writer.close(); await complete; },
|
||||
async abort() { canceled(); },
|
||||
};
|
||||
} catch (error) { fail(error instanceof Error ? error : new Error('Could not start download.')); throw error; }
|
||||
}
|
||||
Reference in new issue
Block a user