Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d92c4b50cf | ||
|
|
f7e8999439 |
No files matched your search
+57
@@ -324,6 +324,8 @@ async function connect(mode: string, sender: Page, receiver: Page, source: strin
|
||||
for (const page of [sender, receiver]) {
|
||||
await expect(page.locator('#log')).toContainText('waiting for the security check');
|
||||
}
|
||||
await expect(sender.locator('#send-status')).toHaveText('Compare the security codes above with the receiver');
|
||||
await expect(receiver.locator('#receive-status')).toHaveText('Compare the security codes above with the sender');
|
||||
}
|
||||
|
||||
// Resolves with the download, which starts once the receiver clicked Download, and the receiver log
|
||||
@@ -355,6 +357,8 @@ async function start(mode: string, sender: Page, receiver: Page, source: string)
|
||||
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 expect(sender.locator('[data-phase=wait] #send-status')).toHaveText('Waiting for the receiver to download');
|
||||
await expect(receiver.locator('[data-phase=wait] #receive-status')).toHaveText('Click Download to save the file');
|
||||
await receiver.click('#download');
|
||||
return started;
|
||||
}
|
||||
@@ -385,6 +389,8 @@ async function transfer(
|
||||
}
|
||||
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||
await expect(receiver.locator('#receive-progress')).toHaveJSProperty('value', 100);
|
||||
await expect(sender.locator('[data-phase=done] #send-status')).toHaveText('Delivered');
|
||||
await expect(receiver.locator('[data-phase=done] #receive-status')).toHaveText('Download complete');
|
||||
// Removed hidden pages release the service worker for updates.
|
||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||
await expectClosed(sender);
|
||||
@@ -633,6 +639,7 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
// A transfer that already finished would report no failure.
|
||||
expect(await download.failure()).toBe('canceled');
|
||||
await expect(receiver.locator('#log')).toContainText('download cancelled');
|
||||
await expect(receiver.locator('[data-phase=stopped] #receive-status')).toHaveText('Download cancelled');
|
||||
await expect(receiver.locator('iframe')).toHaveCount(0);
|
||||
expect(await log(receiver)).not.toContain('download complete');
|
||||
// The window keeps the sender from having sent everything before it hears about the cancel.
|
||||
@@ -665,9 +672,13 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await withLogs(sender, receiver, async () => {
|
||||
await start('offline', sender, receiver, source);
|
||||
await expect(sender.locator('#log')).toContainText('delivered');
|
||||
await expect(sender.locator('#send-file')).toHaveCount(0);
|
||||
const other = { name: 'other.bin', mimeType: 'application/octet-stream', buffer: Buffer.alloc(200_000) };
|
||||
await sender.setInputFiles('input[type=file]', other);
|
||||
await expect(sender.locator('#send-progress')).toHaveJSProperty('value', 100);
|
||||
// The status names the file it belongs to, not the one picked now.
|
||||
await expect(sender.locator('#send-file')).toHaveText('payload.bin');
|
||||
await expect(sender.locator('#send-status')).toHaveText('Delivered');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -713,6 +724,31 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
});
|
||||
});
|
||||
|
||||
test(`copy: ${name} selects the text when the browser blocks the clipboard`, async () => {
|
||||
const sender = await open(name, {
|
||||
init: () => {
|
||||
navigator.clipboard.writeText = () => Promise.reject(new DOMException('blocked', 'NotAllowedError'));
|
||||
},
|
||||
});
|
||||
|
||||
await withLogs(sender, sender, async () => {
|
||||
await sender.uncheck('#stun');
|
||||
await sender.setInputFiles('input[type=file]', await payload(randomBytes(1000)));
|
||||
await sender.click('#send-manual summary');
|
||||
await sender.click('#create-offer');
|
||||
await expect(sender.locator('#offer')).toHaveValue(/.+/);
|
||||
await sender.click('#copy-offer');
|
||||
await expect(sender.locator('#copy-offer')).toHaveText('Copy failed');
|
||||
await expect(sender.locator('#send-manual [role=alert]')).toHaveText(
|
||||
'The browser blocked copying. The offer is selected, copy it yourself.',
|
||||
);
|
||||
const offer = sender.locator('#offer');
|
||||
expect(await offer.evaluate((area: HTMLTextAreaElement) => area.selectionEnd - area.selectionStart)).toBe(
|
||||
(await offer.inputValue()).length,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Share, Receive and the manual exchange each start a session, a new one ends the one before.
|
||||
test(`session: ${name} a new operation ends the previous one`, async () => {
|
||||
const [sender, receiver] = await Promise.all([open(name), open(name)]);
|
||||
@@ -729,6 +765,11 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await receiver.fill('#receive-code', 'nobody');
|
||||
await receiver.click('#receive');
|
||||
await expect.poll(() => sockets.get(receiver)!.length).toBeGreaterThan(0);
|
||||
// The log tells the sessions apart.
|
||||
await expect(sender.locator('#log')).toContainText(
|
||||
/--- share payload\.bin via tracker ---[\s\S]*--- share payload/,
|
||||
);
|
||||
await expect(receiver.locator('#log')).toContainText('--- receive via tracker ---');
|
||||
|
||||
// Closes all of the above, transfer checks that.
|
||||
await transfer('offline', sender, receiver, source, 100_000);
|
||||
@@ -1062,6 +1103,15 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect(receiver.locator('#log')).toContainText(`looking on ${urls[2]}`);
|
||||
expect([trackers.sockets.length, trackers.open]).toEqual([3, 3]);
|
||||
await expect(receiver.locator('#receive-error')).toHaveCount(0);
|
||||
// None has it any more, the search goes on but says so.
|
||||
await expect(receiver.locator('[data-phase=retry] #receive-status')).toHaveText(
|
||||
'No sender with this code on any tracker. Check the code, still looking',
|
||||
);
|
||||
// A sender showed up, busy with another receiver maybe: the code was right.
|
||||
trackers.sockets[2]!.send(JSON.stringify({ action: 'announce', interval: 120, complete: 1 }));
|
||||
await expect(receiver.locator('[data-phase=wait] #receive-status')).toHaveText(
|
||||
'Found the share on three.test, waiting for the sender to answer',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1263,6 +1313,13 @@ for (const name of Object.keys(BROWSERS)) {
|
||||
await expect(receiver.locator('#log')).toContainText(
|
||||
`sender via ${tracker} did not connect: this side ${NO_PUBLIC}`,
|
||||
);
|
||||
// Both keep trying, and say why the last attempt failed.
|
||||
await expect(sender.locator('[data-phase=retry] #send-status')).toContainText(
|
||||
`could not connect to the receiver: the receiver ${NO_PUBLIC}`,
|
||||
);
|
||||
await expect(receiver.locator('[data-phase=retry] #receive-status')).toContainText(
|
||||
`could not connect to the sender: this side ${NO_PUBLIC}`,
|
||||
);
|
||||
// Then once more for the turn a new offer may have taken meanwhile.
|
||||
await fastForward('06:00');
|
||||
await fastForward(CONNECT_TIMEOUT);
|
||||
|
||||
+83
-26
@@ -9,6 +9,7 @@ import {
|
||||
DEFAULT_TRACKERS,
|
||||
type Events,
|
||||
type Incoming,
|
||||
type Phase,
|
||||
type ReceiveEvents,
|
||||
receiveViaTracker,
|
||||
sendViaTracker,
|
||||
@@ -83,6 +84,8 @@ function onResetServers() {
|
||||
}
|
||||
|
||||
const file = ref<File>();
|
||||
// The file of the send session, the user may have picked another one since.
|
||||
const shared = ref<File>();
|
||||
const offer = ref('');
|
||||
const answerInput = ref('');
|
||||
const sendCode = ref('');
|
||||
@@ -100,6 +103,9 @@ const confirmed = ref(false);
|
||||
const log = ref<string[]>([]);
|
||||
// Of the session, shown in the card of its side.
|
||||
const error = ref('');
|
||||
const status = ref<{ phase: Phase; text: string }>();
|
||||
// The bar's look, an error colors whatever it showed.
|
||||
const phase = computed(() => (error.value ? 'error' : status.value?.phase));
|
||||
|
||||
// Shared by both sides, each adds its own progress.
|
||||
const events: Omit<Events, 'progress'> = {
|
||||
@@ -108,6 +114,7 @@ const events: Omit<Events, 'progress'> = {
|
||||
events.log(message);
|
||||
error.value = message;
|
||||
},
|
||||
status: (phase, text) => (status.value = { phase, text }),
|
||||
check: (result) => {
|
||||
check.value = result;
|
||||
confirmed.value = false;
|
||||
@@ -134,24 +141,43 @@ const receiveEvents: ReceiveEvents = {
|
||||
|
||||
const percent = ({ read, size }: Progress) => (size ? Math.floor((read / size) * 100) : 100);
|
||||
|
||||
// Undefined makes the bar indeterminate: until the transfer starts it only shows how the session is
|
||||
// doing. After it, or an error before it, the bar is full.
|
||||
function barValue(progress?: Progress) {
|
||||
if (progress) return percent(progress);
|
||||
return ['start', 'wait', 'retry'].includes(phase.value!) ? undefined : 100;
|
||||
}
|
||||
|
||||
function onConfirm() {
|
||||
confirmed.value = true;
|
||||
check.value?.confirm();
|
||||
}
|
||||
|
||||
// The text copied last, its button says so for a moment.
|
||||
const copied = ref('');
|
||||
// The text copied last and whether that worked. Its button says so, after a success for a moment.
|
||||
const copied = ref<{ text: string; ok: boolean }>();
|
||||
let copiedTimer: number | undefined;
|
||||
|
||||
async function onCopy(text: string) {
|
||||
const copyLabel = (text: string) => (copied.value?.text !== text ? 'Copy' : copied.value.ok ? 'Copied' : 'Copy failed');
|
||||
const copyFailed = (text: string) => copied.value?.text === text && !copied.value.ok;
|
||||
|
||||
// Copies text, shown in the element with id. If the browser blocks that, the text gets selected, so
|
||||
// the user can copy it themselves.
|
||||
async function onCopy(text: string, id: string) {
|
||||
clearTimeout(copiedTimer);
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
return events.log('copy failed, the browser blocked the clipboard');
|
||||
events.log('copy failed, the browser blocked the clipboard');
|
||||
copied.value = { text, ok: false };
|
||||
const element = document.getElementById(id);
|
||||
if (element instanceof HTMLTextAreaElement) {
|
||||
element.focus();
|
||||
element.select();
|
||||
} else if (element) getSelection()?.selectAllChildren(element);
|
||||
return;
|
||||
}
|
||||
copied.value = text;
|
||||
clearTimeout(copiedTimer);
|
||||
copiedTimer = window.setTimeout(() => (copied.value = ''), 2000);
|
||||
copied.value = { text, ok: true };
|
||||
copiedTimer = window.setTimeout(() => (copied.value = undefined), 2000);
|
||||
}
|
||||
|
||||
let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||
@@ -161,11 +187,14 @@ let acceptAnswer: ((answer: string) => Promise<void>) | undefined;
|
||||
let session: AbortController | undefined;
|
||||
const side = ref<'send' | 'receive'>();
|
||||
|
||||
function begin(on: 'send' | 'receive') {
|
||||
// what goes into the log, so the sessions in it can be told apart.
|
||||
function begin(on: 'send' | 'receive', what: string) {
|
||||
session?.abort();
|
||||
session = new AbortController();
|
||||
side.value = on;
|
||||
events.log(`--- ${what} ---`);
|
||||
error.value = '';
|
||||
status.value = undefined;
|
||||
check.value = undefined;
|
||||
confirmed.value = false;
|
||||
sent.value = undefined;
|
||||
@@ -213,7 +242,8 @@ function formatSize(bytes: number) {
|
||||
}
|
||||
|
||||
async function onCreateOffer() {
|
||||
const signal = begin('send');
|
||||
const signal = begin('send', `manual offer for ${file.value!.name}`);
|
||||
shared.value = file.value;
|
||||
const result = await attempt(signal, createOffer(file.value!, sendEvents, signal));
|
||||
if (!result) return;
|
||||
offer.value = result.offer;
|
||||
@@ -227,13 +257,14 @@ function onAcceptAnswer() {
|
||||
}
|
||||
|
||||
async function onCreateAnswer() {
|
||||
const signal = begin('receive');
|
||||
const signal = begin('receive', 'manual answer');
|
||||
const result = await attempt(signal, answerOffer(offerInput.value, receiveEvents, signal));
|
||||
if (result) answer.value = result;
|
||||
}
|
||||
|
||||
async function onShare() {
|
||||
const signal = begin('send');
|
||||
const signal = begin('send', `share ${file.value!.name} via tracker`);
|
||||
shared.value = file.value;
|
||||
const code = await attempt(signal, sendViaTracker(file.value!, sendEvents, signal));
|
||||
if (!code) return;
|
||||
sendCode.value = code;
|
||||
@@ -246,7 +277,7 @@ async function onShare() {
|
||||
const codeGone = computed(() => sendExpired.value || !!sent.value || !!error.value);
|
||||
|
||||
function onReceive() {
|
||||
const signal = begin('receive');
|
||||
const signal = begin('receive', 'receive via tracker');
|
||||
attempt(signal, receiveViaTracker(receiveCode.value, receiveEvents, signal));
|
||||
}
|
||||
</script>
|
||||
@@ -301,11 +332,17 @@ function onReceive() {
|
||||
</template>
|
||||
<template v-else>Drop a file or click to choose</template>
|
||||
</label>
|
||||
<p v-if="sent">
|
||||
<progress id="send-progress" max="100" :value="percent(sent)" aria-label="Sent"></progress>
|
||||
{{ percent(sent) }} %
|
||||
<div v-if="side === 'send' && phase" :data-phase="phase">
|
||||
<p v-if="shared !== file" id="send-file">{{ shared!.name }}</p>
|
||||
<div>
|
||||
<progress id="send-progress" max="100" :value="barValue(sent)" aria-label="Sent"></progress>
|
||||
</div>
|
||||
<p v-if="error" id="send-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="send-status">{{ status!.text }}</span>
|
||||
<span v-if="sent">{{ percent(sent) }} %</span>
|
||||
</p>
|
||||
<p v-if="error && side === 'send'" id="send-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
@@ -317,10 +354,19 @@ function onReceive() {
|
||||
<label v-else for="send-code">Code, give this to the receiver, valid until {{ sendUntil }}:</label>
|
||||
<div role="group">
|
||||
<output id="send-code" :data-expired="codeGone || undefined">{{ sendCode }}</output>
|
||||
<button id="copy-send-code" type="button" data-copy :disabled="codeGone" @click="onCopy(sendCode)">
|
||||
{{ copied === sendCode ? 'Copied' : 'Copy' }}
|
||||
<button
|
||||
id="copy-send-code"
|
||||
type="button"
|
||||
data-copy
|
||||
:disabled="codeGone"
|
||||
@click="onCopy(sendCode, 'send-code')"
|
||||
>
|
||||
{{ copyLabel(sendCode) }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="copyFailed(sendCode)" role="alert">
|
||||
The browser blocked copying. The code is selected, copy it yourself.
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
@@ -331,9 +377,12 @@ function onReceive() {
|
||||
<template v-if="offer">
|
||||
<label for="offer">Offer, send this to the receiver:</label>
|
||||
<textarea id="offer" readonly :value="offer"></textarea>
|
||||
<button id="copy-offer" type="button" data-copy @click="onCopy(offer)">
|
||||
{{ copied === offer ? 'Copied' : 'Copy' }}
|
||||
<button id="copy-offer" type="button" data-copy @click="onCopy(offer, 'offer')">
|
||||
{{ copyLabel(offer) }}
|
||||
</button>
|
||||
<p v-if="copyFailed(offer)" role="alert">
|
||||
The browser blocked copying. The offer is selected, copy it yourself.
|
||||
</p>
|
||||
<label for="answer-input">Answer from the receiver:</label>
|
||||
<textarea id="answer-input" v-model="answerInput"></textarea>
|
||||
<button id="accept-answer" type="button" :disabled="!answerInput.trim()" @click="onAcceptAnswer">
|
||||
@@ -354,11 +403,16 @@ function onReceive() {
|
||||
</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)" aria-label="Received"></progress>
|
||||
{{ percent(received) }} %
|
||||
<div v-if="side === 'receive' && phase" :data-phase="phase">
|
||||
<div>
|
||||
<progress id="receive-progress" max="100" :value="barValue(received)" aria-label="Received"></progress>
|
||||
</div>
|
||||
<p v-if="error" id="receive-error" role="alert">{{ error }}</p>
|
||||
<p v-else role="status">
|
||||
<span id="receive-status">{{ status!.text }}</span>
|
||||
<span v-if="received">{{ percent(received) }} %</span>
|
||||
</p>
|
||||
<p v-if="error && side === 'receive'" id="receive-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h3>Tracker</h3>
|
||||
@@ -394,9 +448,12 @@ function onReceive() {
|
||||
<template v-if="answer">
|
||||
<label for="answer">Answer, send this back to the sender:</label>
|
||||
<textarea id="answer" readonly :value="answer"></textarea>
|
||||
<button id="copy-answer" type="button" data-copy @click="onCopy(answer)">
|
||||
{{ copied === answer ? 'Copied' : 'Copy' }}
|
||||
<button id="copy-answer" type="button" data-copy @click="onCopy(answer, 'answer')">
|
||||
{{ copyLabel(answer) }}
|
||||
</button>
|
||||
<p v-if="copyFailed(answer)" role="alert">
|
||||
The browser blocked copying. The answer is selected, copy it yourself.
|
||||
</p>
|
||||
</template>
|
||||
</section>
|
||||
</details>
|
||||
|
||||
+113
-21
@@ -63,8 +63,15 @@ export type Check = {
|
||||
reject: () => void;
|
||||
};
|
||||
|
||||
// What a session is doing, see Events.status.
|
||||
export type Phase = 'start' | 'wait' | 'retry' | 'transfer' | 'done' | 'stopped';
|
||||
|
||||
export type Events = {
|
||||
log: (message: string) => void;
|
||||
// What the session is doing, a sentence for the user. start: it sets something up or connects,
|
||||
// wait: someone has to act, retry: an attempt failed and it tries again, the text says why. Then
|
||||
// transfer, and once it's over done or stopped. An error replaces it.
|
||||
status: (phase: Phase, text: string) => void;
|
||||
// Something the user has to act on, the session can't go on by itself. Not logged separately.
|
||||
error: (message: string) => void;
|
||||
// Called on both sides once connected by the manual exchange, and without a check when it ended
|
||||
@@ -366,6 +373,12 @@ function stunHint(pc: RTCPeerConnection, peer: string) {
|
||||
return `${missing}, between different networks both sides need STUN`;
|
||||
}
|
||||
|
||||
// Why a tracker peer didn't connect when stunHint has no explanation: both sides offered a public
|
||||
// address, so something in between doesn't let them reach each other. A guess, but the usual one.
|
||||
const BLOCKED = 'a network in between, e.g. a VPN or firewall, may block direct connections';
|
||||
|
||||
const host = (url: string) => URL.parse(url)?.host || url;
|
||||
|
||||
// Anti-MITM check: the first 8 bytes of both DTLS certificate fingerprints, fewer an interposer can
|
||||
// brute force with matching certificates. My local code must equal the peer's remote code and vice
|
||||
// versa, otherwise someone interposed on the signaling.
|
||||
@@ -438,12 +451,15 @@ function connected(
|
||||
pc: RTCPeerConnection,
|
||||
channel: RTCDataChannel,
|
||||
via: string,
|
||||
peer: string,
|
||||
events: Events,
|
||||
next?: () => void,
|
||||
next?: (reason: string) => void,
|
||||
key?: CryptoKey,
|
||||
): Handshake {
|
||||
events.log(`connected via ${via}`);
|
||||
events.log('waiting for the security check');
|
||||
if (key) events.status('start', 'Connected, checking the code');
|
||||
else events.status('wait', `Compare the security codes above with the ${peer}`);
|
||||
let done = false;
|
||||
const end = (reason: string) => {
|
||||
if (done) return;
|
||||
@@ -452,12 +468,12 @@ function connected(
|
||||
pc.close();
|
||||
if (!next) return events.error(reason);
|
||||
events.log(reason);
|
||||
next();
|
||||
next(reason);
|
||||
};
|
||||
// A vanished peer only closes the channel in Firefox, Chromium just fails the connection.
|
||||
channel.addEventListener('close', () => end('peer left before the transfer'));
|
||||
channel.addEventListener('close', () => end(`the ${peer} left before the transfer`));
|
||||
pc.addEventListener('connectionstatechange', () => {
|
||||
if (pc.connectionState === 'failed') end('peer left before the transfer');
|
||||
if (pc.connectionState === 'failed') end(`the ${peer} left before the transfer`);
|
||||
});
|
||||
return {
|
||||
checked: key
|
||||
@@ -507,6 +523,7 @@ async function sendFile(
|
||||
events.progress(read, file.size);
|
||||
} else if (message?.done === true && !stopped) {
|
||||
events.log('delivered');
|
||||
events.status('done', 'Delivered');
|
||||
events.progress(file.size, file.size);
|
||||
stop();
|
||||
} else if (typeof message?.error === 'string') {
|
||||
@@ -529,7 +546,10 @@ async function sendFile(
|
||||
await new Promise((resolve) => channel.addEventListener('open', resolve, { once: true }));
|
||||
}
|
||||
await handshake.checked;
|
||||
if (!accepted && open()) events.log("waiting for the receiver's security check");
|
||||
if (!accepted && open()) {
|
||||
events.log("waiting for the receiver's security check");
|
||||
events.status('wait', "Waiting for the receiver's security check");
|
||||
}
|
||||
while (open() && !accepted) await new Promise<void>((resolve) => (wake = resolve));
|
||||
if (!open()) return;
|
||||
|
||||
@@ -537,11 +557,13 @@ async function sendFile(
|
||||
offered = true;
|
||||
events.log(`offered ${file.name} (${file.size} bytes)`);
|
||||
events.log('waiting for the receiver to download');
|
||||
events.status('wait', 'Waiting for the receiver to download');
|
||||
while (open() && !sending) await new Promise<void>((resolve) => (wake = resolve));
|
||||
if (!open()) return;
|
||||
|
||||
handshake.start();
|
||||
events.log(`sending ${file.name}`);
|
||||
events.status('transfer', 'Sending');
|
||||
events.progress(0, file.size);
|
||||
channel.bufferedAmountLowThreshold = MAX_BUFFERED / 2;
|
||||
for (let offset = 0; offset < file.size; offset += CHUNK_SIZE) {
|
||||
@@ -558,6 +580,7 @@ async function sendFile(
|
||||
channel.send(chunk);
|
||||
}
|
||||
events.log('sent');
|
||||
if (open()) events.status('transfer', 'Sent, waiting for the receiver to save the rest');
|
||||
}
|
||||
|
||||
// Received files are streamed into the browser's download manager by public/sw.js, so a file never
|
||||
@@ -686,11 +709,13 @@ function receiveFile(
|
||||
if (data === 'failed') fail('the service worker refused it');
|
||||
if (data === 'finished') {
|
||||
events.log('download complete');
|
||||
events.status('done', 'Download complete');
|
||||
events.progress(meta!.size, meta!.size);
|
||||
reply({ done: true });
|
||||
}
|
||||
if (data === 'cancelled' && !ended) {
|
||||
events.log('download cancelled');
|
||||
events.status('stopped', 'Download cancelled');
|
||||
reply({ error: 'download cancelled' });
|
||||
}
|
||||
ended = true;
|
||||
@@ -708,6 +733,7 @@ function receiveFile(
|
||||
confirmed = true;
|
||||
reply({ ok: true });
|
||||
events.log('waiting for the sender');
|
||||
events.status('wait', 'Waiting for the sender');
|
||||
});
|
||||
|
||||
function receivedAll() {
|
||||
@@ -724,6 +750,7 @@ function receiveFile(
|
||||
signal.addEventListener('abort', () => fail('stopped'), { once: true });
|
||||
handshake.start();
|
||||
events.log(`receiving ${meta!.name}`);
|
||||
events.status('transfer', 'Receiving');
|
||||
events.progress(0, meta!.size);
|
||||
startDownload();
|
||||
reply({ start: true });
|
||||
@@ -741,6 +768,7 @@ function receiveFile(
|
||||
}
|
||||
meta = { name, size };
|
||||
events.log(`offered ${name} (${size} bytes)`);
|
||||
events.status('wait', 'Click Download to save the file');
|
||||
events.incoming({ name, size, download });
|
||||
} else if (downloading && !complete) {
|
||||
received += data.byteLength;
|
||||
@@ -795,12 +823,15 @@ function failUnconnected(
|
||||
// The sender offers, the receiver answers, no tracker involved.
|
||||
export async function createOffer(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the offer');
|
||||
const pc = await createPeerConnection(signal);
|
||||
const channel = pc.createDataChannel('file');
|
||||
channel.onopen = () => sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
channel.onopen = () =>
|
||||
sendFile(pc, channel, file, events, connected(pc, channel, 'manual exchange', 'receiver', events), signal);
|
||||
const wait = failUnconnected(pc, () => channel.readyState !== 'connecting', events, signal, 'receiver');
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
events.status('wait', 'Send the offer to the receiver and paste their answer below');
|
||||
|
||||
return {
|
||||
offer: btoa(pc.localDescription!.sdp),
|
||||
@@ -813,6 +844,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
||||
await pc.setRemoteDescription(description).catch(() => {
|
||||
throw new Error('not a valid answer to this offer, copy all of it');
|
||||
});
|
||||
events.status('start', 'Connecting to the receiver');
|
||||
wait(CONNECT_TIMEOUT);
|
||||
},
|
||||
};
|
||||
@@ -821,6 +853,7 @@ export async function createOffer(file: File, events: Events, signal: AbortSigna
|
||||
export async function answerOffer(offer: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
const description = decode(offer, 'offer');
|
||||
events.status('start', 'Creating the answer');
|
||||
await downloadsReady();
|
||||
const pc = await createPeerConnection(signal);
|
||||
let opened = false;
|
||||
@@ -828,7 +861,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
// The sender's file channel, anything more is none of ours.
|
||||
if (opened) return;
|
||||
opened = true;
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', events), signal);
|
||||
receiveFile(pc, channel, events, connected(pc, channel, 'manual exchange', 'sender', events), signal);
|
||||
};
|
||||
const wait = failUnconnected(pc, () => opened, events, signal, 'sender');
|
||||
await pc.setRemoteDescription(description).catch(() => {
|
||||
@@ -838,6 +871,7 @@ export async function answerOffer(offer: string, events: ReceiveEvents, signal:
|
||||
await pc.setLocalDescription();
|
||||
await gatherIce(pc);
|
||||
wait(TRACKER_WAIT);
|
||||
events.status('wait', 'Send the answer back to the sender, it connects once it has it');
|
||||
|
||||
return btoa(pc.localDescription!.sdp);
|
||||
}
|
||||
@@ -924,6 +958,7 @@ function noTracker(trackers: (Tracker | undefined)[]) {
|
||||
// receiver connected by then still gets its turn.
|
||||
export async function sendViaTracker(file: File, events: Events, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Creating the code');
|
||||
const code = randomCode();
|
||||
const { hash, key, sealing } = await secrets(code);
|
||||
const peerId = randomBinary(20);
|
||||
@@ -935,8 +970,17 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
let expired = false;
|
||||
// The latest offer that came while busy, answered once that peer is out.
|
||||
let waiting: (() => Promise<void>) | undefined;
|
||||
// Why the last receiver that answered didn't connect, if a missing public address explains it.
|
||||
// Why the last receiver that answered didn't connect.
|
||||
let hint: string | undefined;
|
||||
// Why the last receiver's turn ended without a transfer, shown until the next one connects.
|
||||
let failure: string | undefined;
|
||||
// Receivers answered, a failed one usually tries again right away.
|
||||
let attempts = 0;
|
||||
|
||||
const waitForReceiver = () =>
|
||||
failure
|
||||
? events.status('retry', `${failure}. Waiting for the receiver to try again`)
|
||||
: events.status('wait', 'Waiting for the receiver');
|
||||
|
||||
// Without a tracker no further receiver can find the share.
|
||||
const stranded = () => !shared && !busy && !trackers.some((tracker) => tracker.alive());
|
||||
@@ -955,11 +999,14 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
events.error(reason);
|
||||
};
|
||||
|
||||
function next() {
|
||||
// reason: why the receiver's turn ended, unless it was no receiver to speak of.
|
||||
function next(reason?: string) {
|
||||
busy = false;
|
||||
if (reason) failure = reason;
|
||||
if (signal.aborted) return;
|
||||
if (stranded()) return end(expired ? nobody() : noTracker(trackers));
|
||||
events.log('waiting for the next receiver');
|
||||
waitForReceiver();
|
||||
const offer = waiting;
|
||||
waiting = undefined;
|
||||
void offer?.();
|
||||
@@ -971,29 +1018,35 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
msg: { offer: { sdp: string }; peer_id: string; offer_id: string },
|
||||
) {
|
||||
busy = true;
|
||||
attempts++;
|
||||
events.log(`offer via ${url}`);
|
||||
if (failure) events.status('retry', `${failure}. Trying again, attempt ${attempts}`);
|
||||
else events.status('start', 'Receiver found, connecting');
|
||||
const pc = await createPeerConnection(signal);
|
||||
// Until the data channel opens this ends the turn, from then on connected does.
|
||||
let settled = false;
|
||||
// Shown until the next receiver connects, an unusable offer doesn't concern the user.
|
||||
let problem: string | undefined;
|
||||
const giveUp = (reason: string) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
events.log(reason);
|
||||
pc.close();
|
||||
next();
|
||||
next(problem);
|
||||
};
|
||||
const unconnected = () => {
|
||||
if (settled) return;
|
||||
hint = stunHint(pc, 'receiver');
|
||||
giveUp(hint ? `receiver did not connect: ${hint}` : 'receiver did not connect');
|
||||
hint = stunHint(pc, 'receiver') ?? BLOCKED;
|
||||
problem = `could not connect to the receiver: ${hint}`;
|
||||
giveUp(`receiver did not connect: ${hint}`);
|
||||
};
|
||||
const timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||
pc.ondatachannel = ({ channel }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
const handshake = connected(pc, channel, url, events, next, key);
|
||||
const handshake = connected(pc, channel, url, 'receiver', events, next, key);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
shared = true;
|
||||
@@ -1027,6 +1080,8 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
// The tracker at urls[i]. Receivers that come later walk on to the next one too, see receiveViaTracker.
|
||||
function join(i: number) {
|
||||
const url = urls[i]!;
|
||||
// A receiver's turn goes on without the tracker.
|
||||
if (!busy) events.status('start', `Connecting to ${host(url)}`);
|
||||
const tracker = trackerSocket(
|
||||
url,
|
||||
signal,
|
||||
@@ -1053,6 +1108,7 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
tracker.ws.onopen = () => {
|
||||
announce(tracker.ws, hash, peerId, { left: 0, event: 'started' });
|
||||
events.log(`waiting on ${url}`);
|
||||
if (!busy) waitForReceiver();
|
||||
};
|
||||
trackers.push(tracker);
|
||||
}
|
||||
@@ -1071,20 +1127,33 @@ export async function sendViaTracker(file: File, events: Events, signal: AbortSi
|
||||
// TRACKER_WAIT no offer is made or kept any more, a sender connected by then still gets its turn.
|
||||
export async function receiveViaTracker(code: string, events: ReceiveEvents, signal: AbortSignal) {
|
||||
events = live(events, signal);
|
||||
events.status('start', 'Looking for the sender');
|
||||
await downloadsReady();
|
||||
const { hash, key, sealing } = await secrets(code.trim());
|
||||
if (signal.aborted) return;
|
||||
const peerId = randomBinary(20);
|
||||
const urls = [...settings.trackers];
|
||||
// The current offer per tracker by its place in urls, its connection once made, its socket only
|
||||
// until the answer came. lost: the socket closed before that.
|
||||
type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean };
|
||||
// until the answer came. lost: the socket closed before that. empty: its tracker has no seeder.
|
||||
type Offer = { pc?: RTCPeerConnection; tracker?: Tracker; lost: boolean; empty?: boolean };
|
||||
const offers = new Map<number, Offer>();
|
||||
let isConnected = false;
|
||||
let started = false;
|
||||
let expired = false;
|
||||
// Why the last sender that answered didn't connect, if a missing public address explains it.
|
||||
// Why the last sender that answered didn't connect.
|
||||
let hint: string | undefined;
|
||||
// Why the last connection to the sender failed, shown until the next one connects.
|
||||
let failure: string | undefined;
|
||||
// Answers from the sender, after a failure it answers the replacement right away.
|
||||
let attempts = 0;
|
||||
// Every tracker reported no sender, the status says so until one has it again.
|
||||
let noSender = false;
|
||||
|
||||
const looking = (text: string) => {
|
||||
if (isConnected || started) return;
|
||||
if (failure) events.status('retry', `${failure}. Looking again`);
|
||||
else events.status('start', text);
|
||||
};
|
||||
|
||||
const nobody = () =>
|
||||
hint
|
||||
@@ -1106,11 +1175,13 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
for (const { tracker } of offers.values()) tracker?.close();
|
||||
});
|
||||
|
||||
const next = () => {
|
||||
const next = (reason: string) => {
|
||||
isConnected = false;
|
||||
failure = reason;
|
||||
if (signal.aborted) return;
|
||||
if (expired) return end(nobody());
|
||||
events.log('looking again');
|
||||
looking('Looking for the sender');
|
||||
for (const [i, { pc }] of offers) if (pc?.signalingState === 'closed') void offer(i);
|
||||
};
|
||||
|
||||
@@ -1141,14 +1212,16 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
};
|
||||
const unconnected = () => {
|
||||
if (pc.signalingState === 'closed') return;
|
||||
hint = stunHint(pc, 'sender');
|
||||
retry(hint ? `sender via ${url} did not connect: ${hint}` : `sender via ${url} did not connect`);
|
||||
hint = stunHint(pc, 'sender') ?? BLOCKED;
|
||||
failure = `could not connect to the sender: ${hint}`;
|
||||
retry(`sender via ${url} did not connect: ${hint}`);
|
||||
looking('Looking for the sender');
|
||||
};
|
||||
channel.onopen = () => {
|
||||
clearTimeout(timeout);
|
||||
if (isConnected || started) return pc.close();
|
||||
isConnected = true;
|
||||
const handshake = connected(pc, channel, url, events, next, key);
|
||||
const handshake = connected(pc, channel, url, 'sender', events, next, key);
|
||||
const start = () => {
|
||||
handshake.start();
|
||||
started = true;
|
||||
@@ -1185,7 +1258,19 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
// The tracker's reply to an announcement, complete counts the seeders. Without one the
|
||||
// sender isn't here, or no longer.
|
||||
if (msg.answer === undefined && msg.offer === undefined) {
|
||||
if (!(msg.complete > 0)) walk(i);
|
||||
entry.empty = !(msg.complete > 0);
|
||||
if (entry.empty) walk(i);
|
||||
// Every tracker asked and none has it: a wrong code, or the share is over. A sender that
|
||||
// shows up later may be busy with another receiver, its answer can take a while.
|
||||
const everywhere = [...offers.values()].every((other) => other.lost || other.empty);
|
||||
const none = offers.size === urls.length && everywhere;
|
||||
if (none !== noSender && !isConnected && !started) {
|
||||
if (none)
|
||||
events.status('retry', 'No sender with this code on any tracker. Check the code, still looking');
|
||||
else if (failure) events.status('retry', `${failure}. Looking again`);
|
||||
else events.status('wait', `Found the share on ${host(url)}, waiting for the sender to answer`);
|
||||
}
|
||||
noSender = none;
|
||||
return;
|
||||
}
|
||||
if (msg.offer_id !== offerId || typeof msg.answer?.sdp !== 'string') return;
|
||||
@@ -1195,6 +1280,12 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
if (pc.signalingState === 'closed' || !tracker.alive()) return;
|
||||
if (answer === undefined) return events.log(`answer without the code via ${url}`);
|
||||
events.log(`answer via ${url}`);
|
||||
attempts++;
|
||||
noSender = false;
|
||||
if (!isConnected && !started) {
|
||||
if (failure) events.status('retry', `${failure}. Trying again, attempt ${attempts}`);
|
||||
else events.status('start', 'Sender found, connecting');
|
||||
}
|
||||
tracker.close();
|
||||
timeout = setTimeout(unconnected, CONNECT_TIMEOUT);
|
||||
pc.setRemoteDescription({ type: 'answer', sdp: answer }).catch(() => retry(`unusable answer via ${url}`));
|
||||
@@ -1212,6 +1303,7 @@ export async function receiveViaTracker(code: string, events: ReceiveEvents, sig
|
||||
tracker.ws.onopen = () => {
|
||||
hello('started');
|
||||
events.log(`looking on ${url}`);
|
||||
looking(`Looking for the sender on ${host(url)}`);
|
||||
};
|
||||
})
|
||||
// Closed in the meantime, nothing to report then.
|
||||
|
||||
+86
-22
@@ -193,6 +193,10 @@ section p {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
section p[role='alert'] {
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
|
||||
header label {
|
||||
color: var(--color-text);
|
||||
}
|
||||
@@ -377,54 +381,114 @@ label strong,
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Progress and what went wrong, below the file on both sides */
|
||||
/* How the session is doing, below the file on its side. Until the transfer starts a pill passes
|
||||
through the bar, blue, or pink while it tries again after a failure. Then the transfer's progress,
|
||||
green once done, muted once stopped, pink for an error. The line below says what. */
|
||||
|
||||
article > p[role='alert'] {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
[data-phase] {
|
||||
--bar: var(--color-primary);
|
||||
|
||||
article > p[role='alert']::first-letter {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
p:has(> progress) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
[data-phase='retry'],
|
||||
[data-phase='error'] {
|
||||
--bar: var(--color-secondary);
|
||||
}
|
||||
|
||||
[data-phase='done'] {
|
||||
--bar: var(--color-success);
|
||||
}
|
||||
|
||||
[data-phase='stopped'] {
|
||||
--bar: var(--color-text-muted);
|
||||
}
|
||||
|
||||
[data-phase] p {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
font-size: var(--text-sm);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
progress {
|
||||
flex: 1;
|
||||
/* The send session's file, above its bar once the user picked another one */
|
||||
#send-file {
|
||||
color: var(--color-text);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* A block, a flex container has no first letter. Flex items do, they are blocks. */
|
||||
[data-phase] p[role='alert'] {
|
||||
display: block;
|
||||
color: var(--color-secondary-text);
|
||||
}
|
||||
|
||||
[data-phase] p[role='alert']::first-letter,
|
||||
[data-phase] [role='status'] > :first-child::first-letter {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* The track, the progress inside it fills it or, without a value, is the pill */
|
||||
[data-phase] > div {
|
||||
height: 0.5rem;
|
||||
appearance: none;
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: var(--color-input);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
progress {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
}
|
||||
|
||||
progress::-webkit-progress-bar {
|
||||
background: var(--color-input);
|
||||
background: none;
|
||||
}
|
||||
|
||||
progress::-webkit-progress-value {
|
||||
background: var(--color-primary);
|
||||
background: var(--bar);
|
||||
}
|
||||
|
||||
progress::-moz-progress-bar {
|
||||
background: var(--color-primary);
|
||||
background: var(--bar);
|
||||
}
|
||||
|
||||
progress[value='100']::-webkit-progress-value {
|
||||
background: var(--color-success);
|
||||
progress:indeterminate {
|
||||
width: 25%;
|
||||
border-radius: 999px;
|
||||
background: var(--bar);
|
||||
animation: pass 2584ms linear infinite;
|
||||
}
|
||||
|
||||
progress[value='100']::-moz-progress-bar {
|
||||
background: var(--color-success);
|
||||
progress:indeterminate::-moz-progress-bar {
|
||||
background: none;
|
||||
}
|
||||
|
||||
/* Its own width is a quarter of the track's: from just before it to just past it */
|
||||
@keyframes pass {
|
||||
from {
|
||||
translate: -100%;
|
||||
}
|
||||
|
||||
to {
|
||||
translate: 400%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
progress:indeterminate {
|
||||
translate: 150%;
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Switch, like Pico's role="switch" */
|
||||
|
||||
Reference in new issue
Block a user