Ask before downloading and show transfer progress

Tracker codes now use 8 of [0-9a-zA-Z] instead of 8 digits. After both
security checks the receiver sees the offered file and starts the download
itself, the sender waits for it. Both sides show a progress bar of what the
download manager has read. Copy buttons for the tracker code, offer and
answer; the manual exchange is folded away below the tracker on both sides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
SchluffeandClaude Opus 5.5 committed 2026-10-24 14:15:48 +02:00
1 parent 85ccdbfc03
commit bacc15baaf
4 files changed
+314 -65

No files matched your search

+38 -5
View File
@@ -6,6 +6,8 @@ import { createServer, type ViteDevServer } from 'vite';
// Runs against the real public trackers and STUN servers, the defaults in src/main.ts. // Runs against the real public trackers and STUN servers, the defaults in src/main.ts.
const BROWSERS: Record<string, BrowserType> = { chromium, firefox }; const BROWSERS: Record<string, BrowserType> = { chromium, firefox };
// Chromium needs a permission for the copy buttons, Firefox lets the click do it and rejects the name.
const PERMISSIONS: Record<string, string[]> = { chromium: ['clipboard-write'], firefox: [] };
const SIZE = 5_000_000; const SIZE = 5_000_000;
// Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS // Opt-in with LARGE=1: beyond what fits comfortably in RAM and beyond the 2000 MiB the old OPFS
// staging could store in incognito-like contexts. // staging could store in incognito-like contexts.
@@ -18,8 +20,12 @@ const WINDOW = 8 * 2 ** 20;
// Each mode connects a sender page that already picked a file to a receiver page. // Each mode connects a sender page that already picked a file to a receiver page.
const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = { const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
async manual(sender, receiver) { async manual(sender, receiver) {
await sender.click('#send-manual summary');
await sender.click('#create-offer'); await sender.click('#create-offer');
await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 }); await expect(sender.locator('#offer')).toHaveValue(/.+/, { timeout: 15_000 });
await sender.click('#copy-offer');
await expect(sender.locator('#copy-offer')).toHaveText('Copied');
await receiver.click('#receive-manual summary');
await receiver.fill('#offer-input', await sender.inputValue('#offer')); await receiver.fill('#offer-input', await sender.inputValue('#offer'));
await receiver.click('#create-answer'); await receiver.click('#create-answer');
await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 }); await expect(receiver.locator('#answer')).toHaveValue(/.+/, { timeout: 15_000 });
@@ -48,7 +54,9 @@ const MODES: Record<string, (sender: Page, receiver: Page) => Promise<void>> = {
}, },
async tracker(sender, receiver) { async tracker(sender, receiver) {
await sender.click('#share'); await sender.click('#share');
await expect(sender.locator('#send-code')).toHaveText(/^\d{8}$/); await expect(sender.locator('#send-code')).toHaveText(/^[0-9a-zA-Z]{8}$/);
await sender.click('#copy-send-code');
await expect(sender.locator('#copy-send-code')).toHaveText('Copied');
await expect(sender.locator('#log')).toContainText('waiting on'); await expect(sender.locator('#log')).toContainText('waiting on');
await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!); await receiver.fill('#receive-code', (await sender.locator('#send-code').textContent())!);
await receiver.click('#receive'); await receiver.click('#receive');
@@ -93,7 +101,7 @@ test.afterAll(async () => {
async function open(name: string, sockets: string[], init?: () => void) { async function open(name: string, sockets: string[], init?: () => void) {
const browser = await BROWSERS[name]!.launch(); const browser = await BROWSERS[name]!.launch();
browsers.push(browser); browsers.push(browser);
const page = await (await browser.newContext()).newPage(); const page = await (await browser.newContext({ permissions: PERMISSIONS[name] })).newPage();
page.on('websocket', (ws) => sockets.push(ws.url())); page.on('websocket', (ws) => sockets.push(ws.url()));
if (init) await page.addInitScript(init); if (init) await page.addInitScript(init);
await page.goto(url); await page.goto(url);
@@ -202,14 +210,14 @@ async function connect(mode: string, sender: Page, receiver: Page, source: strin
} }
} }
// Resolves with the download, which starts on its own as soon as the file is announced, and the // Resolves with the download, which starts once the receiver clicked Download, and the receiver log
// receiver log at that moment. // at that moment.
const downloadStarts = (receiver: Page) => const downloadStarts = (receiver: Page) =>
receiver receiver
.waitForEvent('download', { timeout: test.info().timeout }) .waitForEvent('download', { timeout: test.info().timeout })
.then(async (download) => ({ download, logAtStart: await log(receiver) })); .then(async (download) => ({ download, logAtStart: await log(receiver) }));
// Connects and confirms the security check on both sides. // Connects, confirms the security check on both sides and starts the download.
async function start(mode: string, sender: Page, receiver: Page, source: string) { async function start(mode: string, sender: Page, receiver: Page, source: string) {
await connect(mode, sender, receiver, source); await connect(mode, sender, receiver, source);
const started = downloadStarts(receiver); const started = downloadStarts(receiver);
@@ -217,6 +225,11 @@ async function start(mode: string, sender: Page, receiver: Page, source: string)
await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check"); await expect(sender.locator('#log')).toContainText("waiting for the receiver's security check");
await expect(receiver.locator('#log')).not.toContainText('receiving'); await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#confirm'); await receiver.click('#confirm');
// Offered, but nothing is sent before the user asks for it.
await expect(receiver.locator('#incoming')).toContainText(source.split('/').pop()!);
await expect(sender.locator('#log')).toContainText('waiting for the receiver to download');
await expect(receiver.locator('#log')).not.toContainText('receiving');
await receiver.click('#download');
return started; return started;
} }
@@ -239,6 +252,8 @@ async function transfer(
expect(await hash(await download.path())).toBe(await hash(source)); expect(await hash(await download.path())).toBe(await hash(source));
await expect(receiver.locator('#log')).toContainText('download complete'); await expect(receiver.locator('#log')).toContainText('download complete');
await expect(sender.locator('#log')).toContainText('delivered'); await expect(sender.locator('#log')).toContainText('delivered');
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100);
// Removed hidden pages release the service worker for updates. // Removed hidden pages release the service worker for updates.
await expect(receiver.locator('iframe')).toHaveCount(0); await expect(receiver.locator('iframe')).toHaveCount(0);
}); });
@@ -352,6 +367,20 @@ for (const name of Object.keys(BROWSERS)) {
}); });
}); });
test(`progress: ${name} follows the shared file, not a later pick`, async () => {
const [sender, receiver] = await Promise.all([open(name, []), open(name, [])]);
const source = test.info().outputPath('payload.bin');
await writeFile(source, randomBytes(SIZE));
await withLogs(sender!, receiver!, async () => {
await start('offline', sender!, receiver!, source);
await expect(sender!.locator('#log')).toContainText('delivered');
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(2 * SIZE) };
await sender!.setInputFiles('input[type=file]', other);
await expect(sender!.locator('#send-progress')).toHaveJSProperty('value', 100);
});
});
test(`check: ${name} accepts nothing before the receiver confirmed`, async () => { test(`check: ${name} accepts nothing before the receiver confirmed`, async () => {
const [sender, receiver] = await Promise.all([open(name, [], recordChannels), open(name, [])]); const [sender, receiver] = await Promise.all([open(name, [], recordChannels), open(name, [])]);
const source = test.info().outputPath('payload.bin'); const source = test.info().outputPath('payload.bin');
@@ -377,6 +406,7 @@ for (const name of Object.keys(BROWSERS)) {
const started = downloadStarts(receiver!); const started = downloadStarts(receiver!);
await receiver!.click('#confirm'); await receiver!.click('#confirm');
await receiver!.click('#download');
const { download } = await started; const { download } = await started;
expect(download.suggestedFilename()).toBe('payload.bin'); expect(download.suggestedFilename()).toBe('payload.bin');
expect(await hash(await download.path())).toBe(await hash(source)); expect(await hash(await download.path())).toBe(await hash(source));
@@ -406,6 +436,7 @@ for (const name of Object.keys(BROWSERS)) {
const started = downloadStarts(receiver!); const started = downloadStarts(receiver!);
await sender!.click('#confirm'); await sender!.click('#confirm');
await receiver!.click('#confirm'); await receiver!.click('#confirm');
await receiver!.click('#download');
const { download } = await started; const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source)); expect(await hash(await download.path())).toBe(await hash(source));
await expect(sender!.locator('#log')).toContainText('delivered'); await expect(sender!.locator('#log')).toContainText('delivered');
@@ -434,6 +465,7 @@ for (const name of Object.keys(BROWSERS)) {
const started = downloadStarts(receiver!); const started = downloadStarts(receiver!);
await sender!.click('#confirm'); await sender!.click('#confirm');
await receiver!.click('#confirm'); await receiver!.click('#confirm');
await receiver!.click('#download');
const { download } = await started; const { download } = await started;
expect(await hash(await download.path())).toBe(await hash(source)); expect(await hash(await download.path())).toBe(await hash(source));
await expect(sender!.locator('#log')).toContainText('delivered'); await expect(sender!.locator('#log')).toContainText('delivered');
@@ -491,6 +523,7 @@ for (const name of Object.keys(BROWSERS)) {
['sender', 'receiver'].map((profile) => ['sender', 'receiver'].map((profile) =>
BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), { BROWSERS[name]!.launchPersistentContext(test.info().outputPath(profile), {
downloadsPath: test.info().outputPath('downloads'), downloadsPath: test.info().outputPath('downloads'),
permissions: PERMISSIONS[name],
}), }),
), ),
); );
+99 -22
View File
@@ -10,6 +10,8 @@ import {
settings as coreSettings, settings as coreSettings,
type Check, type Check,
type Events, type Events,
type Incoming,
type ReceiveEvents,
} from './main'; } from './main';
const SETTINGS_KEY = 'hellcon:settings'; const SETTINGS_KEY = 'hellcon:settings';
@@ -87,7 +89,8 @@ const check = ref<Check>();
const confirmed = ref(false); const confirmed = ref(false);
const log = ref<string[]>([]); const log = ref<string[]>([]);
const events: Events = { // Shared by both sides, each adds its own progress.
const events: Omit<Events, 'progress'> = {
log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`), log: (message) => log.value.push(`${new Date().toISOString().slice(11, 23)} ${message}`),
check: (result) => { check: (result) => {
check.value = result; check.value = result;
@@ -95,11 +98,46 @@ const events: Events = {
}, },
}; };
// Of the file in transfer, which on the sender isn't necessarily the one picked now. Undefined until
// a transfer starts.
type Progress = { read: number; size: number };
const sent = ref<Progress>();
const sendEvents: Events = { ...events, progress: (read, size) => (sent.value = { read, size }) };
const incoming = ref<Incoming>();
const received = ref<Progress>();
const receiveEvents: ReceiveEvents = {
...events,
progress: (read, size) => (received.value = { read, size }),
incoming: (file) => {
incoming.value = file;
received.value = undefined;
},
};
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
function onConfirm() { function onConfirm() {
confirmed.value = true; confirmed.value = true;
check.value?.confirm(); check.value?.confirm();
} }
// The text copied last, its button says so for a moment.
const copied = ref('');
let copiedTimer: number | undefined;
async function onCopy(text: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
return events.log('copy failed, the browser blocked the clipboard');
}
copied.value = text;
clearTimeout(copiedTimer);
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
}
let acceptAnswer:((answer: string) => Promise<void>) | undefined; let acceptAnswer:((answer: string) => Promise<void>) | undefined;
function onPick(event: Event) { function onPick(event: Event) {
@@ -124,7 +162,8 @@ function formatSize(bytes: number) {
} }
async function onCreateOffer() { async function onCreateOffer() {
const result = await createOffer(file.value!, events); sent.value = undefined;
const result = await createOffer(file.value!, sendEvents);
offer.value = result.offer; offer.value = result.offer;
acceptAnswer = result.accept; acceptAnswer = result.accept;
} }
@@ -134,15 +173,16 @@ function onAcceptAnswer() {
} }
async function onCreateAnswer() { async function onCreateAnswer() {
answer.value = await answerOffer(offerInput.value, events); answer.value = await answerOffer(offerInput.value, receiveEvents);
} }
async function onShare() { async function onShare() {
sendCode.value = await sendViaTracker(file.value!, events); sent.value = undefined;
sendCode.value = await sendViaTracker(file.value!, sendEvents);
} }
function onReceive() { function onReceive() {
receiveViaTracker(receiveCode.value, events); receiveViaTracker(receiveCode.value, receiveEvents);
} }
</script> </script>
@@ -189,46 +229,83 @@ function onReceive() {
</template> </template>
<template v-else>Drop a file or click to choose</template> <template v-else>Drop a file or click to choose</template>
</label> </label>
<p v-if="sent">
<progress id="send-progress" max="100" :value="percent(sent)"></progress>
{{ percent(sent) }} %
</p>
<section> <section>
<h3>Manual</h3> <h3>Tracker</h3>
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
<template v-if="sendCode">
<label for="send-code">Code, give this to the receiver:</label>
<div role="group">
<output id="send-code">{{ sendCode }}</output>
<button id="copy-send-code" @click="onCopy(sendCode)">{{ copied === sendCode ? 'Copied' : 'Copy' }}</button>
</div>
</template>
</section>
<details id="send-manual">
<summary>Manual</summary>
<section>
<button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button> <button id="create-offer" :disabled="!file" @click="onCreateOffer">Create offer</button>
<template v-if="offer"> <template v-if="offer">
<label for="offer">Offer, send this to the receiver:</label> <label for="offer">Offer, send this to the receiver:</label>
<textarea id="offer" readonly :value="offer"></textarea> <textarea id="offer" readonly :value="offer"></textarea>
<button id="copy-offer" data-copy @click="onCopy(offer)">{{ copied === offer ? 'Copied' : 'Copy' }}</button>
<label for="answer-input">Answer from the receiver:</label> <label for="answer-input">Answer from the receiver:</label>
<textarea id="answer-input" v-model="answerInput"></textarea> <textarea id="answer-input" v-model="answerInput"></textarea>
<button id="accept-answer" @click="onAcceptAnswer">Connect</button> <button id="accept-answer" @click="onAcceptAnswer">Connect</button>
</template> </template>
</section> </section>
</details>
<section>
<h3>Tracker</h3>
<button id="share" :disabled="!file || !settings.trackers.length" @click="onShare">Share via tracker</button>
<p v-if="sendCode">Code: <output id="send-code">{{ sendCode }}</output></p>
</section>
</article> </article>
<article> <article>
<h2>Receive</h2> <h2>Receive</h2>
<div id="incoming">
<template v-if="incoming">
<strong>{{ incoming.name }}</strong>
{{ formatSize(incoming.size) }}
<button v-if="!received" id="download" @click="incoming.download()">Download</button>
</template>
<template v-else>The sender's file shows up here after the security check</template>
</div>
<p v-if="received">
<progress id="receive-progress" max="100" :value="percent(received)"></progress>
{{ percent(received) }} %
</p>
<section> <section>
<h3>Manual</h3> <h3>Tracker</h3>
<textarea id="offer-input" v-model="offerInput" placeholder="Paste the offer"></textarea> <label for="receive-code">Code from the sender:</label>
<div role="group">
<input
id="receive-code"
v-model="receiveCode"
autocapitalize="off"
autocomplete="off"
autocorrect="off"
spellcheck="false"
/>
<button id="receive" :disabled="!settings.trackers.length" @click="onReceive">Receive</button>
</div>
</section>
<details id="receive-manual">
<summary>Manual</summary>
<section>
<label for="offer-input">Offer from the sender:</label>
<textarea id="offer-input" v-model="offerInput"></textarea>
<button id="create-answer" @click="onCreateAnswer">Create answer</button> <button id="create-answer" @click="onCreateAnswer">Create answer</button>
<template v-if="answer"> <template v-if="answer">
<label for="answer">Answer, send this back to the sender:</label> <label for="answer">Answer, send this back to the sender:</label>
<textarea id="answer" readonly :value="answer"></textarea> <textarea id="answer" readonly :value="answer"></textarea>
<button id="copy-answer" data-copy @click="onCopy(answer)">{{ copied === answer ? 'Copied' : 'Copy' }}</button>
</template> </template>
</section> </section>
</details>
<section>
<h3>Tracker</h3>
<div role="group">
<input id="receive-code" v-model="receiveCode" placeholder="Code" />
<button id="receive" :disabled="!settings.trackers.length" @click="onReceive">Receive</button>
</div>
</section>
</article> </article>
<details id="servers"> <details id="servers">
+75 -22
View File
@@ -42,6 +42,17 @@ export type Events = {
log: (message: string) => void; log: (message: string) => void;
// Called on both sides once connected, and without a check when it ended undecided. // Called on both sides once connected, and without a check when it ended undecided.
check: (check?: Check) => void; check: (check?: Check) => void;
// Bytes of the transferred file the receiver's download manager has read, on both sides. 0 when
// the transfer starts.
progress: (read: number, size: number) => void;
};
// The sender's file, offered once both sides confirmed the check. download() starts saving it.
export type Incoming = { name: string; size: number; download: () => void };
export type ReceiveEvents = Events & {
// Without a file when the sender left before the download started.
incoming: (file?: Incoming) => void;
}; };
function createPeerConnection() { function createPeerConnection() {
@@ -54,8 +65,15 @@ function randomBinary(length: number) {
return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length))); return String.fromCharCode(...crypto.getRandomValues(new Uint8Array(length)));
} }
const CODE_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// 8 of 62 characters. Bytes from 248 on are dropped, so every character is equally likely.
function randomCode() { function randomCode() {
return String(crypto.getRandomValues(new Uint32Array(1))[0]! % 100_000_000).padStart(8, '0'); let code = '';
while (code.length < 8)
for (const byte of crypto.getRandomValues(new Uint8Array(8)))
if (byte < 248 && code.length < 8) code += CODE_CHARS[byte % 62];
return code;
} }
// The tracker swarm is identified by a 20 byte info_hash, derived from the shared code. // The tracker swarm is identified by a 20 byte info_hash, derived from the shared code.
@@ -144,9 +162,10 @@ function connected(
}; };
} }
// Sends once checked resolved and the receiver confirmed its own check with { ok }. Then it answers // Offers the file once checked resolved and the receiver confirmed its own check with { ok }, sends
// with { read } progress, { done } once the download manager read the last byte, or { error } when // it once the receiver started the download with { start }. Then it answers with { read } progress,
// its download was cancelled or failed. // { done } once the download manager read the last byte, or { error } when its download was
// cancelled or failed.
async function sendFile( async function sendFile(
pc: RTCPeerConnection, pc: RTCPeerConnection,
channel: RTCDataChannel, channel: RTCDataChannel,
@@ -159,6 +178,7 @@ async function sendFile(
} }
let read = 0; let read = 0;
let accepted = false; let accepted = false;
let started = false;
let sending = false; let sending = false;
let stopped = false; let stopped = false;
// Every event the send loop can wait for calls this. // Every event the send loop can wait for calls this.
@@ -172,11 +192,16 @@ async function sendFile(
channel.onmessage = ({ data }) => { channel.onmessage = ({ data }) => {
const message = JSON.parse(data); const message = JSON.parse(data);
if (message.ok) accepted = true; if (message.ok) accepted = true;
else if (message.start) started = true;
// Before that, nothing else can come from a receiver that passed its check. // Before that, nothing else can come from a receiver that passed its check.
else if (!sending) return; else if (!sending) return;
if (message.read) read = message.read; if (message.read) {
read = message.read;
events.progress(read, file.size);
}
if (message.done) { if (message.done) {
events.log('delivered'); events.log('delivered');
events.progress(file.size, file.size);
// Finished, a later close is no loss. // Finished, a later close is no loss.
stopped = true; stopped = true;
} }
@@ -195,11 +220,17 @@ async function sendFile(
while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve)); while (!stopped && !accepted) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return; if (stopped) return;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
events.log(`offered ${file.name} (${file.size} bytes)`);
if (!started) events.log('waiting for the receiver to download');
while (!stopped && !started) await new Promise<void>((resolve) => (wake = resolve));
if (stopped) return;
sending = true; sending = true;
handshake.start(); handshake.start();
events.log(`sending ${file.name} (${file.size} bytes)`); events.log(`sending ${file.name}`);
events.progress(0, file.size);
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2; channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
channel.send(JSON.stringify({ name: file.name, size: file.size }));
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) { for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) { while (!stopped && (offset - read >= WINDOW || channel.bufferedAmount > MAX_BUFFERED)) {
await new Promise<void>((resolve) => (wake = resolve)); await new Promise<void>((resolve) => (wake = resolve));
@@ -253,13 +284,15 @@ async function holdWorker() {
return { frame, worker }; return { frame, worker };
} }
// Accepts nothing until checked resolved, then tells the sender with { ok }. // Accepts nothing until checked resolved, then tells the sender with { ok }. Its file is offered to
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Events, handshake: Handshake) { // the user, chunks are accepted only once they started the download.
function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: ReceiveEvents, handshake: Handshake) {
const id = crypto.randomUUID(); const id = crypto.randomUUID();
const frames: HTMLIFrameElement[] = []; const frames: HTMLIFrameElement[] = [];
let meta: { name: string; size: number } | undefined; let meta: { name: string; size: number } | undefined;
let received = 0; let received = 0;
let confirmed = false; let confirmed = false;
let downloading = false;
let ended = false; let ended = false;
// Chunks can arrive before the worker is held, chaining every post on this keeps them in order. // Chunks can arrive before the worker is held, chaining every post on this keeps them in order.
let worker: Promise<ServiceWorker | void> = Promise.resolve(); let worker: Promise<ServiceWorker | void> = Promise.resolve();
@@ -298,7 +331,10 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
}); });
const { port1, port2 } = new MessageChannel(); const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) => { port1.onmessage = ({ data }) => {
if (typeof data === 'number') return reply({ read: data }); if (typeof data === 'number') {
events.progress(data, meta!.size);
return reply({ read: data });
}
if (data === 'ready' && !ended) { if (data === 'ready' && !ended) {
// A navigation, not fetch(): only navigations hand the response to the download manager. // A navigation, not fetch(): only navigations hand the response to the download manager.
const download = document.createElement('iframe'); const download = document.createElement('iframe');
@@ -310,6 +346,7 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
} }
if (data === 'finished') { if (data === 'finished') {
events.log('download complete'); events.log('download complete');
events.progress(meta!.size, meta!.size);
reply({ done: true }); reply({ done: true });
} }
if (data === 'cancelled' && !ended) { if (data === 'cancelled' && !ended) {
@@ -330,27 +367,43 @@ function receiveFile(pc: RTCPeerConnection, channel: RTCDataChannel, events: Eve
events.log('waiting for the sender'); events.log('waiting for the sender');
}); });
function complete() {
post({ done: true });
events.log('received');
}
function download() {
if (downloading || ended) return;
downloading = true;
handshake.start();
events.log(`receiving ${meta!.name}`);
events.progress(0, meta!.size);
startDownload();
reply({ start: true });
if (!meta!.size) complete();
}
channel.binaryType = 'arraybuffer'; channel.binaryType = 'arraybuffer';
channel.onmessage = ({ data }) => { channel.onmessage = ({ data }) => {
if (ended || !confirmed) return; if (ended || !confirmed) return;
if (typeof data === 'string') { if (typeof data === 'string') {
if (meta) return;
meta = JSON.parse(data); meta = JSON.parse(data);
handshake.start(); events.log(`offered ${meta!.name} (${meta!.size} bytes)`);
events.log(`receiving ${meta!.name} (${meta!.size} bytes)`); events.incoming({ ...meta!, download });
startDownload(); } else if (downloading) {
} else {
received += data.byteLength; received += data.byteLength;
post({ chunk: data }, [data]); post({ chunk: data }, [data]);
} if (received === meta!.size) complete();
if (meta && received === meta.size) {
post({ done: true });
events.log('received');
} }
}; };
// Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished // Fails the download instead of leaving it stalled (Firefox still does, see TODO.md). A vanished
// peer only closes the channel in Firefox, Chromium just fails the connection. // peer only closes the channel in Firefox, Chromium just fails the connection. Before the download
// started, connected reports it and only the offer goes.
function lost() { function lost() {
if (meta && received < meta.size) fail('connection lost'); if (!meta) return;
if (!downloading) events.incoming();
else if (received < meta.size) fail('connection lost');
} }
channel.addEventListener('close', lost); channel.addEventListener('close', lost);
pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost()); pc.addEventListener('connectionstatechange', () => pc.connectionState === 'failed' && lost());
@@ -371,7 +424,7 @@ export async function createOffer(file: File, events: Events) {
}; };
} }
export async function answerOffer(offer: string, events: Events) { export async function answerOffer(offer: string, events: ReceiveEvents) {
await downloadsReady(events); await downloadsReady(events);
const pc = createPeerConnection(); const pc = createPeerConnection();
pc.ondatachannel = ({ channel }) => pc.ondatachannel = ({ channel }) =>
@@ -447,7 +500,7 @@ export async function sendViaTracker(file: File, events: Events) {
// Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails // Receiver keeps one offer up per tracker; the first data channel that opens wins. If its check fails
// or the sender leaves before, the used up offers are replaced. The others stay, a sender may have // or the sender leaves before, the used up offers are replaced. The others stay, a sender may have
// queued one of them. // queued one of them.
export async function receiveViaTracker(code: string, events: Events) { export async function receiveViaTracker(code: string, events: ReceiveEvents) {
await downloadsReady(events); await downloadsReady(events);
const hash = await infoHash(code); const hash = await infoHash(code);
const peerId = randomBinary(20); const peerId = randomBinary(20);
+102 -16
View File
@@ -144,7 +144,7 @@ section {
border-top: 1px solid var(--color-border); border-top: 1px solid var(--color-border);
} }
h3 { h3, article summary {
font-size: var(--text-sm); font-size: var(--text-sm);
font-weight: 600; font-weight: 600;
text-transform: uppercase; text-transform: uppercase;
@@ -152,12 +152,6 @@ h3 {
color: var(--color-text-muted); color: var(--color-text-muted);
} }
small {
font-weight: normal;
text-transform: none;
letter-spacing: normal;
}
label, section p { label, section p {
font-size: var(--text-sm); font-size: var(--text-sm);
color: var(--color-text-muted); color: var(--color-text-muted);
@@ -223,22 +217,63 @@ button:disabled {
[role='group'] { [role='group'] {
display: flex; display: flex;
gap: var(--space-2);
width: 100%; width: 100%;
} }
[role='group'] > input { /* The tracker code on both sides. The sender's is read only like an input, one click selects it. */
border-start-end-radius: 0; #send-code, #receive-code {
border-end-end-radius: 0; color: var(--color-secondary);
font-family: ui-monospace, monospace;
font-size: var(--text-lg);
font-weight: 600;
letter-spacing: 0.15em;
} }
[role='group'] > button { #send-code {
border-start-start-radius: 0; flex: 1;
border-end-start-radius: 0; padding: var(--space-2) var(--space-3);
background: var(--color-input);
border: 1px solid var(--color-border);
border-radius: var(--radius);
user-select: all;
} }
/* Drop zone, the invisible file input covers the whole label */ /* Copy buttons, secondary next to the value they copy */
label:has(> [type='file']) { [data-copy] {
padding: var(--space-1) var(--space-3);
background: transparent;
border-color: var(--color-border);
font-size: var(--text-sm);
}
[data-copy]:hover:not(:disabled) {
background: var(--color-border);
}
/* Manual signaling, folded away below the tracker in each card */
article details {
background: none;
border: none;
border-top: 1px solid var(--color-border);
border-radius: 0;
box-shadow: none;
}
article summary {
padding: var(--space-4) 0 0;
}
article details section {
padding-top: var(--space-2);
border-top: none;
}
/* Drop zone, the invisible file input covers the whole label. The incoming file looks alike. */
label:has(> [type='file']), #incoming {
position: relative; position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -265,6 +300,16 @@ label:has(> [type='file']:focus-visible) {
outline-offset: 2px; outline-offset: 2px;
} }
#incoming {
border-style: solid;
font-size: var(--text-sm);
color: var(--color-text-muted);
}
#incoming button {
margin-top: var(--space-2);
}
[type='file'] { [type='file'] {
position: absolute; position: absolute;
inset: 0; inset: 0;
@@ -272,11 +317,52 @@ label:has(> [type='file']:focus-visible) {
cursor: pointer; cursor: pointer;
} }
label strong { label strong, #incoming strong {
color: var(--color-text); color: var(--color-text);
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
/* Progress, below the file on both sides */
p:has(> progress) {
display: flex;
align-items: center;
gap: var(--space-3);
font-size: var(--text-sm);
font-variant-numeric: tabular-nums;
color: var(--color-text-muted);
}
progress {
flex: 1;
height: 0.5rem;
appearance: none;
border: none;
border-radius: 999px;
background: var(--color-input);
overflow: hidden;
}
progress::-webkit-progress-bar {
background: var(--color-input);
}
progress::-webkit-progress-value {
background: var(--color-primary);
}
progress::-moz-progress-bar {
background: var(--color-primary);
}
progress[value='100']::-webkit-progress-value {
background: var(--color-success);
}
progress[value='100']::-moz-progress-bar {
background: var(--color-success);
}
/* Switch, like Pico's role="switch" */ /* Switch, like Pico's role="switch" */
label:has([role='switch']) { label:has([role='switch']) {